qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,547,913
|
<p>I am fairly new to javscript and this might sound like an easy question. I have two datasets that have the same column and I would like to join them together.</p>
<p>The datasets look sth like this:</p>
<pre><code>const dataset1= [{state: 'France', value: 1001.8},
{state: 'Germany', value: 1236.8},..,]
const dataset2= [{state: 'France', value: 5320},
{state: 'Germany', value: 5670},..,]
</code></pre>
<p>The values on both datasets represent different things. I want to achieve sth like this:</p>
<pre><code>[{state: 'France', value: 1001.8, value2: 5320},
{state: 'Germany', value: 1236.8, value2: 5670},...]
</code></pre>
<p>Would really appreciate it if someone could give me a hint on how to do this!</p>
|
[
{
"answer_id": 74548839,
"author": "Francesco Rosso",
"author_id": 9630238,
"author_profile": "https://Stackoverflow.com/users/9630238",
"pm_score": 0,
"selected": false,
"text": "plugins {\n id 'application'\n id 'java'\n id 'eclipse'\n}\n\nrepositories {\n mavenCentral()\n}\n\ndependencies {\n // Use JUnit Jupiter for testing.\n testImplementation 'org.junit.jupiter:junit-jupiter:5.7.2'\n\n // This dependency is used by the application.\n implementation 'org.slf4j:slf4j-api:2.0.4'\n implementation 'ch.qos.logback:logback-classic:1.4.5'\n\n implementation 'jakarta.enterprise:jakarta.enterprise.cdi-api:3.0.1'\n implementation 'jakarta.ws.rs:jakarta.ws.rs-api:3.0.1'\n\n implementation 'org.jboss.weld.se:weld-se-core:5.1.0.Final'\n implementation 'org.jboss.weld.servlet:weld-servlet-core:5.1.0.Final'\n\n implementation 'org.glassfish.grizzly:grizzly-http-server:4.0.0'\n\n implementation 'org.glassfish.jersey.core:jersey-server:3.1.0'\n implementation 'org.glassfish.jersey.containers:jersey-container-grizzly2-http:3.1.0'\n implementation 'org.glassfish.jersey.ext.cdi:jersey-weld2-se:3.1.0'\n implementation 'org.glassfish.jersey.inject:jersey-hk2:3.1.0'\n implementation 'org.glassfish.jersey.media:jersey-media-json-jackson:3.1.0'\n\n implementation 'com.fasterxml.jackson.core:jackson-core:2.12.7'\n implementation 'com.fasterxml.jackson.core:jackson-databind:2.12.7'\n}\n\napplication {\n // Define the main class for the application.\n mainClass = 'it.gym.StartApp'\n}\n\ntasks.named('test') {\n // Use JUnit Platform for unit tests.\n useJUnitPlatform()\n}\n package it.gym;\n\nimport java.net.URI;\n\nimport org.glassfish.grizzly.http.server.HttpServer;\nimport org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;\nimport org.glassfish.jersey.server.ResourceConfig;\nimport org.jboss.weld.environment.se.Weld;\n\npublic class StartApp {\n\n public static void main(String[] args) {\n Weld weld = new Weld();\n weld.initialize();\n\n ResourceConfig resourceConfig = new ResourceConfig();\n resourceConfig.packages(\"it.gym\");\n\n final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(URI.create(\"http://localhost:9000/\"),\n resourceConfig);\n\n try {\n Thread.sleep(1000 * 1000);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n\n server.shutdownNow();\n weld.shutdown();\n }\n}\n"
},
{
"answer_id": 74554923,
"author": "Joakim Erdfelt",
"author_id": 775715,
"author_profile": "https://Stackoverflow.com/users/775715",
"pm_score": 1,
"selected": false,
"text": "jetty-11.0.x implementation 'org.slf4j:slf4j-api:2.0.4'\n implementation 'ch.qos.logback:logback-classic:1.4.5'\n\n implementation 'org.eclipse.jetty:jetty-servlet:11.0.12'\n implementation 'org.eclipse.jetty:jetty-cdi:11.0.12'\n \n implementation 'org.jboss.weld.servlet:weld-servlet-core:4.0.3.Final'\n\n implementation 'org.glassfish.jersey.containers:jersey-container-servlet-core:3.0.4'\n implementation 'org.glassfish.jersey.media:jersey-cdi2-se:3.0.4'\n implementation 'org.glassfish.jersey.media:jersey-media-json-jackson:3.0.4'\n jetty-cdi context.addEventListener(Listener.using(weld));\ncontext.setAttribute(\n WeldServletLifecycle.BEAN_MANAGER_ATTRIBUTE_NAME,\n container.getBeanManager());\n import org.eclipse.jetty.cdi.CdiServletContainerInitializer;\nimport org.eclipse.jetty.cdi.CdiDecoratingListener;\nimport org.jboss.weld.environment.servlet.EnhancedListener;\n\ncontext.setInitParameter(\n CdiServletContainerInitializer.CDI_INTEGRATION_ATTRIBUTE, \n CdiDecoratingListener.MODE);\ncontext.addServletContainerInitializer(new CdiServletContainerInitializer());\ncontext.addServletContainerInitializer(new EnhancedListener());\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17749183/"
] |
74,547,917
|
<p>In vim, <code>/string</code> is to search a <code>string</code>, <code>:s/string/replace</code> is to replace <code>string</code> with <code>replace</code>.</p>
<p>By typing <code>/</code> and hitting up/down, one can view history searches. Same with replacing.</p>
<p>But is there a way to make replacing use history of searching, that is to replace the string that has just been searched for?</p>
<p>I'm trying to use regex to replace <code>/****ABC****/</code> comments with <code>/**** ABC *****/</code> to pass coding style check, the number of <code>*</code> is variable and <code>ABC</code> contains several words.</p>
<p>I used searching instead of replacing to try to find the right regex, which has a lot of <code>\\*[]</code>.</p>
<p>(I'd like to paste my result here but it keeps pompting up uploading image box...)</p>
<p>I do understand that I can copy the regex somewhere else and paste it back after typing <code>:%s/</code>, but what if I'm using non GUI vim? Is there a feature that helps with this or will I have to write the regex on paper?</p>
|
[
{
"answer_id": 74548225,
"author": "M. Desjardins",
"author_id": 1507350,
"author_profile": "https://Stackoverflow.com/users/1507350",
"pm_score": 0,
"selected": false,
"text": ":%s// :h :s :global :global :s /search <c-r>/ :%s/"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3665518/"
] |
74,547,926
|
<p>In my Python lab, I need to ask the user how many numbers to store; have them enter said numbers individually and store them in a file named numbers1.txt. Then again, repeat this process but store the numbers in a file named numbers2.txt. From there I had to write some code that would read a line from one file and a line from the other file, the 2 integers are multiplied together and their value is added to a variable called scalar_product which was initialized at 0. The code should stop when one of the files has reached end of file.</p>
<p>The code I have so far is as follows:</p>
<pre><code> def main():
num = int(input("How many numbers would you like to store"))
numbers1 = open('numbers1.txt', 'w')
for count in range(1, num + 1):
nums = input("Enter each number individually {}:".format(count))
numbers1.write(str(nums) + "\n")
numbers1.close()
def main_two():
num2 = int(input("How many numbers would you like to store"))
numbers2 = open('numbers2.txt', 'w')
for count in range(1, num2 + 1):
nums2 = input("Enter each number individually {}:".format(count))
numbers2.write(str(nums2) + "\n")
numbers2.close()
main()
main_two()
numfile1 = open("numbers1.txt","r")
numfile2 = open("numbers2.txt","r")
scalar_product = 0
number1 = numfile1.readline()
number2 = numfile2.readline()
while number1 != "" and number2 != "":
scalar_product += int(number1) * int(number2)
number1 = numfile1.readline()
number2 = numfile2.readline()
numfile1.close()
numfile2.close()
</code></pre>
<p>I have no issues with the first few steps, Python prompts the users for the amount of numbers they would like to store but when I reach the section on multiplying the 2 values from numbers1.txt and numbers2.txt I get the following ValueError:</p>
<pre><code> How many numbers would you like to store2
Enter each number individually 1:4
Enter each number individually 2:5
How many numbers would you like to store3
Enter each number individually 1:4
Enter each number individually 2:6
Enter each number individually 3:3
Traceback (most recent call last):
File "/Users/jake./PycharmProjects/CH9_Munyak_Jacob/ReadingProcessFiles.py", line 31, in <module>
number1 = numfile1.readline()
ValueError: I/O operation on closed file.
Process finished with exit code 1
</code></pre>
<p>Can anybody point me in the right direction?</p>
<p>I am not sure why It's a closed file when I re-opened it in line 24 and line 25</p>
|
[
{
"answer_id": 74548265,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 0,
"selected": false,
"text": "close with zip scalar_product = 0\nwith open(\"numbers1.txt\") as numfile1, open(\"numbers2.txt\") as numfile2:\n for number1, number2 in zip(numfile1, numfile2):\n scalar_product += int(number1) * int(number2)\n with open(\"numbers1.txt\") as numfile1, open(\"numbers2.txt\") as numfile2:\n scalar_product = sum(int(x) * int(y) for x, y in zip(numfile1, numfile2))\n"
},
{
"answer_id": 74548300,
"author": "0x0fba",
"author_id": 20339407,
"author_profile": "https://Stackoverflow.com/users/20339407",
"pm_score": 1,
"selected": false,
"text": "while number1 != \"\" and number2 != \"\":\n scalar_product += int(number1) * int(number2)\n number1 = numfile1.readline()\n number2 = numfile2.readline()\n\n# close files at the end\nnumfile1.close()\nnumfile2.close()\n"
},
{
"answer_id": 74548772,
"author": "Ammar_Asim_23",
"author_id": 18134093,
"author_profile": "https://Stackoverflow.com/users/18134093",
"pm_score": 0,
"selected": false,
"text": "#This will be a quick fix for your problem\nwith open(\"numbers1.txt\") as numfile1:\n with open(\"numbers2.txt\", \"r\") as numfile2:\n scalar_product = 0\n number1 = numfile1.readline()\n number2 = numfile2.readline()\n while number1 != \"\" and number2 != \"\":\n scalar_product += int(number1) * int(number2)\n number1 = numfile1.readline()\n number2 = numfile2.readline()\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20524919/"
] |
74,547,933
|
<p>I have a JSON file that is given as:</p>
<pre><code>{
"Person": "true",
"Age": "true",
"Location": "false",
"Phone": "true"
}
</code></pre>
<p>I am able to read it in Unity by using the code below. I am using SimpleJSON library.</p>
<pre><code>using System.Collections;
using System.Collections.Generic;
using System.IO;
using SimpleJSON;
using UnityEngine;
using UnityEngine.UI;
public class ReadWriteScene : MonoBehaviour {
public string jsonFile;
JSONNode itemsData;
string path;
// Start is called before the first frame update
void Start () {
path = Path.Combine (Application.streamingAssetsPath, "Settings.json");
if (File.Exists (path)) {
jsonFile = File.ReadAllText (path);
DeserializePages ();
}
}
void Update () {
}
public void DeserializePages () {
itemsData = JSON.Parse (jsonFile);
var parseJSON = JSON.Parse (jsonFile);
Debug.Log(parseJSON["Phone"].Value);
}
}
</code></pre>
<p>But I do not know how to write or make changes to the JSON via code? For example, how do I change the attribute "Age" to "false"?</p>
|
[
{
"answer_id": 74548520,
"author": "Mauro Vanetti",
"author_id": 581285,
"author_profile": "https://Stackoverflow.com/users/581285",
"pm_score": 1,
"selected": false,
"text": "itemsData[\"Age\"] = \"false\";\n"
},
{
"answer_id": 74548747,
"author": "Mykhailo Svyrydovych",
"author_id": 13251244,
"author_profile": "https://Stackoverflow.com/users/13251244",
"pm_score": 0,
"selected": false,
"text": "itemsData[\"Age\"] = \"false\";\nFile.WriteAllTextAsync(path, itemsData.ToString());\n"
},
{
"answer_id": 74548768,
"author": "Vika",
"author_id": 17561671,
"author_profile": "https://Stackoverflow.com/users/17561671",
"pm_score": 1,
"selected": true,
"text": "public void SaveData(){\n JSONObject json = new JSONObject();\n json.Add(\"Person\", \"true\");\n json.Add(\"Age\", \"false\");\n json.Add(\"Location\", \"true\");\n json.Add(\"Phone\", \"true\");\n\n File.WriteAllText(path, json.ToString());\n }\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17561671/"
] |
74,547,950
|
<p>I have a button with a click event called <code>handleCount()</code>. I have 3 functions, <code>fun1()</code>, <code>fun2()</code>, <code>fun3()</code>. I'm calling <code>fun1()</code>, <code>fun2()</code>, <code>fun3()</code> in <code>handleCount()</code> based on <code>count</code> value.</p>
<p>If <code>count</code> value is 0 then <code>fun1</code> should be called, if count value is 1 then <code>fun1()</code> and <code>fun2()</code> should be called and if count value is 2 then <code>fun1()</code>, <code>fun2()</code>, <code>fun3()</code> should be called and its working as expected.</p>
<p>The issue is that I want them to be called one after another with each click like when <code>count === 2</code> then <code>fun1()</code> should be called first and then on 2 click <code>fun2()</code> should be called and for 3rd click <code>fun3()</code> should be called.</p>
<p>How can I achieve this? I would like to know logic to implement this.</p>
<p>Note I'm not incrementing/decrementing <code>count</code> value because I get <code>count</code> value from an API.</p>
<pre class="lang-js prettyprint-override"><code>var count = 2;
const function1 = () => {
console.log("Function one");
}
const function2 = () => {
console.log("Function two")
}
const function3 = () => {
console.log("Function three")
}
const handleCount = () => {
if (count === 0) {
function1();
}
if (count === 1) {
function1();
function2();
}
if (count === 2) {
function1();
function2();
function3();
}
}
return (
<>
<button onClick={handleCount}></button>
</>
)
</code></pre>
|
[
{
"answer_id": 74548520,
"author": "Mauro Vanetti",
"author_id": 581285,
"author_profile": "https://Stackoverflow.com/users/581285",
"pm_score": 1,
"selected": false,
"text": "itemsData[\"Age\"] = \"false\";\n"
},
{
"answer_id": 74548747,
"author": "Mykhailo Svyrydovych",
"author_id": 13251244,
"author_profile": "https://Stackoverflow.com/users/13251244",
"pm_score": 0,
"selected": false,
"text": "itemsData[\"Age\"] = \"false\";\nFile.WriteAllTextAsync(path, itemsData.ToString());\n"
},
{
"answer_id": 74548768,
"author": "Vika",
"author_id": 17561671,
"author_profile": "https://Stackoverflow.com/users/17561671",
"pm_score": 1,
"selected": true,
"text": "public void SaveData(){\n JSONObject json = new JSONObject();\n json.Add(\"Person\", \"true\");\n json.Add(\"Age\", \"false\");\n json.Add(\"Location\", \"true\");\n json.Add(\"Phone\", \"true\");\n\n File.WriteAllText(path, json.ToString());\n }\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20338321/"
] |
74,547,956
|
<p><code>window.open(URL, '_blank')</code></p>
<p>this is not working with local file
it's give error "Not allowed to load local resource"</p>
<p>my local file path is like bellow</p>
<p>file:///var/www/html/proj/proj.pdf</p>
|
[
{
"answer_id": 74548520,
"author": "Mauro Vanetti",
"author_id": 581285,
"author_profile": "https://Stackoverflow.com/users/581285",
"pm_score": 1,
"selected": false,
"text": "itemsData[\"Age\"] = \"false\";\n"
},
{
"answer_id": 74548747,
"author": "Mykhailo Svyrydovych",
"author_id": 13251244,
"author_profile": "https://Stackoverflow.com/users/13251244",
"pm_score": 0,
"selected": false,
"text": "itemsData[\"Age\"] = \"false\";\nFile.WriteAllTextAsync(path, itemsData.ToString());\n"
},
{
"answer_id": 74548768,
"author": "Vika",
"author_id": 17561671,
"author_profile": "https://Stackoverflow.com/users/17561671",
"pm_score": 1,
"selected": true,
"text": "public void SaveData(){\n JSONObject json = new JSONObject();\n json.Add(\"Person\", \"true\");\n json.Add(\"Age\", \"false\");\n json.Add(\"Location\", \"true\");\n json.Add(\"Phone\", \"true\");\n\n File.WriteAllText(path, json.ToString());\n }\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8138415/"
] |
74,547,987
|
<p>I was using public repo for wso2is i.e wso2/wso2is:5.10.0 however when I try to upgrade to 6.0.0 it does not let me pull the image. Looks like 6.0.0 is not on the public repo. How do I get 6.0.0, do we need to have active subscription to use the private wso2 ?</p>
|
[
{
"answer_id": 74548520,
"author": "Mauro Vanetti",
"author_id": 581285,
"author_profile": "https://Stackoverflow.com/users/581285",
"pm_score": 1,
"selected": false,
"text": "itemsData[\"Age\"] = \"false\";\n"
},
{
"answer_id": 74548747,
"author": "Mykhailo Svyrydovych",
"author_id": 13251244,
"author_profile": "https://Stackoverflow.com/users/13251244",
"pm_score": 0,
"selected": false,
"text": "itemsData[\"Age\"] = \"false\";\nFile.WriteAllTextAsync(path, itemsData.ToString());\n"
},
{
"answer_id": 74548768,
"author": "Vika",
"author_id": 17561671,
"author_profile": "https://Stackoverflow.com/users/17561671",
"pm_score": 1,
"selected": true,
"text": "public void SaveData(){\n JSONObject json = new JSONObject();\n json.Add(\"Person\", \"true\");\n json.Add(\"Age\", \"false\");\n json.Add(\"Location\", \"true\");\n json.Add(\"Phone\", \"true\");\n\n File.WriteAllText(path, json.ToString());\n }\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19557539/"
] |
74,547,994
|
<p>I have this start timer function</p>
<pre><code>async startTimer() {
this.count = 30;
for (var i = 30; i >= 0; i--) {
await new Promise((f) => setTimeout(f, 1000));
this.count = i;
}
}
</code></pre>
<p>which gets started by calling <code>this.startTimer()</code> but when i try to set <code>this.count=0</code> to stop the timer it doesn't stop rather than when i run <code>this.startTimer</code> again old one also run.</p>
<p>Any solution please. Thanks</p>
|
[
{
"answer_id": 74548520,
"author": "Mauro Vanetti",
"author_id": 581285,
"author_profile": "https://Stackoverflow.com/users/581285",
"pm_score": 1,
"selected": false,
"text": "itemsData[\"Age\"] = \"false\";\n"
},
{
"answer_id": 74548747,
"author": "Mykhailo Svyrydovych",
"author_id": 13251244,
"author_profile": "https://Stackoverflow.com/users/13251244",
"pm_score": 0,
"selected": false,
"text": "itemsData[\"Age\"] = \"false\";\nFile.WriteAllTextAsync(path, itemsData.ToString());\n"
},
{
"answer_id": 74548768,
"author": "Vika",
"author_id": 17561671,
"author_profile": "https://Stackoverflow.com/users/17561671",
"pm_score": 1,
"selected": true,
"text": "public void SaveData(){\n JSONObject json = new JSONObject();\n json.Add(\"Person\", \"true\");\n json.Add(\"Age\", \"false\");\n json.Add(\"Location\", \"true\");\n json.Add(\"Phone\", \"true\");\n\n File.WriteAllText(path, json.ToString());\n }\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3653474/"
] |
74,547,995
|
<p>I have created some code to search through a string and return True if there is an emoji in the string. The strings are found in a column in a pandas dataframe, and one can assume the string and the length of the dataframe could be arbitrarily long. I then create a new column in my dataframe with these boolean results.</p>
<p>Here is my code:</p>
<pre><code>import emoji
contains_emoji = []
for row in df['post_text']:
emoji_found = False
for char in row:
if emoji.is_emoji(char):
emoji_found = True
break
contains_emoji.append(emoji_found)
df['has_emoji'] = contains_emoji
</code></pre>
<p>In an effort to get slicker, I was wondering if anyone could recommend a faster, shorter, or more pythonic way of searching like this?</p>
|
[
{
"answer_id": 74548113,
"author": "ScottC",
"author_id": 20174226,
"author_profile": "https://Stackoverflow.com/users/20174226",
"pm_score": 3,
"selected": true,
"text": "emoji.emoji_count() import emoji\n\n# Create example dataframe\ndf = pd.DataFrame({'post_text':['', '', 'text ', 'abc']})\n\n# Create column based on emoji within text\ndf['has_emoji'] = df['post_text'].apply(lambda x: emoji.emoji_count(x) > 0)\n\n# print dataframe\nprint(df)\n post_text has_emoji\n0 True\n1 True\n2 text True\n3 abc False\n"
},
{
"answer_id": 74548356,
"author": "najeem",
"author_id": 3679377,
"author_profile": "https://Stackoverflow.com/users/3679377",
"pm_score": 2,
"selected": false,
"text": "df[\"has_emoji\"] = df.post_text.apply(emoji.emoji_count) > 0\n"
},
{
"answer_id": 74548602,
"author": "ZachW",
"author_id": 8462327,
"author_profile": "https://Stackoverflow.com/users/8462327",
"pm_score": 1,
"selected": false,
"text": "df['has_emoji'] = df['post_text'].str.contains(r'[\\U0001f600-\\U0001f650]')\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10138766/"
] |
74,548,015
|
<p>I'd like to emphasize where a web application is loaded from: the local development environment vs a test or production environment.
To keep things simple, the mechanism should work just on CSS. But so far my CSS is a static file.</p>
<p>Is it possible to write a CSS that evaluates on the browser what background color to use, maybe based on the URL it was loaded from (localhost vs other hosts)?</p>
<p>Somehow I am hoping to get a solution based on <a href="https://www.w3.org/TR/css-conditional-5/#when-rule" rel="nofollow noreferrer">CSS Conditional Rules</a>.</p>
|
[
{
"answer_id": 74548153,
"author": "FUZIION",
"author_id": 13050564,
"author_profile": "https://Stackoverflow.com/users/13050564",
"pm_score": 3,
"selected": true,
"text": "if (window.location.href.indexOf(\"stackoverflow\") > -1) {\n document.body.style.backgroundColor = 'red';\n} else {\n document.body.style.backgroundColor = 'blue';\n} location.host if (window.location.host.indexOf(\"localhost\") > -1) {\n document.body.style.backgroundColor = 'red';\n} else {\n document.body.style.backgroundColor = 'blue';\n}"
},
{
"answer_id": 74549333,
"author": "Hiran Chaudhuri",
"author_id": 4222206,
"author_profile": "https://Stackoverflow.com/users/4222206",
"pm_score": 0,
"selected": false,
"text": "public class App extends UI implements View {\n\n @Override\n protected void init(VaadinRequest request) {\n if (\"127.0.0.1\".equals(request.getRemoteAddr()) || \"localhost\".equals(request.getRemoteAddr())) {\n this.addStyleName(\"dev-environment\");\n }\n }\n}\n // emphasize we are on localhost. The application sets the class name 'dev-environment' in this case\n.dev-environment {\n background-color: #EEF0FF;\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4222206/"
] |
74,548,069
|
<p>I have a boolean BehaviorSubject whose value I want to use in my template:</p>
<pre><code>isLoggedIn$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
</code></pre>
<p>in ngOnInit, I subscribe to it:</p>
<pre><code>this.isLoggedIn$.subscribe((result) => {
console.log('result', result);
});
</code></pre>
<p>Following that (in the ngOnInit), I have a service call that returns a promise. When that is done, I set the behavior subject value:</p>
<pre><code> this.authService.isLoggedIn().then((loggedIn) => {
if (loggedIn) {
this.isLoggedIn$.next(loggedIn);
console.log('loggedIn', loggedIn);
// set the user model value here...
}
});
</code></pre>
<p>Lastly, I am displaying this value in the template:</p>
<pre><code><span>{{ isLoggedIn$ | async }}</span>
</code></pre>
<p>However, even though the console is showing the value changing, the template is not updating. I tried ngAfterViewInit and change detection and nothing seems to work. I assume the reason the value isn't updating in the template is becasue angular doesn't think anything has changed when the behavior subject is updated.</p>
<p>Am I missing something?</p>
<p>The problem is it might take a second or two to get the value back from the authService.isLoggedIn promise and if it is delayed longer that, the template wont display data (login info, like the user name) from the promise. The only thing that works is if I use a setTimeout() wrapper around the service call, which I would prefer not to do.</p>
<p>Any suggestions?</p>
<p><strong>EDIT</strong>: here is the whole component, adding the Observable as suggested by Brandon. Still doesn't work though:</p>
<pre><code>import { Component, OnInit } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { IUserModel } from './_interfaces/user';
import { AppService } from './_services/app.service';
import { AuthService } from './_services/auth.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
apiUser?: IUserModel;
isLoggedIn$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
isLoggedInOb: Observable<boolean> = new Observable<boolean>;
constructor(
private readonly authService: AuthService,
private readonly appService: AppService) {
}
ngOnInit(): void {
this.isLoggedInOb.subscribe((result) => {
this.isLoggedIn = result;
console.log('result', result);
});
setTimeout(() => {
this.authService.isLoggedIn().then((loggedIn) => {
this.isLoggedIn$.next(loggedIn);
this.isLoggedInOb = this.isLoggedIn$.asObservable();
console.log('loggedIn', loggedIn);
this.appService.lastActivityDatetimeSubject$.subscribe((data) => {
this.lastActivityDatetime = data;
});
});
}, 0);
this.appService.apiUserSubject$.subscribe((data) => {
this.apiUser = data;
});
}
login(): void {
this.authService.login();
}
logout(): void {
this.authService.logout();
}
}
</code></pre>
<p>If I set the setTimeout to 1000 milliseconds, it works but not if I remove the setTimeout function.</p>
<p>Here is the template:</p>
<pre><code><header>
<div class="header-group-1">
<a href="index.html" class="header-logo-link">
<img src="assets/images/logo.png" class="header-logo-img" alt="Company Logo" />
</a>
<div class="header-logo-text-wrapper">
<span class="header-logo-text-top">Company Name</span>
</div>
</div>
<div>
<div class="header-group-2">
<div class="header-app-name">
<span>App Name</span>
</div>
<div class="header-greeting">
<span *ngIf="apiUser && isLoggedIn && apiUser.FirstName">Hello {{apiUser.FirstName}} {{apiUser.LastName}}!</span>
<button class="focus-dark" *ngIf="!isLoggedIn" mat-stroked-button (click)="login()">Login</button>
<button class="focus-dark" *ngIf="isLoggedIn" mat-stroked-button (click)="logout()">Logout</button>
{{ isLoggedInOb | async }} <--- this is what I am trying to have updated when the behavior subject is updated
</div>
</div>
</div>
</header>
<div class="router-outlet-content" role="main">
<router-outlet></router-outlet>
</div>
<footer class="footer" role="contentinfo">
<div class="footer-first-row">
<a href="/disclaimer">Disclaimer</a>
<span class="divider" aria-hidden="true">|</span>
<a href="/privacy-policy">Privacy Policy</a>
<span class="divider" aria-hidden="true">|</span>
<a href="/terms-conditions">Terms and Conditions</a>
</div>
</footer>
</code></pre>
|
[
{
"answer_id": 74548153,
"author": "FUZIION",
"author_id": 13050564,
"author_profile": "https://Stackoverflow.com/users/13050564",
"pm_score": 3,
"selected": true,
"text": "if (window.location.href.indexOf(\"stackoverflow\") > -1) {\n document.body.style.backgroundColor = 'red';\n} else {\n document.body.style.backgroundColor = 'blue';\n} location.host if (window.location.host.indexOf(\"localhost\") > -1) {\n document.body.style.backgroundColor = 'red';\n} else {\n document.body.style.backgroundColor = 'blue';\n}"
},
{
"answer_id": 74549333,
"author": "Hiran Chaudhuri",
"author_id": 4222206,
"author_profile": "https://Stackoverflow.com/users/4222206",
"pm_score": 0,
"selected": false,
"text": "public class App extends UI implements View {\n\n @Override\n protected void init(VaadinRequest request) {\n if (\"127.0.0.1\".equals(request.getRemoteAddr()) || \"localhost\".equals(request.getRemoteAddr())) {\n this.addStyleName(\"dev-environment\");\n }\n }\n}\n // emphasize we are on localhost. The application sets the class name 'dev-environment' in this case\n.dev-environment {\n background-color: #EEF0FF;\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/296848/"
] |
74,548,070
|
<p>I have an array of shapes created in a for loop and want to assign simple code to each of them as "yes/no" buttons.</p>
<p>The code that creates the array of buttons is as follows:</p>
<pre><code> Dim i As Integer
Dim j As Integer
Dim k As Integer
For i = 1 To 3
For j = 2 To 17
ActiveSheet.Shapes.addshape(msoShapeRectangle, Cells(j, i).Left + 0, _
Cells(j, i).Top + 0, Cells(j, i).Width, Cells(j, i).Height).Select
Next j
Next i
</code></pre>
<p>I would like to be able to assign code to each of the shapes as they are created but do not know how. What I want the code to do for each shape looks like the below. I want the shapes to react when clicked and cycle through yes/no/blank text in each of the shapes. The general logic of the code is below</p>
<pre><code> value = value +1
if value = 1, then "yes" and green
if value = 2, then "no" and red
if value = 3, then value = 0 and blank and grey
</code></pre>
<p>Thank you in advance for your help</p>
|
[
{
"answer_id": 74552240,
"author": "Tim Williams",
"author_id": 478884,
"author_profile": "https://Stackoverflow.com/users/478884",
"pm_score": 1,
"selected": false,
"text": "Option Explicit\n\nSub Tester()\n \n Dim i As Long, j As Long, k As Long\n Dim addr As String, shp As Shape\n\n For i = 1 To 3\n For j = 2 To 17\n With ActiveSheet.Cells(j, i)\n Set shp = .Parent.Shapes.AddShape(msoShapeRectangle, .Left + 0, _\n .Top + 0, .Width, .Height)\n With shp.TextFrame2\n .VerticalAnchor = msoAnchorMiddle\n .TextRange.ParagraphFormat.Alignment = msoAlignCenter\n End With\n shp.Name = \"Button_\" & .Address(False, False)\n End With\n shp.Fill.ForeColor.RGB = RGB(200, 200, 200)\n shp.OnAction = \"ButtonClick\"\n Next j\n Next i\nEnd Sub\n\n'called from a click on a shape\nSub ButtonClick()\n Dim shp As Shape, capt As String, tr As TextRange2\n \n 'get a reference to the clicked-on shape\n Set shp = ActiveSheet.Shapes(Application.Caller)\n Set tr = shp.TextFrame2.TextRange\n \n Select Case tr.Text 'decide based on current button text\n Case \"Yes\"\n tr.Text = \"\"\n shp.Fill.ForeColor.RGB = RGB(200, 200, 200)\n Case \"No\"\n tr.Text = \"Yes\"\n shp.Fill.ForeColor.RGB = vbGreen\n Case \"\"\n tr.Text = \"No\"\n shp.Fill.ForeColor.RGB = vbRed\n End Select\nEnd Sub\n"
},
{
"answer_id": 74558100,
"author": "Ike",
"author_id": 16578424,
"author_profile": "https://Stackoverflow.com/users/16578424",
"pm_score": 0,
"selected": false,
"text": "clickArea B2:D17 Option explicit\nPrivate Const nameClickArea As String = \"clickArea\"\n\nPrivate Enum bgValueColor\n neutral = 15921906 'gray\n yes = 11854022 'green\n no = 11389944 'red\nEnd Enum\n\nPrivate Sub Worksheet_SelectionChange(ByVal Target As Range)\n'whenever user clicks in the \"clickArea\" the changeValueAndColor macro is triggered\nIf Not Intersect(Target.Cells(1, 1), Application.Range(nameClickArea)) Is Nothing Then\n changeValueAndColor Target.Cells(1, 1)\nEnd If\nEnd Sub\n\nPrivate Sub changeValueAndColor(c As Range)\n\n'this is to deselect the current cell so that user can select it again\nApplication.EnableEvents = False: Application.ScreenUpdating = False\n\n With Application.Range(nameClickArea).Offset(50).Resize(1, 1)\n .Select\n End With\n \n 'this part changes the value and color according to the current value\n With c\n Select Case .Value\n Case vbNullString\n .Value = \"yes\"\n .Interior.Color = yes\n Case \"yes\"\n .Value = \"no\"\n .Interior.Color = no\n Case \"no\"\n .Value = vbNullString\n .Interior.Color = neutral\n End Select\n End With\n \nApplication.EnableEvents = True: Application.ScreenUpdating = True\nEnd Sub\n Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)\nclearAll\nEnd Sub\n\nPrivate Sub clearAll()\nWith Application.Range(nameClickArea)\n .ClearContents\n .Interior.Color = neutral\nEnd With\nEnd Sub\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16759275/"
] |
74,548,105
|
<p>I'm having some issues hosting blazor WASM standalone (without an asp.net core project as host) behind nginx as a reverse proxy.</p>
<p>Here is my Nginx default config file:</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>server {
listen 80;
listen [::]:80;
server_name localhost;
location / {
root /var/www/web/BlazorApp/wwwroot;
try_files $uri $uri/ index.html =404;
include /etc/nginx/mime.types;
types {
application/wasm wasm;
}
default_type application/octet-stream;
}
location /service1/ {
proxy_pass http://localhost:5001/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /service2/ {
proxy_pass http://localhost:5002/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /service3/ {
proxy_pass http://localhost:5003/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}</code></pre>
</div>
</div>
</p>
<p>This Configuration works in the sense that I can access my blazor app using</p>
<pre><code>http://{server-ip-address}
</code></pre>
<p>and my other services using</p>
<pre><code>http://{server-ip-address}/serviceX
</code></pre>
<p>where X would refer to service 1,2 and 3 respectively</p>
<p><strong>First issue</strong>: when I navigate in my blazor app for example to <code>http://{server-ip-address}/My-Blazor-Page</code> and I refresh the page I get a 404 not found error.</p>
<p>for it to work back again I need to go back to the base address <code>http://{server-ip-address}</code> and navigate back to <code>My-Blazor-Page</code>.
I cannot refresh a page and go back to the same page.</p>
<p><strong>Second issue</strong>: I would like my blazor app to have a different location. I would like to use <code>http://{server-ip-address}/Blazor</code> rather than <code>http://{server-ip-address}/</code>.</p>
<p>I tried everything to get it right but this is the only config that semi-works</p>
<p>Many thanks for your help!</p>
|
[
{
"answer_id": 74552240,
"author": "Tim Williams",
"author_id": 478884,
"author_profile": "https://Stackoverflow.com/users/478884",
"pm_score": 1,
"selected": false,
"text": "Option Explicit\n\nSub Tester()\n \n Dim i As Long, j As Long, k As Long\n Dim addr As String, shp As Shape\n\n For i = 1 To 3\n For j = 2 To 17\n With ActiveSheet.Cells(j, i)\n Set shp = .Parent.Shapes.AddShape(msoShapeRectangle, .Left + 0, _\n .Top + 0, .Width, .Height)\n With shp.TextFrame2\n .VerticalAnchor = msoAnchorMiddle\n .TextRange.ParagraphFormat.Alignment = msoAlignCenter\n End With\n shp.Name = \"Button_\" & .Address(False, False)\n End With\n shp.Fill.ForeColor.RGB = RGB(200, 200, 200)\n shp.OnAction = \"ButtonClick\"\n Next j\n Next i\nEnd Sub\n\n'called from a click on a shape\nSub ButtonClick()\n Dim shp As Shape, capt As String, tr As TextRange2\n \n 'get a reference to the clicked-on shape\n Set shp = ActiveSheet.Shapes(Application.Caller)\n Set tr = shp.TextFrame2.TextRange\n \n Select Case tr.Text 'decide based on current button text\n Case \"Yes\"\n tr.Text = \"\"\n shp.Fill.ForeColor.RGB = RGB(200, 200, 200)\n Case \"No\"\n tr.Text = \"Yes\"\n shp.Fill.ForeColor.RGB = vbGreen\n Case \"\"\n tr.Text = \"No\"\n shp.Fill.ForeColor.RGB = vbRed\n End Select\nEnd Sub\n"
},
{
"answer_id": 74558100,
"author": "Ike",
"author_id": 16578424,
"author_profile": "https://Stackoverflow.com/users/16578424",
"pm_score": 0,
"selected": false,
"text": "clickArea B2:D17 Option explicit\nPrivate Const nameClickArea As String = \"clickArea\"\n\nPrivate Enum bgValueColor\n neutral = 15921906 'gray\n yes = 11854022 'green\n no = 11389944 'red\nEnd Enum\n\nPrivate Sub Worksheet_SelectionChange(ByVal Target As Range)\n'whenever user clicks in the \"clickArea\" the changeValueAndColor macro is triggered\nIf Not Intersect(Target.Cells(1, 1), Application.Range(nameClickArea)) Is Nothing Then\n changeValueAndColor Target.Cells(1, 1)\nEnd If\nEnd Sub\n\nPrivate Sub changeValueAndColor(c As Range)\n\n'this is to deselect the current cell so that user can select it again\nApplication.EnableEvents = False: Application.ScreenUpdating = False\n\n With Application.Range(nameClickArea).Offset(50).Resize(1, 1)\n .Select\n End With\n \n 'this part changes the value and color according to the current value\n With c\n Select Case .Value\n Case vbNullString\n .Value = \"yes\"\n .Interior.Color = yes\n Case \"yes\"\n .Value = \"no\"\n .Interior.Color = no\n Case \"no\"\n .Value = vbNullString\n .Interior.Color = neutral\n End Select\n End With\n \nApplication.EnableEvents = True: Application.ScreenUpdating = True\nEnd Sub\n Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)\nclearAll\nEnd Sub\n\nPrivate Sub clearAll()\nWith Application.Range(nameClickArea)\n .ClearContents\n .Interior.Color = neutral\nEnd With\nEnd Sub\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8468850/"
] |
74,548,126
|
<p>I am trying to concatenate two strings in TypeScript like this:</p>
<pre><code>let string1 = new String("IdNumber: " + this.IdNumber);
let string2 = new String(this.notes);
this.notes = string1.concat(string2.toString());
</code></pre>
<p>The output I see for this.notes on line 3 is missing the original text from this.notes in string2.
This is what I see in devTools for this.notes on line 3 when debugging:</p>
<pre><code>"IdNumber: 524242
"
</code></pre>
<p>when hovering over this.notes on line 2 in devTools it looks like this:</p>
<pre><code>"testing
testing 2
testing 3"
</code></pre>
<p>I was hoping that this.notes on line 3 would look like this:</p>
<pre><code>"IdNumber: 524242
testing
testing 2
testing 3"
</code></pre>
<p>What am I doing wrong?</p>
|
[
{
"answer_id": 74552240,
"author": "Tim Williams",
"author_id": 478884,
"author_profile": "https://Stackoverflow.com/users/478884",
"pm_score": 1,
"selected": false,
"text": "Option Explicit\n\nSub Tester()\n \n Dim i As Long, j As Long, k As Long\n Dim addr As String, shp As Shape\n\n For i = 1 To 3\n For j = 2 To 17\n With ActiveSheet.Cells(j, i)\n Set shp = .Parent.Shapes.AddShape(msoShapeRectangle, .Left + 0, _\n .Top + 0, .Width, .Height)\n With shp.TextFrame2\n .VerticalAnchor = msoAnchorMiddle\n .TextRange.ParagraphFormat.Alignment = msoAlignCenter\n End With\n shp.Name = \"Button_\" & .Address(False, False)\n End With\n shp.Fill.ForeColor.RGB = RGB(200, 200, 200)\n shp.OnAction = \"ButtonClick\"\n Next j\n Next i\nEnd Sub\n\n'called from a click on a shape\nSub ButtonClick()\n Dim shp As Shape, capt As String, tr As TextRange2\n \n 'get a reference to the clicked-on shape\n Set shp = ActiveSheet.Shapes(Application.Caller)\n Set tr = shp.TextFrame2.TextRange\n \n Select Case tr.Text 'decide based on current button text\n Case \"Yes\"\n tr.Text = \"\"\n shp.Fill.ForeColor.RGB = RGB(200, 200, 200)\n Case \"No\"\n tr.Text = \"Yes\"\n shp.Fill.ForeColor.RGB = vbGreen\n Case \"\"\n tr.Text = \"No\"\n shp.Fill.ForeColor.RGB = vbRed\n End Select\nEnd Sub\n"
},
{
"answer_id": 74558100,
"author": "Ike",
"author_id": 16578424,
"author_profile": "https://Stackoverflow.com/users/16578424",
"pm_score": 0,
"selected": false,
"text": "clickArea B2:D17 Option explicit\nPrivate Const nameClickArea As String = \"clickArea\"\n\nPrivate Enum bgValueColor\n neutral = 15921906 'gray\n yes = 11854022 'green\n no = 11389944 'red\nEnd Enum\n\nPrivate Sub Worksheet_SelectionChange(ByVal Target As Range)\n'whenever user clicks in the \"clickArea\" the changeValueAndColor macro is triggered\nIf Not Intersect(Target.Cells(1, 1), Application.Range(nameClickArea)) Is Nothing Then\n changeValueAndColor Target.Cells(1, 1)\nEnd If\nEnd Sub\n\nPrivate Sub changeValueAndColor(c As Range)\n\n'this is to deselect the current cell so that user can select it again\nApplication.EnableEvents = False: Application.ScreenUpdating = False\n\n With Application.Range(nameClickArea).Offset(50).Resize(1, 1)\n .Select\n End With\n \n 'this part changes the value and color according to the current value\n With c\n Select Case .Value\n Case vbNullString\n .Value = \"yes\"\n .Interior.Color = yes\n Case \"yes\"\n .Value = \"no\"\n .Interior.Color = no\n Case \"no\"\n .Value = vbNullString\n .Interior.Color = neutral\n End Select\n End With\n \nApplication.EnableEvents = True: Application.ScreenUpdating = True\nEnd Sub\n Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)\nclearAll\nEnd Sub\n\nPrivate Sub clearAll()\nWith Application.Range(nameClickArea)\n .ClearContents\n .Interior.Color = neutral\nEnd With\nEnd Sub\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7201774/"
] |
74,548,143
|
<p>When trying to use Huggingface estimator on sagemaker, Run training on Amazon SageMaker e.g.</p>
<pre><code># create the Estimator
huggingface_estimator = HuggingFace(
entry_point='train.py',
source_dir='./scripts',
instance_type='ml.p3.2xlarge',
instance_count=1,
role=role,
transformers_version='4.17',
pytorch_version='1.10',
py_version='py38',
hyperparameters = hyperparameters
)
</code></pre>
<p>When I tried to increase the version to transformers_version='4.24', it throws an error where the maximum version supported is 4.17.</p>
<p><strong>How to use AWS Sagemaker with newer version of Huggingface Estimator?</strong></p>
<p>There's a note on using newer version for inference on <a href="https://discuss.huggingface.co/t/deploying-open-ais-whisper-on-sagemaker/24761/9" rel="nofollow noreferrer">https://discuss.huggingface.co/t/deploying-open-ais-whisper-on-sagemaker/24761/9</a> but it looks like the way to use it for training with the Huggingface estimator is kind of complicated <a href="https://discuss.huggingface.co/t/huggingface-pytorch-versions-on-sagemaker/26315/5?u=alvations" rel="nofollow noreferrer">https://discuss.huggingface.co/t/huggingface-pytorch-versions-on-sagemaker/26315/5?u=alvations</a> and it's not confirmed that the complicated steps can work.</p>
|
[
{
"answer_id": 74554115,
"author": "Arun Lokanatha",
"author_id": 19490330,
"author_profile": "https://Stackoverflow.com/users/19490330",
"pm_score": 2,
"selected": false,
"text": "pt_estimator = PyTorch(\nentry_point=\"train.py\",\nsource_dir=\"scripts\",\nrole=sagemaker.get_execution_role(),\n"
},
{
"answer_id": 74598533,
"author": "Ivan Khvostishkov",
"author_id": 18309077,
"author_profile": "https://Stackoverflow.com/users/18309077",
"pm_score": 2,
"selected": false,
"text": "requirements.txt transformers==4.24.0\n"
},
{
"answer_id": 74660931,
"author": "hakkikonu",
"author_id": 1848929,
"author_profile": "https://Stackoverflow.com/users/1848929",
"pm_score": 0,
"selected": false,
"text": "ImportError: Unable to import 'transformers'\n # create the Estimator\nhuggingface_estimator = HuggingFace(\n entry_point='train.py',\n source_dir='./scripts',\n instance_type='ml.p3.2xlarge',\n instance_count=1,\n role=role,\n transformers_version='4.24',\n pytorch_version='1\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/610569/"
] |
74,548,150
|
<p>I have one column that has important identifiers, but they are not uniform, so I am stuck with string splitting. I guess an example is best.</p>
<p><strong>Code example, "df" is the tibble as is, result the result</strong></p>
<pre><code>a <- c('Text1','Text1','Text1','Text1_sub1','Text1_sub2','Text2','Text2','Text2_sub1_sub2','Text2_sub3')
b <- c("0" ,"0" ,"0" ,NA ,NA ,"0" ,"0" ,NA ,NA)
df <- tibble(a,b)
a <- c('Text1','Text1','Text1','Text1' ,'Text1' ,'Text2','Text2','Text2' ,'Text2')
b <- c("0" ,"0" ,"0" ,"sub1" ,"sub2" ,"0" ,"0" ,"sub1_sub2" ,"sub3")
result <- tibble(a,b)
</code></pre>
<p><strong>In Different formating:</strong></p>
<pre><code>> df
# A tibble: 9 x 2
a b
<chr> <chr>
1 Text1 0
2 Text1 0
3 Text1 0
4 Text1_sub1 NA
5 Text1_sub2 NA
6 Text2 0
7 Text2 0
8 Text2_sub1_sub2 NA
9 Text2_sub3 NA
> result
# A tibble: 9 x 2
a b
<chr> <chr>
1 Text1 0
2 Text1 0
3 Text1 0
4 Text1 sub1
5 Text1 sub2
6 Text2 0
7 Text2 0
8 Text2 sub1_sub2
9 Text2 sub3
</code></pre>
<p>I want to use column as identifier, therefore I would like to take the unique strings in column a where b == 0, and then substract those from column a where b != 0, and transfer it to b. Any help highly appreciated, tidy solution would be nice, but any pointer will do, thanks!</p>
|
[
{
"answer_id": 74548298,
"author": "DaveArmstrong",
"author_id": 8206434,
"author_profile": "https://Stackoverflow.com/users/8206434",
"pm_score": 1,
"selected": false,
"text": "library(dplyr)\nlibrary(glue)\na <- c('Text1','Text1','Text1','Text1_sub1','Text1_sub2','Text2','Text2','Text2_sub1_sub2','Text2_sub3')\nb <- c(\"0\" ,\"0\" ,\"0\" ,NA ,NA ,\"0\" ,\"0\" ,NA ,NA)\ndf <- tibble(a,b)\nunstr <- df %>% \n filter(b == \"0\") %>% \n select(a) %>% \n distinct() %>% \n pull %>% \n glue_collapse(sep=\"|\")\nresult <- df %>% \n mutate(b = case_when(is.na(b) ~ gsub(glue(\"{unstr}_(.*)\"), \"\\\\1\", a), \n TRUE ~ b), \n a = gsub(glue(\"({unstr})_.*\"), \"\\\\1\", a))\nresult\n#> # A tibble: 9 × 2\n#> a b \n#> <chr> <chr> \n#> 1 Text1 0 \n#> 2 Text1 0 \n#> 3 Text1 0 \n#> 4 Text1 _sub1 \n#> 5 Text1 _sub2 \n#> 6 Text2 0 \n#> 7 Text2 0 \n#> 8 Text2 sub1_sub2\n#> 9 Text2 sub3\n"
},
{
"answer_id": 74548465,
"author": "bouncyball",
"author_id": 5619526,
"author_profile": "https://Stackoverflow.com/users/5619526",
"pm_score": 2,
"selected": false,
"text": "separate df %>%\n separate(a, \n into = c(\"a\", \"b_new\"), \n sep = \"_\",\n extra = \"merge\") %>%\n mutate(b = coalesce(b, b_new)) %>%\n select(-b_new)\n\n\n# A tibble: 9 × 2\n a b \n <chr> <chr> \n1 Text1 0 \n2 Text1 0 \n3 Text1 0 \n4 Text1 sub1 \n5 Text1 sub2 \n6 Text2 0 \n7 Text2 0 \n8 Text2 sub1_sub2\n9 Text2 sub3 \n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3620212/"
] |
74,548,163
|
<p>I have a data frame and am trying to fill the missing values with the previous and next values in the data frame. I used the following code, but it did not fill and returns missing values still. I tried 2 different variations, but both do not work. Could someone please let me know what I am doing wrong? Thanks!</p>
<p><strong>Data frame:</strong> 'oil.csv'</p>
<pre><code>date dcoilwtico
1/1/13
1/2/13 93.14
1/3/13 92.97
1/4/13 93.12
1/7/13 93.2
1/8/13 93.21
1/9/13 93.08
1/10/13 93.81
1/11/13 93.6
1/14/13 94.27
1/15/13 93.26
1/16/13 94.28
1/17/13 95.49
1/18/13 95.61
1/21/13
1/22/13 96.09
</code></pre>
<p><strong>dput(oil_df)</strong>:</p>
<pre><code>structure(list(date = c("2013-01-01", "2013-01-02", "2013-01-03",
"2013-01-04", "2013-01-07", "2013-01-08", "2013-01-09", "2013-01-10",
"2013-01-11", "2013-01-14", "2013-01-15", "2013-01-16", "2013-01-17",
"2013-01-18", "2013-01-21", "2013-01-22", "2013-01-23", "2013-01-24",
"2013-01-25", "2013-01-28", "2013-01-29", "2013-01-30", "2013-01-31",
"2013-02-01", "2013-02-04", "2013-02-05", "2013-02-06", "2013-02-07",
"2013-02-08", "2013-02-11", "2013-02-12", "2013-02-13", "2013-02-14",
"2013-02-15", "2013-02-18", "2013-02-19", "2013-02-20", "2013-02-21",
"2013-02-22", "2013-02-25", "2013-02-26", "2013-02-27", "2013-02-28",
"2013-03-01", "2013-03-04", "2013-03-05", "2013-03-06", "2013-03-07",
"2013-03-08", "2013-03-11", "2013-03-12", "2013-03-13", "2013-03-14",
"2013-03-15", "2013-03-18", "2013-03-19", "2013-03-20", "2013-03-21",
"2013-03-22", "2013-03-25", "2013-03-26", "2013-03-27", "2013-03-28",
"2013-03-29", "2013-04-01", "2013-04-02", "2013-04-03", "2013-04-04",
"2013-04-05", "2013-04-08", "2013-04-09", "2013-04-10", "2013-04-11",
"2013-04-12", "2013-04-15", "2013-04-16", "2013-04-17", "2013-04-18",
"2013-04-19", "2013-04-22", "2013-04-23", "2013-04-24", "2013-04-25",
"2013-04-26", "2013-04-29", "2013-04-30", "2013-05-01", "2013-05-02",
"2013-05-03", "2013-05-06", "2013-05-07", "2013-05-08", "2013-05-09",
"2013-05-10", "2013-05-13", "2013-05-14", "2013-05-15", "2013-05-16",
"2013-05-17", "2013-05-20", "2013-05-21", "2013-05-22", "2013-05-23",
"2013-05-24", "2013-05-27", "2013-05-28", "2013-05-29", "2013-05-30",
"2013-05-31", "2013-06-03", "2013-06-04", "2013-06-05", "2013-06-06",
"2013-06-07", "2013-06-10", "2013-06-11", "2013-06-12", "2013-06-13",
"2013-06-14", "2013-06-17", "2013-06-18", "2013-06-19", "2013-06-20",
"2013-06-21", "2013-06-24", "2013-06-25", "2013-06-26", "2013-06-27",
"2013-06-28", "2013-07-01", "2013-07-02", "2013-07-03", "2013-07-04",
"2013-07-05", "2013-07-08", "2013-07-09", "2013-07-10", "2013-07-11",
"2013-07-12", "2013-07-15", "2013-07-16", "2013-07-17", "2013-07-18",
"2013-07-19", "2013-07-22", "2013-07-23", "2013-07-24", "2013-07-25",
"2013-07-26", "2013-07-29", "2013-07-30", "2013-07-31", "2013-08-01",
"2013-08-02", "2013-08-05", "2013-08-06", "2013-08-07", "2013-08-08",
"2013-08-09", "2013-08-12", "2013-08-13", "2013-08-14", "2013-08-15",
"2013-08-16", "2013-08-19", "2013-08-20", "2013-08-21", "2013-08-22",
"2013-08-23", "2013-08-26", "2013-08-27", "2013-08-28", "2013-08-29",
"2013-08-30", "2013-09-02", "2013-09-03", "2013-09-04", "2013-09-05",
"2013-09-06", "2013-09-09", "2013-09-10", "2013-09-11", "2013-09-12",
"2013-09-13", "2013-09-16", "2013-09-17", "2013-09-18", "2013-09-19",
"2013-09-20", "2013-09-23", "2013-09-24", "2013-09-25", "2013-09-26",
"2013-09-27", "2013-09-30", "2013-10-01", "2013-10-02", "2013-10-03",
"2013-10-04", "2013-10-07", "2013-10-08", "2013-10-09", "2013-10-10",
"2013-10-11", "2013-10-14", "2013-10-15", "2013-10-16", "2013-10-17",
"2013-10-18", "2013-10-21", "2013-10-22", "2013-10-23", "2013-10-24",
"2013-10-25", "2013-10-28", "2013-10-29", "2013-10-30", "2013-10-31",
"2013-11-01", "2013-11-04", "2013-11-05", "2013-11-06", "2013-11-07",
"2013-11-08", "2013-11-11", "2013-11-12", "2013-11-13", "2013-11-14",
"2013-11-15", "2013-11-18", "2013-11-19", "2013-11-20", "2013-11-21",
"2013-11-22", "2013-11-25", "2013-11-26", "2013-11-27", "2013-11-28",
"2013-11-29", "2013-12-02", "2013-12-03", "2013-12-04", "2013-12-05",
"2013-12-06", "2013-12-09", "2013-12-10", "2013-12-11", "2013-12-12",
"2013-12-13", "2013-12-16", "2013-12-17", "2013-12-18", "2013-12-19",
"2013-12-20", "2013-12-23", "2013-12-24", "2013-12-25", "2013-12-26",
"2013-12-27", "2013-12-30", "2013-12-31", "2014-01-01", "2014-01-02",
"2014-01-03", "2014-01-06", "2014-01-07", "2014-01-08", "2014-01-09",
"2014-01-10", "2014-01-13", "2014-01-14", "2014-01-15", "2014-01-16",
"2014-01-17", "2014-01-20", "2014-01-21", "2014-01-22", "2014-01-23",
"2014-01-24", "2014-01-27", "2014-01-28", "2014-01-29", "2014-01-30",
"2014-01-31", "2014-02-03", "2014-02-04", "2014-02-05", "2014-02-06",
"2014-02-07", "2014-02-10", "2014-02-11", "2014-02-12", "2014-02-13",
"2014-02-14", "2014-02-17", "2014-02-18", "2014-02-19", "2014-02-20",
"2014-02-21", "2014-02-24", "2014-02-25", "2014-02-26", "2014-02-27",
"2014-02-28", "2014-03-03", "2014-03-04", "2014-03-05", "2014-03-06",
"2014-03-07", "2014-03-10", "2014-03-11", "2014-03-12", "2014-03-13",
"2014-03-14", "2014-03-17", "2014-03-18", "2014-03-19", "2014-03-20",
"2014-03-21", "2014-03-24", "2014-03-25", "2014-03-26", "2014-03-27",
"2014-03-28", "2014-03-31", "2014-04-01", "2014-04-02", "2014-04-03",
"2014-04-04", "2014-04-07", "2014-04-08", "2014-04-09", "2014-04-10",
"2014-04-11", "2014-04-14", "2014-04-15", "2014-04-16", "2014-04-17",
"2014-04-18", "2014-04-21", "2014-04-22", "2014-04-23", "2014-04-24",
"2014-04-25", "2014-04-28", "2014-04-29", "2014-04-30", "2014-05-01",
"2014-05-02", "2014-05-05", "2014-05-06", "2014-05-07", "2014-05-08",
"2014-05-09", "2014-05-12", "2014-05-13", "2014-05-14", "2014-05-15",
"2014-05-16", "2014-05-19", "2014-05-20", "2014-05-21", "2014-05-22",
"2014-05-23", "2014-05-26", "2014-05-27", "2014-05-28", "2014-05-29",
"2014-05-30", "2014-06-02", "2014-06-03", "2014-06-04", "2014-06-05",
"2014-06-06", "2014-06-09", "2014-06-10", "2014-06-11", "2014-06-12",
"2014-06-13", "2014-06-16", "2014-06-17", "2014-06-18", "2014-06-19",
"2014-06-20", "2014-06-23", "2014-06-24", "2014-06-25", "2014-06-26",
"2014-06-27", "2014-06-30", "2014-07-01", "2014-07-02", "2014-07-03",
"2014-07-04", "2014-07-07", "2014-07-08", "2014-07-09", "2014-07-10",
"2014-07-11", "2014-07-14", "2014-07-15", "2014-07-16", "2014-07-17",
"2014-07-18", "2014-07-21", "2014-07-22", "2014-07-23", "2014-07-24",
"2014-07-25", "2014-07-28", "2014-07-29", "2014-07-30", "2014-07-31",
"2014-08-01", "2014-08-04", "2014-08-05", "2014-08-06", "2014-08-07",
"2014-08-08", "2014-08-11", "2014-08-12", "2014-08-13", "2014-08-14",
"2014-08-15", "2014-08-18", "2014-08-19", "2014-08-20", "2014-08-21",
"2014-08-22", "2014-08-25", "2014-08-26", "2014-08-27", "2014-08-28",
"2014-08-29", "2014-09-01", "2014-09-02", "2014-09-03", "2014-09-04",
"2014-09-05", "2014-09-08", "2014-09-09", "2014-09-10", "2014-09-11",
"2014-09-12", "2014-09-15", "2014-09-16", "2014-09-17", "2014-09-18",
"2014-09-19", "2014-09-22", "2014-09-23", "2014-09-24", "2014-09-25",
"2014-09-26", "2014-09-29", "2014-09-30", "2014-10-01", "2014-10-02",
"2014-10-03", "2014-10-06", "2014-10-07", "2014-10-08", "2014-10-09",
"2014-10-10", "2014-10-13", "2014-10-14", "2014-10-15", "2014-10-16",
"2014-10-17", "2014-10-20", "2014-10-21", "2014-10-22", "2014-10-23",
"2014-10-24", "2014-10-27", "2014-10-28", "2014-10-29", "2014-10-30",
"2014-10-31", "2014-11-03", "2014-11-04", "2014-11-05", "2014-11-06",
"2014-11-07", "2014-11-10", "2014-11-11", "2014-11-12", "2014-11-13",
"2014-11-14", "2014-11-17", "2014-11-18", "2014-11-19", "2014-11-20",
"2014-11-21", "2014-11-24", "2014-11-25", "2014-11-26", "2014-11-27",
"2014-11-28", "2014-12-01", "2014-12-02", "2014-12-03", "2014-12-04",
"2014-12-05", "2014-12-08", "2014-12-09", "2014-12-10", "2014-12-11",
"2014-12-12", "2014-12-15", "2014-12-16", "2014-12-17", "2014-12-18",
"2014-12-19", "2014-12-22", "2014-12-23", "2014-12-24", "2014-12-25",
"2014-12-26", "2014-12-29", "2014-12-30", "2014-12-31", "2015-01-01",
"2015-01-02", "2015-01-05", "2015-01-06", "2015-01-07", "2015-01-08",
"2015-01-09", "2015-01-12", "2015-01-13", "2015-01-14", "2015-01-15",
"2015-01-16", "2015-01-19", "2015-01-20", "2015-01-21", "2015-01-22",
"2015-01-23", "2015-01-26", "2015-01-27", "2015-01-28", "2015-01-29",
"2015-01-30", "2015-02-02", "2015-02-03", "2015-02-04", "2015-02-05",
"2015-02-06", "2015-02-09", "2015-02-10", "2015-02-11", "2015-02-12",
"2015-02-13", "2015-02-16", "2015-02-17", "2015-02-18", "2015-02-19",
"2015-02-20", "2015-02-23", "2015-02-24", "2015-02-25", "2015-02-26",
"2015-02-27", "2015-03-02", "2015-03-03", "2015-03-04", "2015-03-05",
"2015-03-06", "2015-03-09", "2015-03-10", "2015-03-11", "2015-03-12",
"2015-03-13", "2015-03-16", "2015-03-17", "2015-03-18", "2015-03-19",
"2015-03-20", "2015-03-23", "2015-03-24", "2015-03-25", "2015-03-26",
"2015-03-27", "2015-03-30", "2015-03-31", "2015-04-01", "2015-04-02",
"2015-04-03", "2015-04-06", "2015-04-07", "2015-04-08", "2015-04-09",
"2015-04-10", "2015-04-13", "2015-04-14", "2015-04-15", "2015-04-16",
"2015-04-17", "2015-04-20", "2015-04-21", "2015-04-22", "2015-04-23",
"2015-04-24", "2015-04-27", "2015-04-28", "2015-04-29", "2015-04-30",
"2015-05-01", "2015-05-04", "2015-05-05", "2015-05-06", "2015-05-07",
"2015-05-08", "2015-05-11", "2015-05-12", "2015-05-13", "2015-05-14",
"2015-05-15", "2015-05-18", "2015-05-19", "2015-05-20", "2015-05-21",
"2015-05-22", "2015-05-25", "2015-05-26", "2015-05-27", "2015-05-28",
"2015-05-29", "2015-06-01", "2015-06-02", "2015-06-03", "2015-06-04",
"2015-06-05", "2015-06-08", "2015-06-09", "2015-06-10", "2015-06-11",
"2015-06-12", "2015-06-15", "2015-06-16", "2015-06-17", "2015-06-18",
"2015-06-19", "2015-06-22", "2015-06-23", "2015-06-24", "2015-06-25",
"2015-06-26", "2015-06-29", "2015-06-30", "2015-07-01", "2015-07-02",
"2015-07-03", "2015-07-06", "2015-07-07", "2015-07-08", "2015-07-09",
"2015-07-10", "2015-07-13", "2015-07-14", "2015-07-15", "2015-07-16",
"2015-07-17", "2015-07-20", "2015-07-21", "2015-07-22", "2015-07-23",
"2015-07-24", "2015-07-27", "2015-07-28", "2015-07-29", "2015-07-30",
"2015-07-31", "2015-08-03", "2015-08-04", "2015-08-05", "2015-08-06",
"2015-08-07", "2015-08-10", "2015-08-11", "2015-08-12", "2015-08-13",
"2015-08-14", "2015-08-17", "2015-08-18", "2015-08-19", "2015-08-20",
"2015-08-21", "2015-08-24", "2015-08-25", "2015-08-26", "2015-08-27",
"2015-08-28", "2015-08-31", "2015-09-01", "2015-09-02", "2015-09-03",
"2015-09-04", "2015-09-07", "2015-09-08", "2015-09-09", "2015-09-10",
"2015-09-11", "2015-09-14", "2015-09-15", "2015-09-16", "2015-09-17",
"2015-09-18", "2015-09-21", "2015-09-22", "2015-09-23", "2015-09-24",
"2015-09-25", "2015-09-28", "2015-09-29", "2015-09-30", "2015-10-01",
"2015-10-02", "2015-10-05", "2015-10-06", "2015-10-07", "2015-10-08",
"2015-10-09", "2015-10-12", "2015-10-13", "2015-10-14", "2015-10-15",
"2015-10-16", "2015-10-19", "2015-10-20", "2015-10-21", "2015-10-22",
"2015-10-23", "2015-10-26", "2015-10-27", "2015-10-28", "2015-10-29",
"2015-10-30", "2015-11-02", "2015-11-03", "2015-11-04", "2015-11-05",
"2015-11-06", "2015-11-09", "2015-11-10", "2015-11-11", "2015-11-12",
"2015-11-13", "2015-11-16", "2015-11-17", "2015-11-18", "2015-11-19",
"2015-11-20", "2015-11-23", "2015-11-24", "2015-11-25", "2015-11-26",
"2015-11-27", "2015-11-30", "2015-12-01", "2015-12-02", "2015-12-03",
"2015-12-04", "2015-12-07", "2015-12-08", "2015-12-09", "2015-12-10",
"2015-12-11", "2015-12-14", "2015-12-15", "2015-12-16", "2015-12-17",
"2015-12-18", "2015-12-21", "2015-12-22", "2015-12-23", "2015-12-24",
"2015-12-25", "2015-12-28", "2015-12-29", "2015-12-30", "2015-12-31",
"2016-01-01", "2016-01-04", "2016-01-05", "2016-01-06", "2016-01-07",
"2016-01-08", "2016-01-11", "2016-01-12", "2016-01-13", "2016-01-14",
"2016-01-15", "2016-01-18", "2016-01-19", "2016-01-20", "2016-01-21",
"2016-01-22", "2016-01-25", "2016-01-26", "2016-01-27", "2016-01-28",
"2016-01-29", "2016-02-01", "2016-02-02", "2016-02-03", "2016-02-04",
"2016-02-05", "2016-02-08", "2016-02-09", "2016-02-10", "2016-02-11",
"2016-02-12", "2016-02-15", "2016-02-16", "2016-02-17", "2016-02-18",
"2016-02-19", "2016-02-22", "2016-02-23", "2016-02-24", "2016-02-25",
"2016-02-26", "2016-02-29", "2016-03-01", "2016-03-02", "2016-03-03",
"2016-03-04", "2016-03-07", "2016-03-08", "2016-03-09", "2016-03-10",
"2016-03-11", "2016-03-14", "2016-03-15", "2016-03-16", "2016-03-17",
"2016-03-18", "2016-03-21", "2016-03-22", "2016-03-23", "2016-03-24",
"2016-03-25", "2016-03-28", "2016-03-29", "2016-03-30", "2016-03-31",
"2016-04-01", "2016-04-04", "2016-04-05", "2016-04-06", "2016-04-07",
"2016-04-08", "2016-04-11", "2016-04-12", "2016-04-13", "2016-04-14",
"2016-04-15", "2016-04-18", "2016-04-19", "2016-04-20", "2016-04-21",
"2016-04-22", "2016-04-25", "2016-04-26", "2016-04-27", "2016-04-28",
"2016-04-29", "2016-05-02", "2016-05-03", "2016-05-04", "2016-05-05",
"2016-05-06", "2016-05-09", "2016-05-10", "2016-05-11", "2016-05-12",
"2016-05-13", "2016-05-16", "2016-05-17", "2016-05-18", "2016-05-19",
"2016-05-20", "2016-05-23", "2016-05-24", "2016-05-25", "2016-05-26",
"2016-05-27", "2016-05-30", "2016-05-31", "2016-06-01", "2016-06-02",
"2016-06-03", "2016-06-06", "2016-06-07", "2016-06-08", "2016-06-09",
"2016-06-10", "2016-06-13", "2016-06-14", "2016-06-15", "2016-06-16",
"2016-06-17", "2016-06-20", "2016-06-21", "2016-06-22", "2016-06-23",
"2016-06-24", "2016-06-27", "2016-06-28", "2016-06-29", "2016-06-30",
"2016-07-01", "2016-07-04", "2016-07-05", "2016-07-06", "2016-07-07",
"2016-07-08", "2016-07-11", "2016-07-12", "2016-07-13", "2016-07-14",
"2016-07-15", "2016-07-18", "2016-07-19", "2016-07-20", "2016-07-21",
"2016-07-22", "2016-07-25", "2016-07-26", "2016-07-27", "2016-07-28",
"2016-07-29", "2016-08-01", "2016-08-02", "2016-08-03", "2016-08-04",
"2016-08-05", "2016-08-08", "2016-08-09", "2016-08-10", "2016-08-11",
"2016-08-12", "2016-08-15", "2016-08-16", "2016-08-17", "2016-08-18",
"2016-08-19", "2016-08-22", "2016-08-23", "2016-08-24", "2016-08-25",
"2016-08-26", "2016-08-29", "2016-08-30", "2016-08-31", "2016-09-01",
"2016-09-02", "2016-09-05", "2016-09-06", "2016-09-07", "2016-09-08",
"2016-09-09", "2016-09-12", "2016-09-13", "2016-09-14", "2016-09-15",
"2016-09-16", "2016-09-19", "2016-09-20", "2016-09-21", "2016-09-22",
"2016-09-23", "2016-09-26", "2016-09-27", "2016-09-28", "2016-09-29",
"2016-09-30", "2016-10-03", "2016-10-04", "2016-10-05", "2016-10-06",
"2016-10-07", "2016-10-10", "2016-10-11", "2016-10-12", "2016-10-13",
"2016-10-14", "2016-10-17", "2016-10-18", "2016-10-19", "2016-10-20",
"2016-10-21", "2016-10-24", "2016-10-25", "2016-10-26", "2016-10-27",
"2016-10-28", "2016-10-31", "2016-11-01", "2016-11-02", "2016-11-03",
"2016-11-04", "2016-11-07", "2016-11-08", "2016-11-09", "2016-11-10",
"2016-11-11", "2016-11-14", "2016-11-15", "2016-11-16", "2016-11-17",
"2016-11-18", "2016-11-21", "2016-11-22", "2016-11-23", "2016-11-24",
"2016-11-25", "2016-11-28", "2016-11-29", "2016-11-30", "2016-12-01",
"2016-12-02", "2016-12-05", "2016-12-06", "2016-12-07", "2016-12-08",
"2016-12-09", "2016-12-12", "2016-12-13", "2016-12-14", "2016-12-15",
"2016-12-16", "2016-12-19", "2016-12-20", "2016-12-21", "2016-12-22",
"2016-12-23", "2016-12-26", "2016-12-27", "2016-12-28", "2016-12-29",
"2016-12-30", "2017-01-02", "2017-01-03", "2017-01-04", "2017-01-05",
"2017-01-06", "2017-01-09", "2017-01-10", "2017-01-11", "2017-01-12",
"2017-01-13", "2017-01-16", "2017-01-17", "2017-01-18", "2017-01-19",
"2017-01-20", "2017-01-23", "2017-01-24", "2017-01-25", "2017-01-26",
"2017-01-27", "2017-01-30", "2017-01-31", "2017-02-01", "2017-02-02",
"2017-02-03", "2017-02-06", "2017-02-07", "2017-02-08", "2017-02-09",
"2017-02-10", "2017-02-13", "2017-02-14", "2017-02-15", "2017-02-16",
"2017-02-17", "2017-02-20", "2017-02-21", "2017-02-22", "2017-02-23",
"2017-02-24", "2017-02-27", "2017-02-28", "2017-03-01", "2017-03-02",
"2017-03-03", "2017-03-06", "2017-03-07", "2017-03-08", "2017-03-09",
"2017-03-10", "2017-03-13", "2017-03-14", "2017-03-15", "2017-03-16",
"2017-03-17", "2017-03-20", "2017-03-21", "2017-03-22", "2017-03-23",
"2017-03-24", "2017-03-27", "2017-03-28", "2017-03-29", "2017-03-30",
"2017-03-31", "2017-04-03", "2017-04-04", "2017-04-05", "2017-04-06",
"2017-04-07", "2017-04-10", "2017-04-11", "2017-04-12", "2017-04-13",
"2017-04-14", "2017-04-17", "2017-04-18", "2017-04-19", "2017-04-20",
"2017-04-21", "2017-04-24", "2017-04-25", "2017-04-26", "2017-04-27",
"2017-04-28", "2017-05-01", "2017-05-02", "2017-05-03", "2017-05-04",
"2017-05-05", "2017-05-08", "2017-05-09", "2017-05-10", "2017-05-11",
"2017-05-12", "2017-05-15", "2017-05-16", "2017-05-17", "2017-05-18",
"2017-05-19", "2017-05-22", "2017-05-23", "2017-05-24", "2017-05-25",
"2017-05-26", "2017-05-29", "2017-05-30", "2017-05-31", "2017-06-01",
"2017-06-02", "2017-06-05", "2017-06-06", "2017-06-07", "2017-06-08",
"2017-06-09", "2017-06-12", "2017-06-13", "2017-06-14", "2017-06-15",
"2017-06-16", "2017-06-19", "2017-06-20", "2017-06-21", "2017-06-22",
"2017-06-23", "2017-06-26", "2017-06-27", "2017-06-28", "2017-06-29",
"2017-06-30", "2017-07-03", "2017-07-04", "2017-07-05", "2017-07-06",
"2017-07-07", "2017-07-10", "2017-07-11", "2017-07-12", "2017-07-13",
"2017-07-14", "2017-07-17", "2017-07-18", "2017-07-19", "2017-07-20",
"2017-07-21", "2017-07-24", "2017-07-25", "2017-07-26", "2017-07-27",
"2017-07-28", "2017-07-31", "2017-08-01", "2017-08-02", "2017-08-03",
"2017-08-04", "2017-08-07", "2017-08-08", "2017-08-09", "2017-08-10",
"2017-08-11", "2017-08-14", "2017-08-15", "2017-08-16", "2017-08-17",
"2017-08-18", "2017-08-21", "2017-08-22", "2017-08-23", "2017-08-24",
"2017-08-25", "2017-08-28", "2017-08-29", "2017-08-30", "2017-08-31"
), dcoilwtico = c(NA, 93.14, 92.97, 93.12, 93.2, 93.21, 93.08,
93.81, 93.6, 94.27, 93.26, 94.28, 95.49, 95.61, NA, 96.09, 95.06,
95.35, 95.15, 95.95, 97.62, 97.98, 97.65, 97.46, 96.21, 96.68,
96.44, 95.84, 95.71, 97.01, 97.48, 97.03, 97.3, 95.95, NA, 96.69,
94.92, 92.79, 93.12, 92.74, 92.63, 92.84, 92.03, 90.71, 90.13,
90.88, 90.47, 91.53, 92.01, 92.07, 92.44, 92.47, 93.03, 93.49,
93.71, 92.44, 93.21, 92.46, 93.41, 94.55, 95.99, 96.53, 97.24,
NA, 97.1, 97.23, 95.02, 93.26, 92.76, 93.36, 94.18, 94.59, 93.44,
91.23, 88.75, 88.73, 86.65, 87.83, 88.04, 88.81, 89.21, 91.07,
93.27, 92.63, 94.09, 93.22, 90.74, 93.7, 95.25, 95.8, 95.28,
96.24, 96.09, 95.81, 94.76, 93.96, 93.95, 94.85, 95.72, 96.29,
95.55, 93.98, 94.12, 93.84, NA, 94.65, 93.13, 93.57, 91.93, 93.41,
93.36, 93.66, 94.71, 96.11, 95.82, 95.5, 95.98, 96.66, 97.83,
97.86, 98.46, 98.24, 94.89, 93.81, 95.07, 95.25, 95.47, 97, 96.36,
97.94, 99.65, 101.92, NA, 103.09, 103.03, 103.46, 106.41, 104.77,
105.85, 106.2, 105.88, 106.39, 107.94, 108, 106.61, 107.13, 105.41,
105.47, 104.76, 104.61, 103.14, 105.1, 107.93, 106.94, 106.61,
105.32, 104.41, 103.45, 106.04, 106.19, 106.78, 106.89, 107.43,
107.58, 107.14, 104.9, 103.93, 104.93, 106.48, 105.88, 109.11,
110.17, 108.51, 107.98, NA, 108.67, 107.29, 108.5, 110.62, 109.62,
107.48, 107.65, 108.72, 108.31, 106.54, 105.36, 108.23, 106.26,
104.7, 103.62, 103.22, 102.68, 103.1, 102.86, 102.36, 102.09,
104.15, 103.29, 103.83, 103.07, 103.54, 101.63, 103.08, 102.17,
102.46, 101.15, 102.34, 100.72, 100.87, 99.28, 97.63, 96.9, 96.65,
97.4, 98.74, 98.29, 96.81, 96.29, 94.56, 94.58, 93.4, 94.74,
94.25, 94.56, 95.13, 93.12, 93.91, 93.76, 93.8, 93.03, 93.35,
93.34, 95.35, 94.53, 93.86, 93.41, 92.05, NA, 92.55, 93.61, 95.83,
96.97, 97.14, 97.48, 97.1, 98.32, 97.25, 97.21, 96.27, 97.18,
96.99, 97.59, 98.4, 99.11, 98.62, 98.87, NA, 99.18, 99.94, 98.9,
98.17, NA, 95.14, 93.66, 93.12, 93.31, 91.9, 91.36, 92.39, 91.45,
92.15, 93.78, 93.54, 93.96, NA, 94.51, 96.35, 97.23, 96.66, 95.82,
97.49, 97.34, 98.25, 97.55, 96.44, 97.24, 97.4, 97.84, 99.98,
100.12, 99.96, 100.38, 100.27, 100.31, NA, 102.54, 103.46, 103.2,
102.53, 103.17, 102.2, 102.93, 102.68, 102.88, 105.34, 103.64,
101.75, 101.82, 102.82, 101.39, 100.29, 98.29, 98.57, 99.23,
98.43, 100.08, 100.71, 99.68, 99.97, 100.05, 99.66, 100.61, 101.25,
101.73, 101.57, 99.69, 99.6, 100.29, 101.16, 100.43, 102.57,
103.55, 103.37, 103.68, 104.05, 103.7, 103.71, 104.33, NA, 104.35,
101.69, 101.47, 102.2, 100.85, 101.13, 101.56, 100.07, 99.69,
100.09, 99.74, 99.81, 101.06, 100.52, 100.32, 100.89, 102.01,
102.63, 101.74, 102.31, 102.95, 102.8, 104.31, 104.03, 105.01,
NA, 104.78, 103.37, 104.26, 103.4, 103.07, 103.34, 103.27, 103.17,
103.32, 105.09, 105.02, 105.04, 107.2, 107.49, 107.52, 106.95,
106.64, 107.08, 107.95, 106.83, 106.64, 107.04, 106.49, 106.46,
106.07, 106.06, 105.18, 104.76, NA, 104.19, 104.06, 102.93, 103.61,
101.48, 101.73, 100.56, 101.88, 103.84, 103.83, 105.34, 104.59,
103.81, 102.76, 105.23, 105.68, 104.91, 104.29, 98.23, 97.86,
98.26, 97.34, 96.93, 97.34, 97.61, 98.09, 97.36, 97.57, 95.54,
97.3, 96.44, 94.35, 96.4, 93.97, 93.61, 95.39, 95.78, 95.82,
96.44, 97.86, NA, 92.92, 95.5, 94.51, 93.32, 92.64, 92.73, 91.71,
92.89, 92.18, 92.86, 94.91, 94.33, 93.07, 92.43, 91.46, 91.55,
93.6, 93.59, 95.55, 94.53, 91.17, 90.74, 91.02, 89.76, 90.33,
88.89, 87.29, 85.76, 85.87, 85.73, 81.72, 81.82, 82.33, 82.8,
82.76, 83.25, 80.52, 82.81, 81.27, 81.26, 81.36, 82.25, 81.06,
80.53, 78.77, 77.15, 78.71, 77.87, 78.71, 77.43, 77.85, 77.16,
74.13, 75.91, 75.64, 74.55, 74.55, 75.63, 76.52, 75.74, 74.04,
73.7, NA, 65.94, 68.98, 66.99, 67.3, 66.73, 65.89, 63.13, 63.74,
60.99, 60.01, 57.81, 55.96, 55.97, 56.43, 54.18, 56.91, 55.25,
56.78, 55.7, NA, 54.59, 53.46, 54.14, 53.45, NA, 52.72, 50.05,
47.98, 48.69, 48.8, 48.35, 46.06, 45.92, 48.49, 46.37, 48.49,
NA, 46.79, 47.85, 45.93, 45.26, 44.8, 45.84, 44.08, 44.12, 47.79,
49.25, 53.04, 48.45, 50.48, 51.66, 52.99, 50.06, 48.8, 51.17,
52.66, NA, 53.56, 52.13, 51.12, 49.95, 49.56, 48.48, 50.25, 47.65,
49.84, 49.59, 50.43, 51.53, 50.76, 49.61, 49.95, 48.42, 48.06,
47.12, 44.88, 43.93, 43.39, 44.63, 44.02, 46, 47.4, 47.03, 48.75,
51.41, 48.83, 48.66, 47.72, 50.12, 49.13, NA, 52.08, 53.95, 50.44,
50.79, 51.63, 51.95, 53.3, 56.25, 56.69, 55.71, 56.37, 55.58,
56.17, 56.59, 55.98, 55.56, 57.05, 58.55, 59.62, 59.1, 58.92,
60.38, 60.93, 58.99, 59.41, 59.23, 60.72, 60.5, 59.89, 59.73,
59.44, 57.3, 58.96, 60.18, 58.88, NA, 57.29, 57.51, 57.69, 60.25,
60.24, 61.3, 59.67, 58, 59.11, 58.15, 60.15, 61.36, 60.74, 59.96,
59.53, 60.01, 59.89, 60.41, 59.62, 60.01, 61.05, 60.01, 59.59,
59.41, 58.34, 59.48, 56.94, 56.93, NA, 52.48, 52.33, 51.61, 52.76,
52.74, 52.19, 53.05, 51.4, 50.9, 50.88, 50.11, 50.59, 49.27,
48.11, 47.98, 47.17, 47.97, 48.77, 48.53, 47.11, 45.25, 45.75,
45.13, 44.69, 43.87, 44.94, 43.11, 43.22, 42.27, 42.45, 41.93,
42.58, 40.75, 41, 40.45, 38.22, 39.15, 38.5, 42.47, 45.29, 49.2,
45.38, 46.3, 46.75, 46.02, NA, 45.92, 44.13, 45.85, 44.75, 44.07,
44.58, 47.12, 46.93, 44.71, 46.67, 46.17, 44.53, 44.94, 45.55,
44.4, 45.24, 45.06, 44.75, 45.54, 46.28, 48.53, 47.86, 49.46,
49.67, 47.09, 46.7, 46.63, 46.38, 47.3, 45.91, 45.84, 45.22,
44.9, 43.91, 43.19, 43.21, 45.93, 46.02, 46.6, 46.12, 47.88,
46.32, 45.27, 44.32, 43.87, 44.23, 42.95, 41.74, 40.69, 41.68,
40.73, 40.75, 40.55, 39.39, 39.27, 40.89, 41.22, NA, 40.57, 40.43,
40.58, 39.93, 41.08, 40, 37.64, 37.46, 37.16, 36.76, 35.65, 36.31,
37.32, 35.55, 34.98, 34.72, 34.55, 36.12, 36.76, 37.62, NA, 36.36,
37.88, 36.59, 37.13, NA, 36.81, 35.97, 33.97, 33.29, 33.2, 31.42,
30.42, 30.42, 31.22, 29.45, NA, 28.47, 26.68, 29.55, 32.07, 30.31,
29.54, 32.32, 33.21, 33.66, 31.62, 29.9, 32.29, 31.63, 30.86,
29.71, 27.96, 27.54, 26.19, 29.32, NA, 29.05, 30.68, 30.77, 29.59,
31.37, 31.84, 30.35, 31.4, 31.65, 32.74, 34.39, 34.57, 34.56,
35.91, 37.9, 36.67, 37.62, 37.77, 38.51, 37.2, 36.32, 38.43,
40.17, 39.47, 39.91, 41.45, 38.28, 38.14, NA, 37.99, 36.91, 36.91,
36.94, 35.36, 34.3, 34.52, 37.74, 37.3, 39.74, 40.46, 42.12,
41.7, 41.45, 40.4, 39.74, 40.88, 42.72, 43.18, 42.76, 41.67,
42.52, 45.29, 46.03, 45.98, 44.75, 43.65, 43.77, 44.33, 44.58,
43.45, 44.68, 46.21, 46.64, 46.22, 47.72, 48.29, 48.12, 48.16,
47.67, 48.12, 48.04, 49.1, 49, 49.36, NA, 49.1, 49.07, 49.14,
48.69, 49.71, 50.37, 51.23, 50.52, 49.09, 48.89, 48.49, 47.92,
46.14, 48, 49.4, 48.95, 49.16, 49.34, 46.7, 45.8, 47.93, 49.85,
48.27, 49.02, NA, 46.73, 47.37, 45.22, 45.37, 44.73, 46.82, 44.87,
45.64, 45.93, 45.23, 44.64, 44.96, 43.96, 43.41, 42.4, 42.16,
41.9, 41.13, 41.54, 40.05, 39.5, 40.8, 41.92, 41.83, 43.06, 42.78,
41.75, 43.51, 44.47, 45.72, 46.57, 46.81, 48.2, 48.48, 46.8,
47.54, 46.29, 46.97, 47.64, 46.97, 46.32, 44.68, 43.17, 44.39,
NA, 44.85, 45.47, 47.63, 45.88, 46.28, 44.91, 43.62, 43.85, 43.04,
43.34, 43.85, 45.33, 46.1, 44.36, 45.6, 44.65, 47.07, 47.72,
47.72, 48.8, 48.67, 49.75, 50.44, 49.76, 49.76, 50.72, 50.14,
50.47, 50.35, 49.97, 50.3, 51.59, 50.31, 50.61, 50.18, 49.45,
48.75, 49.71, 48.72, 46.83, 46.66, 45.32, 44.66, 44.07, 44.88,
44.96, 45.2, 44.62, 43.39, 43.29, 45.86, 45.56, 45.37, 45.69,
47.48, 48.07, 46.72, NA, 46.72, 45.66, 45.29, 49.41, 51.08, 51.7,
51.72, 50.95, 49.85, 50.84, 51.51, 52.74, 52.99, 51.01, 50.9,
51.93, 52.13, 52.22, 51.44, 51.98, 52.01, NA, 52.82, 54.01, 53.8,
53.75, NA, 52.36, 53.26, 53.77, 53.98, 51.95, 50.82, 52.19, 53.01,
52.36, NA, 52.45, 51.12, 51.39, 52.33, 52.77, 52.38, 52.14, 53.24,
53.18, 52.63, 52.75, 53.9, 53.55, 53.81, 53.01, 52.19, 52.37,
52.99, 53.84, 52.96, 53.21, 53.11, 53.41, 53.41, NA, 54.02, 53.61,
54.48, 53.99, 54.04, 54, 53.82, 52.63, 53.33, 53.19, 52.68, 49.83,
48.75, 48.05, 47.95, 47.24, 48.34, 48.3, 48.34, 47.79, 47.02,
47.29, 47, 47.3, 47.02, 48.36, 49.47, 50.3, 50.54, 50.25, 50.99,
51.14, 51.69, 52.25, 53.06, 53.38, 53.12, 53.19, NA, 52.62, 52.46,
50.49, 50.26, 49.64, 48.9, 49.22, 49.22, 48.96, 49.31, 48.83,
47.65, 47.79, 45.55, 46.23, 46.46, 45.84, 47.28, 47.81, 47.83,
48.86, 48.64, 49.04, 49.36, 50.32, 50.81, 51.12, 50.99, 48.57,
49.58, NA, 49.63, 48.29, 48.32, 47.68, 47.4, 48.13, 45.8, 45.68,
45.82, 46.1, 46.41, 44.79, 44.47, 44.73, 44.24, 43.34, 42.48,
42.53, 42.86, 43.24, 44.25, 44.74, 44.88, 46.02, NA, NA, 45.11,
45.52, 44.25, 44.4, 45.06, 45.48, 46.06, 46.53, 46.02, 46.4,
47.1, 46.73, 45.78, 46.21, 47.77, 48.58, 49.05, 49.72, 50.21,
49.19, 49.6, 49.03, 49.57, 49.37, 49.07, 49.59, 48.54, 48.81,
47.59, 47.57, 46.8, 47.07, 48.59, 47.39, 47.65, 48.45, 47.24,
47.65, 46.4, 46.46, 45.96, 47.26)), class = "data.frame", row.names = c(NA,
-1218L))
</code></pre>
<p><strong>Code:</strong></p>
<pre><code># Tried both of these options, and both don't work
oil_df %>% fill(everything()) %>% fill(everything(), .direction = 'up')
na.locf(na.locf(oil_df), fromLast = TRUE)
# Confirm oil_df has no more missing values
sum(is.na(oil_df))
</code></pre>
<p><strong>Output:</strong> Excepted 0</p>
<pre><code>> na.locf(na.locf(oil_df), fromLast = TRUE)
>
> # Confirm oil_df has no more missing values
> sum(is.na(oil_df))
[1] 43
</code></pre>
|
[
{
"answer_id": 74548298,
"author": "DaveArmstrong",
"author_id": 8206434,
"author_profile": "https://Stackoverflow.com/users/8206434",
"pm_score": 1,
"selected": false,
"text": "library(dplyr)\nlibrary(glue)\na <- c('Text1','Text1','Text1','Text1_sub1','Text1_sub2','Text2','Text2','Text2_sub1_sub2','Text2_sub3')\nb <- c(\"0\" ,\"0\" ,\"0\" ,NA ,NA ,\"0\" ,\"0\" ,NA ,NA)\ndf <- tibble(a,b)\nunstr <- df %>% \n filter(b == \"0\") %>% \n select(a) %>% \n distinct() %>% \n pull %>% \n glue_collapse(sep=\"|\")\nresult <- df %>% \n mutate(b = case_when(is.na(b) ~ gsub(glue(\"{unstr}_(.*)\"), \"\\\\1\", a), \n TRUE ~ b), \n a = gsub(glue(\"({unstr})_.*\"), \"\\\\1\", a))\nresult\n#> # A tibble: 9 × 2\n#> a b \n#> <chr> <chr> \n#> 1 Text1 0 \n#> 2 Text1 0 \n#> 3 Text1 0 \n#> 4 Text1 _sub1 \n#> 5 Text1 _sub2 \n#> 6 Text2 0 \n#> 7 Text2 0 \n#> 8 Text2 sub1_sub2\n#> 9 Text2 sub3\n"
},
{
"answer_id": 74548465,
"author": "bouncyball",
"author_id": 5619526,
"author_profile": "https://Stackoverflow.com/users/5619526",
"pm_score": 2,
"selected": false,
"text": "separate df %>%\n separate(a, \n into = c(\"a\", \"b_new\"), \n sep = \"_\",\n extra = \"merge\") %>%\n mutate(b = coalesce(b, b_new)) %>%\n select(-b_new)\n\n\n# A tibble: 9 × 2\n a b \n <chr> <chr> \n1 Text1 0 \n2 Text1 0 \n3 Text1 0 \n4 Text1 sub1 \n5 Text1 sub2 \n6 Text2 0 \n7 Text2 0 \n8 Text2 sub1_sub2\n9 Text2 sub3 \n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18469498/"
] |
74,548,178
|
<pre class="lang-sql prettyprint-override"><code>select max(to_number(ltrim(aefo_number,'VE')))
from exemption
where aefo_number like 'E%'
or aefo_number like 'V%'
</code></pre>
<p>I am getting Function to_number(text) does not exist error for the above select statement and I am unable to convert it.</p>
<p>If anyone know the syntax for the select statement please let me know</p>
|
[
{
"answer_id": 74548538,
"author": "a_horse_with_no_name",
"author_id": 330315,
"author_profile": "https://Stackoverflow.com/users/330315",
"pm_score": 2,
"selected": false,
"text": "to_number() to_number(ltrim(aefo_number,'VE'), '99999999999') numeric integer select max(ltrim(aefo_number,'VE')::integer)\nfrom exemption\nwhere aefo_number like 'E%'\nor aefo_number like 'V%'\n"
},
{
"answer_id": 74548621,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 0,
"selected": false,
"text": "V E select MAX(SUBSTR(aefo_number,2)::integer)\nfrom exemption\nwhere aefo_number like 'E%'\nor aefo_number like 'V%'\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20561493/"
] |
74,548,189
|
<p>I have been working with AWS Athena for a while and need to do create a backup and version control of the views. I'm trying to build an automation for the backup to run daily and get all the views.
I tried to find a way to copy all the views created in Athena using boto3, but I couldn't find a way to do that. With Dbeaver I can see and export the views SQL script but from what I've seen only one at a time which not serve the goal.
I'm open for any way.</p>
<p>I try to find answer to my question in boto3 documentation and Dbeaver documentation. read thread on stack over flow and some google search did not took me so far.</p>
|
[
{
"answer_id": 74552985,
"author": "John Rotenstein",
"author_id": 174777,
"author_profile": "https://Stackoverflow.com/users/174777",
"pm_score": 0,
"selected": false,
"text": "SHOW CREATE TABLE [db_name.]table_name table_name"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19487309/"
] |
74,548,240
|
<p>say I have four separate lists like so:</p>
<pre><code>colors = ['red', 'blue', 'green', 'black']
widths = [10.0, 12.0, 8.0, 22.0]
lengths = [35.5, 41.0, 36.5, 36.0]
materials = ['steel', 'copper', 'iron', 'steel']
</code></pre>
<p>What's the best way to take this data and create a list of dicts representing objects like so:</p>
<pre><code>objects = [{'color': 'red', 'width': 10.0, 'length': 35.5, 'material': 'steel'}, {'color': 'blue', 'width': 12.0, 'length': 41.0, 'material': 'copper'}, {'color': 'green', 'width': 8.0, 'length': 36.5, 'material': 'iron'}, {'color': 'black', 'width': 22.0, 'length': 36.0, 'material': 'steel'}]
</code></pre>
<p>I'm currently using a for loop:</p>
<pre><code>for color in colors:
obj = {}
obj['color'] = color
obj['width'] = widths[colors.index(color)]
obj['length'] = lengths[colors.index(color)]
obj['material'] = materials[colors.index(color)]
objects.append(obj)
</code></pre>
<p>but this is slow for large lists so I'm wondering if there's a faster way</p>
|
[
{
"answer_id": 74548365,
"author": "CodeKorn",
"author_id": 10882128,
"author_profile": "https://Stackoverflow.com/users/10882128",
"pm_score": 0,
"selected": false,
"text": "range colors = ['red', 'blue', 'green', 'black']\nwidths = [10.0, 12.0, 8.0, 22.0]\nlengths = [35.5, 41.0, 36.5, 36.0]\nmaterials = ['steel', 'copper', 'iron', 'steel']\nobjects = []\nfor i in range(len(colors)):\n d = {}\n d['colors'] = colors[i]\n d['widths'] = widths[i]\n d['lengths'] = lengths[i]\n d['materials'] = materials[i]\n objects.append(d)\n colors"
},
{
"answer_id": 74548378,
"author": "0x0fba",
"author_id": 20339407,
"author_profile": "https://Stackoverflow.com/users/20339407",
"pm_score": 3,
"selected": true,
"text": "objects = [{\"color\": c, \"width\": w, \"length\": l, \"material\": m} for c, w, l, m in zip(colors, widths, lengths, materials)]\n"
},
{
"answer_id": 74548419,
"author": "Mauro Vanetti",
"author_id": 581285,
"author_profile": "https://Stackoverflow.com/users/581285",
"pm_score": 0,
"selected": false,
"text": "zip objects = []\nfor object in zip(colors, widths, lengths, materials):\n objects.append({\n 'color': object[0], \n 'width': object[1], \n 'length': object[2], \n 'material': object[3]})\n"
},
{
"answer_id": 74548469,
"author": "Amin",
"author_id": 10281248,
"author_profile": "https://Stackoverflow.com/users/10281248",
"pm_score": 0,
"selected": false,
"text": "zipped = zip(colors, widths, lengths, materials)\nobjects = [{\"color\": color, \"width\": width, \"length\": length, \"material\": material} for color, width, length, material in zipped]\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12251859/"
] |
74,548,251
|
<p>I'm trying to get the Username and Date <code>'y/m/d'</code> from a <code>/var/log/secure</code>, however when I'm trying to use <code>awk</code>, it only provides the date.</p>
<p>Sample of a secure log file.</p>
<pre><code>2022-11-23T02:03:24.594880+01:00 servername su: pam_unix(su:session): session opened for user john.doe by (uid=0)
</code></pre>
<p>What I'm expecting to print is: <code>2022-11-23 john.doe</code></p>
<p>Here's my code.</p>
<pre><code>cat /var/log/secure | grep 'session opened' | awk -FT '{print $1 " " " User: " $9 }'
</code></pre>
<p>"The output is only: <code>2022-11-23 User:"</code></p>
|
[
{
"answer_id": 74549039,
"author": "The fourth bird",
"author_id": 5424988,
"author_profile": "https://Stackoverflow.com/users/5424988",
"pm_score": 3,
"selected": true,
"text": "T 2022-11-23 User: T awk -F\"[[:blank:]]+|T\" '{print $1, $10 }' file\n T awk '{split($1,a,\"T\"); print a[1], $9}'\n T T awk 'match($0, /^[0-9]{4}(-[0-9]{2}){2}T/) {\n print substr($0,RSTART,RLENGTH-1), $9\n}'\n 2022-11-23 john.doe\n"
},
{
"answer_id": 74549275,
"author": "Jetchisel",
"author_id": 4452265,
"author_profile": "https://Stackoverflow.com/users/4452265",
"pm_score": 1,
"selected": false,
"text": "date username user by sed sed '/session opened/s/^\\([^T]*\\).* user \\(.*\\) by .*$/\\1 \\2/' /var/log/secure\n"
},
{
"answer_id": 74549687,
"author": "RavinderSingh13",
"author_id": 5866580,
"author_profile": "https://Stackoverflow.com/users/5866580",
"pm_score": 2,
"selected": false,
"text": "awk awk -F'T| user | by ' '{print $1,$3}' Input_file\n"
},
{
"answer_id": 74554693,
"author": "Ed Morton",
"author_id": 1745001,
"author_profile": "https://Stackoverflow.com/users/1745001",
"pm_score": 1,
"selected": false,
"text": "cat grep $ awk '/session opened/{print substr($0,1,10), $9}' /var/log/secure\n2022-11-23 john.doe\n grep grep 'session opened' | awk '{foo}' awk '/session opened/{foo}' cat"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18653424/"
] |
74,548,257
|
<p>So I have a dataframe with 3 columns: date, price, text</p>
<pre><code>import pandas as pd
from datetime import datetime
import random
columns = ('dates','prices','text')
datelist = pd.date_range(datetime.today(), periods=5).tolist()
prices = []
for i in range(0, 5):
prices.append(random.randint(50, 60))
text =['AAA','BBB','CCC','DDD','EEE']
df = pd.DataFrame({'dates': datelist, 'price':prices, 'text':text})
</code></pre>
<pre><code> dates price text
0 2022-11-23 14:11:51.142574 51 AAA
1 2022-11-24 14:11:51.142574 57 BBB
2 2022-11-25 14:11:51.142574 52 CCC
3 2022-11-26 14:11:51.142574 51 DDD
4 2022-11-27 14:11:51.142574 59 EEE
</code></pre>
<p>I want to plot date and price on a line chart, but when I hover over the line I want it to show the text from the row corresponding to that date.</p>
<p>eg when I hover over the point corresponding to 2022-11-27 I want the text to show 'EEE'</p>
<p>ive tried a few things in matplotlib etc but can only get data from the x and y axis to show but I cant figure out how to show data from a different column.</p>
|
[
{
"answer_id": 74548439,
"author": "ZachW",
"author_id": 8462327,
"author_profile": "https://Stackoverflow.com/users/8462327",
"pm_score": 2,
"selected": true,
"text": "import plotly.graph_objects as go\n\nfig = go.Figure(data=go.Scatter(x=df['dates'], y=df['price'], mode='lines+markers', text=df['text']))\nfig.show()\n"
},
{
"answer_id": 74549204,
"author": "LoneWanderer",
"author_id": 7237062,
"author_profile": "https://Stackoverflow.com/users/7237062",
"pm_score": 0,
"selected": false,
"text": "from matplotlib import pyplot as plt\n\nfrom matplotlib.patheffects import withSimplePatchShadow\nimport mplcursors\nfrom pandas import DataFrame\n\n\ndf = DataFrame(\n dict(\n Suburb=[\"Ames\", \"Somerset\", \"Sawyer\"],\n Area=[1023, 2093, 723],\n SalePrice=[507500, 647000, 546999],\n )\n)\n\ndf.plot.scatter(x=\"Area\", y=\"SalePrice\", s=100)\n\n\ndef show_hover_panel(get_text_func=None):\n cursor = mplcursors.cursor(\n hover=2, # Transient\n annotation_kwargs=dict(\n bbox=dict(\n boxstyle=\"square,pad=0.5\",\n facecolor=\"white\",\n edgecolor=\"#ddd\",\n linewidth=0.5,\n path_effects=[withSimplePatchShadow(offset=(1.5, -1.5))],\n ),\n linespacing=1.5,\n arrowprops=None,\n ),\n highlight=True,\n highlight_kwargs=dict(linewidth=2),\n )\n\n if get_text_func:\n cursor.connect(\n event=\"add\",\n func=lambda sel: sel.annotation.set_text(get_text_func(sel.index)),\n )\n\n return cursor\n\n\ndef on_add(index):\n item = df.iloc[index]\n parts = [\n f\"Suburb: {item.Suburb}\",\n f\"Area: {item.Area:,.0f}m²\",\n f\"Sale price: ${item.SalePrice:,.0f}\",\n ]\n\n return \"\\n\".join(parts)\n\n\nshow_hover_panel(on_add)\n\nplt.show()\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9410998/"
] |
74,548,261
|
<p>I am developing an internal TypeScript library which needs to call a couple of GraphQL endpoints. The library is supposed be imported in front end projects, but it is not dependent on any specific framework (like angular or react).</p>
<p>I would like to be able to use a GraphQL library for GraphQL calls. I checked Apollo, but it brings react with it (which I don't need). In <a href="https://github.com/graphql/graphql-js#using-in-a-browser" rel="nofollow noreferrer">the graphql-js documentation</a>, it states that it can be used in browser, at the same time they only provide code samples for server-side code.</p>
<p>So far, I am just making plain rest class, but I am interested in generating at least types automatically as it is inconvenient.</p>
<p><strong>Q:</strong> How to use graphql-js in the client code? Or is there any other way to call graphql endpoints without having to import Apollo with react?</p>
<p>Any suggestion is appreciated.</p>
|
[
{
"answer_id": 74548439,
"author": "ZachW",
"author_id": 8462327,
"author_profile": "https://Stackoverflow.com/users/8462327",
"pm_score": 2,
"selected": true,
"text": "import plotly.graph_objects as go\n\nfig = go.Figure(data=go.Scatter(x=df['dates'], y=df['price'], mode='lines+markers', text=df['text']))\nfig.show()\n"
},
{
"answer_id": 74549204,
"author": "LoneWanderer",
"author_id": 7237062,
"author_profile": "https://Stackoverflow.com/users/7237062",
"pm_score": 0,
"selected": false,
"text": "from matplotlib import pyplot as plt\n\nfrom matplotlib.patheffects import withSimplePatchShadow\nimport mplcursors\nfrom pandas import DataFrame\n\n\ndf = DataFrame(\n dict(\n Suburb=[\"Ames\", \"Somerset\", \"Sawyer\"],\n Area=[1023, 2093, 723],\n SalePrice=[507500, 647000, 546999],\n )\n)\n\ndf.plot.scatter(x=\"Area\", y=\"SalePrice\", s=100)\n\n\ndef show_hover_panel(get_text_func=None):\n cursor = mplcursors.cursor(\n hover=2, # Transient\n annotation_kwargs=dict(\n bbox=dict(\n boxstyle=\"square,pad=0.5\",\n facecolor=\"white\",\n edgecolor=\"#ddd\",\n linewidth=0.5,\n path_effects=[withSimplePatchShadow(offset=(1.5, -1.5))],\n ),\n linespacing=1.5,\n arrowprops=None,\n ),\n highlight=True,\n highlight_kwargs=dict(linewidth=2),\n )\n\n if get_text_func:\n cursor.connect(\n event=\"add\",\n func=lambda sel: sel.annotation.set_text(get_text_func(sel.index)),\n )\n\n return cursor\n\n\ndef on_add(index):\n item = df.iloc[index]\n parts = [\n f\"Suburb: {item.Suburb}\",\n f\"Area: {item.Area:,.0f}m²\",\n f\"Sale price: ${item.SalePrice:,.0f}\",\n ]\n\n return \"\\n\".join(parts)\n\n\nshow_hover_panel(on_add)\n\nplt.show()\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2065796/"
] |
74,548,266
|
<p>To reduce my last question (it was a bit complicated). Is it possible to change the names of "array objects" dynamically?</p>
<p>I have a list of variables (structure must stay like this way):</p>
<pre><code>var markers = []
var markerHouse = ... markers.push(markerHouse);
var markerAnimal = ... markers.push(markerAnimal);
var markerCar = ... markers.push(markerCar);
// aso.
</code></pre>
<p>I tried lots of ways to change the array object names, like this one:</p>
<pre><code>var NewMarkers = "markerHouse, markerAnimal"; // string content, generated by a function
var NewMarkersArray = NewMarkers.split(","); // create array of this string
var NewGroup = L.layerGroup([NewMarkersArray]); // request for array of objects
</code></pre>
<p>The result of <code>NewGroup</code> is:</p>
<pre><code>L.layerGroup(["markerHouse", "markerAnimal"]);
</code></pre>
<p>And I get a "TypeError: cannot use 'in' operator to search for "_leaflet_id" in "markerHouse" ...</p>
<p>But what I need is:</p>
<pre><code>L.layerGroup([markerHouse, markerAnimal]);
</code></pre>
|
[
{
"answer_id": 74548330,
"author": "voidbrain",
"author_id": 1000137,
"author_profile": "https://Stackoverflow.com/users/1000137",
"pm_score": 0,
"selected": false,
"text": "L.layerGroup([eval(\"markerHouse\"), eval(\"markerAnimal\")]);\n"
},
{
"answer_id": 74548496,
"author": "George Marios",
"author_id": 10622933,
"author_profile": "https://Stackoverflow.com/users/10622933",
"pm_score": 1,
"selected": false,
"text": "L.layerGroup( [ window[\"markerHouse\"], window[\"markerAnimal\")] ]);\n var dynamicallyGeneratedArrayOfVarNames = \"markerHouse,markerAnimal\".split(',');\nL.layerGroup( [ window[dynamicallyGeneratedArrayOfVarNames[0]], window[dynamicallyGeneratedArrayOfVarNames[1])] ]);\n var markerHouse = 'markerHouse content';\nvar markerAnimal = 'markerAnimal content'\n\nconsole.log(window['markerHouse']);\nconsole.log(window['markerAnimal']);\n\n// And with dynamically retrieved names\nvar NewMarkers = \"markerHouse, markerAnimal\"; // string content, generated by a function\nvar NewMarkersArray = NewMarkers.split(\", \"); // create array of this string\nconsole.log(window[NewMarkersArray[0]])\nconsole.log(window[NewMarkersArray[1]]) const myvars = {}\nmyvars.markerHouse = \"any type of marker house data\"\nmyvars.markerAnimal = \"any type of marker animal data\"\n\nL.layerGroup( [ myvars[\"markerHouse\"], myvars[\"markerAnimal\")] ]);\n"
},
{
"answer_id": 74549197,
"author": "Pointy",
"author_id": 182668,
"author_profile": "https://Stackoverflow.com/users/182668",
"pm_score": 0,
"selected": false,
"text": "const allMarkers = {\n house: whatever,\n animal: whatever,\n boat: whatever,\n // ...\n };\n\n let markerNames = [\"house\", \"boat\"];\n\n let markers = markerNames.map(name => allMarkers[name]);\n let newGroup = L.layerGroup(markers);\n allMarkers .map()"
},
{
"answer_id": 74549532,
"author": "Trevor Dixon",
"author_id": 711902,
"author_profile": "https://Stackoverflow.com/users/711902",
"pm_score": 0,
"selected": false,
"text": "const vars = {\n 'markerHouse': markerHouse,\n 'markerAnimal': markerAnimal,\n};\n const vars = {markerHouse, markerAnimal};\n var NewGroup = L.layerGroup(NewMarkersArray.map(v => vars[v]));\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4399382/"
] |
74,548,279
|
<p>So would like to create an 2D array of characters for testing purposes. Here is my code.</p>
<pre><code> const int rows = 4;
const int columns = 6;
//char field[rows][columns];
//fill_field(rows,columns,field);
char field[rows][columns] = {
"A BCD ",
"B CDA ",
"C DAB ",
"D ABC "
};
</code></pre>
<p>I'm getting error saying "variable-sized object may not be initialized" and "excess elements in array initializer" for every string i have typed.</p>
|
[
{
"answer_id": 74548383,
"author": "0___________",
"author_id": 6110094,
"author_profile": "https://Stackoverflow.com/users/6110094",
"pm_score": 0,
"selected": false,
"text": "const int #define rows 4\n#define columns 6\n"
},
{
"answer_id": 74548401,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 1,
"selected": false,
"text": "columns 7 '\\0' const int rows = 4;\nconst int columns = 6;\n//char field[rows][columns];\n//fill_field(rows,columns,field);\nchar field[rows][columns] = {\n \"A BCD \",\n \"B CDA \", \n \"C DAB \", \n \"D ABC \"\n };\n rows columns enum { rows = 4, columns = 7 };\n//char field[rows][columns];\n//fill_field(rows,columns,field);\nchar field[rows][columns] = {\n \"A BCD \",\n \"B CDA \", \n \"C DAB \", \n \"D ABC \"\n };\n const char * field[] = { \"A BCD \", \"B CDA \", \"C DAB \", \"D ABC \" };\n\nconst size_t N = sizeof( field ) / sizeof( *field );\n for ( size_t i = 0; i < N; i++ )\n{\n for ( size_t j = 0; field[i][j] != '\\0'; j++ )\n {\n putchar( field[i][j] );\n }\n putchar( '\\n' );\n}\n"
},
{
"answer_id": 74548624,
"author": "AnthonyLambert",
"author_id": 31762,
"author_profile": "https://Stackoverflow.com/users/31762",
"pm_score": -1,
"selected": true,
"text": "int main()\n {\n char field[4][6] = {\n {'A',' ','B','C','D',' '},\n {'B',' ','C','D','A',' '},\n {'C',' ','D','A','B',' '},\n {'D',' ','A','B','C',' '},\n };\n \n char fieldWithNulls[4][7] = {\n {'A',' ','B','C','D',' ', 0},\n {'B',' ','C','D','A',' ', 0},\n {'C',' ','D','A','B',' ', 0},\n {'D',' ','A','B','C',' ', 0},\n };\n\n char fieldWithNullsAndStrings[][7] = {\n {\"A BCD \"},\n {\"B CDA \"},\n {\"C DAB \"},\n {\"D ABC \"},\n };\n\n char fieldWithNullsAndStrings2[][7] = {\n \"A BCD \",\n \"B CDA \",\n \"C DAB \",\n \"D ABC \",\n };\n }\n char fieldWithNulls[][7] = {\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20582642/"
] |
74,548,292
|
<p>I am going to be given an array of integers. My job is to take that array and find an index N where the sum of the integers to the left of N is equal to the sum of the integers to the right of N. If there is no index that would make this happen, return -1.</p>
<p>My code is:</p>
<pre class="lang-py prettyprint-override"><code>def find_even_index(arr):
#your code here
for i in range(len(arr)):
if sum(arr[0:i]) == sum(arr[i+1:len(arr)]):
return i
else:
return -1
</code></pre>
<p>This code works for some lists, but doesn't work for others. What's wrong here? E.g. it doesn't work for [14, -6, -1, -8, 8, 16, 4, -10, -11, -10, 2, 8, 4, 14, -8, -10, 21, -10, -1] it should return 12 but returns -1, likewise for a lot of other lists where it should return an index but returns -1.</p>
|
[
{
"answer_id": 74548383,
"author": "0___________",
"author_id": 6110094,
"author_profile": "https://Stackoverflow.com/users/6110094",
"pm_score": 0,
"selected": false,
"text": "const int #define rows 4\n#define columns 6\n"
},
{
"answer_id": 74548401,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 1,
"selected": false,
"text": "columns 7 '\\0' const int rows = 4;\nconst int columns = 6;\n//char field[rows][columns];\n//fill_field(rows,columns,field);\nchar field[rows][columns] = {\n \"A BCD \",\n \"B CDA \", \n \"C DAB \", \n \"D ABC \"\n };\n rows columns enum { rows = 4, columns = 7 };\n//char field[rows][columns];\n//fill_field(rows,columns,field);\nchar field[rows][columns] = {\n \"A BCD \",\n \"B CDA \", \n \"C DAB \", \n \"D ABC \"\n };\n const char * field[] = { \"A BCD \", \"B CDA \", \"C DAB \", \"D ABC \" };\n\nconst size_t N = sizeof( field ) / sizeof( *field );\n for ( size_t i = 0; i < N; i++ )\n{\n for ( size_t j = 0; field[i][j] != '\\0'; j++ )\n {\n putchar( field[i][j] );\n }\n putchar( '\\n' );\n}\n"
},
{
"answer_id": 74548624,
"author": "AnthonyLambert",
"author_id": 31762,
"author_profile": "https://Stackoverflow.com/users/31762",
"pm_score": -1,
"selected": true,
"text": "int main()\n {\n char field[4][6] = {\n {'A',' ','B','C','D',' '},\n {'B',' ','C','D','A',' '},\n {'C',' ','D','A','B',' '},\n {'D',' ','A','B','C',' '},\n };\n \n char fieldWithNulls[4][7] = {\n {'A',' ','B','C','D',' ', 0},\n {'B',' ','C','D','A',' ', 0},\n {'C',' ','D','A','B',' ', 0},\n {'D',' ','A','B','C',' ', 0},\n };\n\n char fieldWithNullsAndStrings[][7] = {\n {\"A BCD \"},\n {\"B CDA \"},\n {\"C DAB \"},\n {\"D ABC \"},\n };\n\n char fieldWithNullsAndStrings2[][7] = {\n \"A BCD \",\n \"B CDA \",\n \"C DAB \",\n \"D ABC \",\n };\n }\n char fieldWithNulls[][7] = {\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16843327/"
] |
74,548,309
|
<p>I am starting to learn HTML and CSS and I decided to try to make a website with dreamweaver just for practice.
But I am strongly struggling with making my website responsive. I tend to give fix position to every element and obviously that is very bad cause if you re-size the website is going to be completely destroyed.
For that reason I would love if someone could have a look at my code and tell me what things I could change to make it more responsive and therefore adapt to different screen resolutions.</p>
<p>Here is my HTML:
`</p>
<pre><code><!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Home Page</title>
<link href="../style/style.css" rel="stylesheet" type="text/css">
</head>
<body class="body">
<div id="container"> </div>
<div id="left"> </div>
<div id="content">
<nav>
<a href="index.html"><img class="logo-img" src="../images/logo.png" width="150" height="75" alt=""/>
<img class="insta" src="../images/insta.png" width="20" height="20" alt=""/>
<img class="facebook" src="../images/facebook.png" width="20" height="20" alt=""/>
<ul class="navlist">
<li class="navlistitem"><a href="index.html" class="navlist_style">Home</a> </li>
<li class="navlistitem"><a href="classes.html" class="navlist_style">Classes</a></li>
<li class="navlistitem"><a href="Gallery.html" class="navlist_style">Gallery</a> </li>
<li class="navlistitem"><a href="Location.html" class="navlist_style">Location</a> </li>
<li class="navlistitem"><a href="Contact.html" class="navlist_style">Contact</a></li>
</ul>
</nav>
</div>
<div id="right"> </div>
<img class="ban" src="../images/ban.jpg" width="1139.5px" height="200px" alt=""/>
</body>
</html>
</code></pre>
<p><code>and here is the CSS for this HTML code:</code></p>
<pre><code>nav {
background-color:#3D9CC5;
margin: 0;
padding: 20;
list-style-type: none;
height: 78px;
width: 100%;
}
body {
margin:0;
padding:0;
}
.navlist {
padding: 0px;
list-style-type: none;
overflow: hidden;
}
.navlistitem {
padding-top: 12px;
padding-right: 17px;
padding-bottom: 9px;
padding-left: 1px;
position: relative;
float: left;
font-family: Consolas, "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", Monaco, "Courier New", monospace;
}
.navlist_style:active {
color:#000000;
}
.navlist_style {
text-decoration: none;
margin-top: 0px;
color: #FFFFFF;
font-style: normal;
font-size: 22px;
text-align: center;
margin-right: 40px;
font-family: Gotham, "Helvetica Neue", Helvetica, Arial, sans-serif;
}
.navlist_style:hover {
color:#000000;
}
.navlist_style::before {
}
.logo-img {
float: left;
margin-left: 250px;
font-family: "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", "DejaVu Sans", Verdana, sans-serif;
}
.insta {
padding-top: 30px;
float: right;
margin-right: 30px;
}
.facebook {
float: right;
padding-top: 30px;
margin-right: 7px;
}
.ban {
margin-left: 190px;
}
.body {
margin: 0px;
}
.navlist_style::before {
content: '';
display:block;
height: 5px;
background-color:#000000;
position: absolute;
top: 0px;
width: 0px;
transition: all ease-in-out 250ms;
}
.navlist_style:hover::before {
width:57%;
}
#container {
width: 100%;
min-height: 100%;
position: relative;
}
#left, #right {
width: 17%;
height: 3000px;
position: absolute;
z-index: -1;
}
#left {
left: 0;
background-color:#EDEBEB;
}
#right {
right:0;
background-color:#EDEBEB;
}
</code></pre>
<p>`
If you re-size the website you will see how it gets destroyed.
Another question, how can I make the menus align in the center with the nav bar?
Sorry if it's too much I know its not great but I am just starting...
Thanks for everything!</p>
<p>I think one of the ways to fix this is instead of setting X pixels the width just give a % of the page, but not sure how to do that. Every response is appreciated, thanks!</p>
|
[
{
"answer_id": 74548383,
"author": "0___________",
"author_id": 6110094,
"author_profile": "https://Stackoverflow.com/users/6110094",
"pm_score": 0,
"selected": false,
"text": "const int #define rows 4\n#define columns 6\n"
},
{
"answer_id": 74548401,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 1,
"selected": false,
"text": "columns 7 '\\0' const int rows = 4;\nconst int columns = 6;\n//char field[rows][columns];\n//fill_field(rows,columns,field);\nchar field[rows][columns] = {\n \"A BCD \",\n \"B CDA \", \n \"C DAB \", \n \"D ABC \"\n };\n rows columns enum { rows = 4, columns = 7 };\n//char field[rows][columns];\n//fill_field(rows,columns,field);\nchar field[rows][columns] = {\n \"A BCD \",\n \"B CDA \", \n \"C DAB \", \n \"D ABC \"\n };\n const char * field[] = { \"A BCD \", \"B CDA \", \"C DAB \", \"D ABC \" };\n\nconst size_t N = sizeof( field ) / sizeof( *field );\n for ( size_t i = 0; i < N; i++ )\n{\n for ( size_t j = 0; field[i][j] != '\\0'; j++ )\n {\n putchar( field[i][j] );\n }\n putchar( '\\n' );\n}\n"
},
{
"answer_id": 74548624,
"author": "AnthonyLambert",
"author_id": 31762,
"author_profile": "https://Stackoverflow.com/users/31762",
"pm_score": -1,
"selected": true,
"text": "int main()\n {\n char field[4][6] = {\n {'A',' ','B','C','D',' '},\n {'B',' ','C','D','A',' '},\n {'C',' ','D','A','B',' '},\n {'D',' ','A','B','C',' '},\n };\n \n char fieldWithNulls[4][7] = {\n {'A',' ','B','C','D',' ', 0},\n {'B',' ','C','D','A',' ', 0},\n {'C',' ','D','A','B',' ', 0},\n {'D',' ','A','B','C',' ', 0},\n };\n\n char fieldWithNullsAndStrings[][7] = {\n {\"A BCD \"},\n {\"B CDA \"},\n {\"C DAB \"},\n {\"D ABC \"},\n };\n\n char fieldWithNullsAndStrings2[][7] = {\n \"A BCD \",\n \"B CDA \",\n \"C DAB \",\n \"D ABC \",\n };\n }\n char fieldWithNulls[][7] = {\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20582754/"
] |
74,548,343
|
<p>We have the following two data frames</p>
<pre><code>temp = pd.DataFrame(np.array([['I am feeling very well',1],['It is hard to believe this happened',0],
['What is love?',1], ['No new friends',0],
['I love this show',1],['Amazing day today',1]]),
columns = ['message','sentiment'])
temp_truncated = pd.DataFrame(np.array([['I am feeling very',1],['It is hard to believe',1],
['What is',1], ['Amazing day',1]]),
columns = ['message','cutoff'])
</code></pre>
<p>My idea is to create a third DataFrame that would represent the inner join between <code>temp</code> and <code>temp_truncated</code> by finding matches in <code>temp</code> that start with / contain the strings in <code>temp_truncated</code></p>
<p>Desired Output:</p>
<pre><code> message sentiment cutoff
0 I am feeling very well 1 1
1 It is hard to believe this happened 0 1
2 What is love 1 1
3 Amazing day today 1 1
</code></pre>
|
[
{
"answer_id": 74548471,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 4,
"selected": true,
"text": "import re\npattern = '|'.join(map(re.escape, temp_truncated['message']))\n\nkey = temp['message'].str.extract(f'({pattern})', expand=False)\n\nout = (temp\n .merge(temp_truncated.rename(columns={'message': 'sub'}),\n left_on=key, right_on='sub')\n .drop(columns='sub')\n)\n message sentiment cutoff\n0 I am feeling very well 1 1\n1 It is hard to believe this happened 0 1\n2 What is love? 1 1\n3 Amazing day today 1 1\n"
},
{
"answer_id": 74548595,
"author": "abokey",
"author_id": 16120011,
"author_profile": "https://Stackoverflow.com/users/16120011",
"pm_score": 0,
"selected": false,
"text": "rapidfuzz pandas.merge #pip install rapidfuzz\nfrom rapidfuzz import process\n\nout = (\n temp_truncated\n .assign(message_adapted = (temp_truncated['message']\n .map(lambda x: process.extractOne(x, temp['message']))).str[0])\n .merge(temp, left_on=\"message_adapted\", right_on=\"message\", how=\"left\", suffixes=(\"_\", \"\"))\n .drop(columns=[\"message_adapted\", \"message_\"])\n .loc[:, temp.columns.tolist() + [\"cutoff\"]]\n )\n print(out)\n message sentiment cutoff\n0 I am feeling very well 1 1\n1 It is hard to believe this happened 0 1\n2 What is love? 1 1\n3 Amazing day today 1 1\n"
},
{
"answer_id": 74548796,
"author": "Paul",
"author_id": 7194474,
"author_profile": "https://Stackoverflow.com/users/7194474",
"pm_score": 0,
"selected": false,
"text": "str.startswith str. str.contains matches = temp_truncated.message.apply(\n lambda x: temp[temp.message.str.startswith(x)]['sentiment']\n).dropna(how='all')\n matches temp_truncated temp temp matches temp temp temp_truncated df = temp.iloc[matches.columns]\ndf.index = matches.index\ndf = df.merge(temp_truncated['cutoff'], left_index=True, right_index=True)\n message sentiment cutoff\n0 I am feeling very well 1 1\n1 It is hard to believe this happened 0 1\n2 What is love? 1 1\n3 Amazing day today 1 1\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8972207/"
] |
74,548,359
|
<p>I'm using Google Tag Manager to configure events for an e-commerce and I need search for the word "trash" in the string below:</p>
<p><code>"SVGSVGElement: html > body.template-home.overflow-none > div.theme-w" + "ide#container > form.js-ajax-cart-panel.js-fullscreen-modal.ajax-car" + "t-container.modal-right.modal-xs.modal-xs-right.modal-xs-right-out#a" + "jax-cart-details > div.modal-xs-dialog > div.modal-content > div.aja" + "x-cart-body.modal-right-body.modal-xs-body > div.js-ajax-cart-list.a" + "jax-cart-table.pull-left > div.js-cart-item.js-cart-item-shippable.a" + "jax-cart-item > div.ajax-cart-item-delete-col.cart-delete-container." + "ajax-cart-item-col.text-right > button.cart-btn-delete.ajax-cart-btn" + "-delete.pull-right.p-top-none > div.cart-delete-svg-icon.svg-icon-te" + "xt > svg.svg-trash-icon"</code></p>
<p>Question:</p>
<p>What expression do I use to search for the word "trash" in the string at Google Tag Manager?</p>
<p>Thanks for listening!</p>
<p>I have already tested the following RegEx:</p>
<p><code>\btrash\b /(trash\d+(\.\d)*)/I /trash/g</code></p>
<p>But none of them worked.</p>
|
[
{
"answer_id": 74548471,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 4,
"selected": true,
"text": "import re\npattern = '|'.join(map(re.escape, temp_truncated['message']))\n\nkey = temp['message'].str.extract(f'({pattern})', expand=False)\n\nout = (temp\n .merge(temp_truncated.rename(columns={'message': 'sub'}),\n left_on=key, right_on='sub')\n .drop(columns='sub')\n)\n message sentiment cutoff\n0 I am feeling very well 1 1\n1 It is hard to believe this happened 0 1\n2 What is love? 1 1\n3 Amazing day today 1 1\n"
},
{
"answer_id": 74548595,
"author": "abokey",
"author_id": 16120011,
"author_profile": "https://Stackoverflow.com/users/16120011",
"pm_score": 0,
"selected": false,
"text": "rapidfuzz pandas.merge #pip install rapidfuzz\nfrom rapidfuzz import process\n\nout = (\n temp_truncated\n .assign(message_adapted = (temp_truncated['message']\n .map(lambda x: process.extractOne(x, temp['message']))).str[0])\n .merge(temp, left_on=\"message_adapted\", right_on=\"message\", how=\"left\", suffixes=(\"_\", \"\"))\n .drop(columns=[\"message_adapted\", \"message_\"])\n .loc[:, temp.columns.tolist() + [\"cutoff\"]]\n )\n print(out)\n message sentiment cutoff\n0 I am feeling very well 1 1\n1 It is hard to believe this happened 0 1\n2 What is love? 1 1\n3 Amazing day today 1 1\n"
},
{
"answer_id": 74548796,
"author": "Paul",
"author_id": 7194474,
"author_profile": "https://Stackoverflow.com/users/7194474",
"pm_score": 0,
"selected": false,
"text": "str.startswith str. str.contains matches = temp_truncated.message.apply(\n lambda x: temp[temp.message.str.startswith(x)]['sentiment']\n).dropna(how='all')\n matches temp_truncated temp temp matches temp temp temp_truncated df = temp.iloc[matches.columns]\ndf.index = matches.index\ndf = df.merge(temp_truncated['cutoff'], left_index=True, right_index=True)\n message sentiment cutoff\n0 I am feeling very well 1 1\n1 It is hard to believe this happened 0 1\n2 What is love? 1 1\n3 Amazing day today 1 1\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20582645/"
] |
74,548,391
|
<p>I used a for-loop in my code and my output prints vertically, but what I want is it to print horizontally. For example</p>
<pre class="lang-java prettyprint-override"><code>for (int i = 0; i < 10; i++ ) {
System.out.println("i is " + (i+1) + " | ");
}
</code></pre>
<p>For this the output is:</p>
<pre class="lang-none prettyprint-override"><code>i is 1 |
i is 2 |
i is 3 |
and so on...
</code></pre>
<p>The output I want is:</p>
<pre class="lang-none prettyprint-override"><code>i is 1 | i is 2 | i is 3 | ... and so on
</code></pre>
|
[
{
"answer_id": 74548493,
"author": "aatwork",
"author_id": 14263933,
"author_profile": "https://Stackoverflow.com/users/14263933",
"pm_score": 1,
"selected": false,
"text": "for (int i = 0; i < 10; i++ ) {\n System.out.print(\"i is \" + (i+1) + \" | \");\n}\n"
},
{
"answer_id": 74548509,
"author": "Bhanu Pratap",
"author_id": 20582851,
"author_profile": "https://Stackoverflow.com/users/20582851",
"pm_score": 0,
"selected": false,
"text": "print() println() for (int i = 0; i < 10; i++ ) {\n System.out.print(\"i is \" + (i+1) + \" | \");\n}\n"
},
{
"answer_id": 74548533,
"author": "Ela Singh",
"author_id": 13180602,
"author_profile": "https://Stackoverflow.com/users/13180602",
"pm_score": 0,
"selected": false,
"text": "System.out.print System.out.println println for (int i = 0; i < 10; i++) {\n System.out.print(\"i is \" + (i + 1) + \" | \");\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20136181/"
] |
74,548,395
|
<p>I am making a post request to the tiktok API, entering the 3 parameters that are requested, but when I carry out the request, it shows me the following: "Required fields are missing: app_id is required.", I attach an image:</p>
<p><a href="https://i.stack.imgur.com/AOuEU.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>but when performing the same procedure in postman if I have a positive response.</p>
<p>here is my code:</p>
<p>my route:</p>
<pre><code>Route::get('callback-tiktok', [AuthsController::class, 'SocialAuth']);
</code></pre>
<p>my controller:</p>
<pre><code> <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
class AuthsController extends Controller
{
public function SocialAuth(Request $request)
{
$a = $request->input('auth_code');
// create a guzzle client object here
$client = new Client();
$respuesta = $this->client->request(
'POST',
'https://business-api.tiktok.com/open_api/v1.3/oauth2/access_token/',
[
'form_params' => [
'app_id' => '7112335319877287937',
'secret' => '18f52730856f43ed821187bfa9283794ca360ef1',
'auth_code' => $a
],
'headers' => [
'Content-Type' => 'application /json'
],
]
);
return response()->json($respuesta->getBody()->getContents());
}
}
</code></pre>
<p>When compiling I get the following:</p>
<p>The stream or file "/home/epgutp/tiktok/storage/logs/laravel.log" could not be opened in append mode: Failed to open stream: Permission denied The exception occurred while attempting to log: The stream or file "/home/epgutp/tiktok/storage/logs/laravel.log" could not be opened in append mode: Failed to open stream: Permission denied The exception occurred while attempting to log: The stream or file "/home/epgutp/tiktok/storage/logs/laravel.log" could not be opened in append mode: Failed to open stream: Permission denied The exception occurred while attempting to log: The stream or file "/home/epgutp/tiktok/storage/logs/laravel.log" could not be opened in append mode: Failed to open stream: Permission denied The exception occurred while attempting to log: The stream or file "/home/epgutp/tiktok/storage/logs/laravel.log" could not be opened in append mode: Failed to open stream: Permission denied The exception occurred while attempting to log: The stream or file "/home/epgutp/tiktok/storage/logs/laravel.log" could not be opened in append mode: Failed to open stream: Permission denied The exception occurred while attempting to log: The stream or file....</p>
|
[
{
"answer_id": 74548493,
"author": "aatwork",
"author_id": 14263933,
"author_profile": "https://Stackoverflow.com/users/14263933",
"pm_score": 1,
"selected": false,
"text": "for (int i = 0; i < 10; i++ ) {\n System.out.print(\"i is \" + (i+1) + \" | \");\n}\n"
},
{
"answer_id": 74548509,
"author": "Bhanu Pratap",
"author_id": 20582851,
"author_profile": "https://Stackoverflow.com/users/20582851",
"pm_score": 0,
"selected": false,
"text": "print() println() for (int i = 0; i < 10; i++ ) {\n System.out.print(\"i is \" + (i+1) + \" | \");\n}\n"
},
{
"answer_id": 74548533,
"author": "Ela Singh",
"author_id": 13180602,
"author_profile": "https://Stackoverflow.com/users/13180602",
"pm_score": 0,
"selected": false,
"text": "System.out.print System.out.println println for (int i = 0; i < 10; i++) {\n System.out.print(\"i is \" + (i + 1) + \" | \");\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19474791/"
] |
74,548,404
|
<p>I have a general component that accepts a prop named <code>component</code> and the rest of the props should be the props of that specific component. how can I do it in typescript?</p>
<p>i.e. :</p>
<pre><code> <FormField component={Input} ... />
</code></pre>
<p>This FormField should accept whatever props <code>Input</code> component accepts.</p>
<p>Note:</p>
<ul>
<li>I want to infer the type from props. don't want to pass additional type</li>
</ul>
|
[
{
"answer_id": 74548513,
"author": "A.Vinuela",
"author_id": 9095818,
"author_profile": "https://Stackoverflow.com/users/9095818",
"pm_score": 1,
"selected": false,
"text": "const FormField = <K,>(props: FormFieldProps & K) => {\n //Your component here\n}\n <FormField<InputProps> .... />\n"
},
{
"answer_id": 74550311,
"author": "Doc",
"author_id": 13181643,
"author_profile": "https://Stackoverflow.com/users/13181643",
"pm_score": 0,
"selected": false,
"text": "React.ComponentPropsWithoutRef<T> React.ComponentPropsWithRef<T> const FormField = <K>(props: FormFieldProps & React.ComponentPropsWithoutRef<K>) => {\n //Your component here\n}\n <FormField<typeof AnyComponent> .... />\n // UNFORTUNATELY THIS IS NOT VALID\ninterface FormFieldProps {\ncomponent: T,\nprops: React.ComponentPropsWithoutRef<T>\n}\n T component"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7787393/"
] |
74,548,456
|
<p>How does the code look like to partition the following table. date and status are given, partition column shall be added. Column group is only to explain where the group starts and ends.
Finally, I like to do some analytics, e.g. how long takes the process per group.</p>
<p>In words but don't know to convert to code:
status 'approved' always defines the end. Only an 'open' after 'approval' defines the start. The other 'open' are not relevant.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>date</th>
<th>status</th>
<th>Group</th>
<th>Partition</th>
</tr>
</thead>
<tbody>
<tr>
<td>1.10.2022</td>
<td>open</td>
<td>Group 1 Starts</td>
<td>1</td>
</tr>
<tr>
<td>2.10.2022</td>
<td>waiting</td>
<td></td>
<td>1</td>
</tr>
<tr>
<td>3.10.2022</td>
<td>open</td>
<td></td>
<td>1</td>
</tr>
<tr>
<td>4.10.2022</td>
<td>waiting</td>
<td></td>
<td>1</td>
</tr>
<tr>
<td>5.10.2022</td>
<td>approved</td>
<td>Group 1 Ends</td>
<td>1</td>
</tr>
<tr>
<td>7.10.2022</td>
<td>open</td>
<td>Group 2 Start</td>
<td>2</td>
</tr>
<tr>
<td>8.10.2022</td>
<td>waiting</td>
<td></td>
<td>2</td>
</tr>
<tr>
<td>9.10.2022</td>
<td>open</td>
<td></td>
<td>2</td>
</tr>
<tr>
<td>10.10.2022</td>
<td>waiting</td>
<td></td>
<td>2</td>
</tr>
<tr>
<td>11.10.2022</td>
<td>open</td>
<td></td>
<td>2</td>
</tr>
<tr>
<td>12.10.2022</td>
<td>waiting</td>
<td></td>
<td>2</td>
</tr>
<tr>
<td>15.10.2022</td>
<td>approved</td>
<td>Group 2 Ends</td>
<td>2</td>
</tr>
<tr>
<td>17.10.2022</td>
<td>open</td>
<td>Group 3 Starts</td>
<td>3</td>
</tr>
<tr>
<td>20.10.2022</td>
<td>waiting</td>
<td></td>
<td>3</td>
</tr>
</tbody>
</table>
</div>
<p>Thanks for the solution. Works fine :-) And sorry for not using the right expression. If Group is better than Partition even better...</p>
<p>Can we make it slightly more complicated?</p>
<p>This patter in the table applis to several parent records. So in reality there is an additional column Parent ID. This table below is then for example for parent ID A. There are many more parents.</p>
<p>How can an additional grouping be added by Parent ID?
At eeach new parent the counting starts again at 1</p>
|
[
{
"answer_id": 74548877,
"author": "Mike Organek",
"author_id": 13808319,
"author_profile": "https://Stackoverflow.com/users/13808319",
"pm_score": 1,
"selected": false,
"text": "with groups as ( -- Assign partitions\n select *, \n coalesce(\n sum(case when status = 'approved' then 1 else 0 end) \n over (order by date rows between unbounded preceding \n and 1 preceding),\n 0\n ) + 1 as partition\n from do_part\n)\nselect date, status, \n case -- Construct text descriptions\n when partition != coalesce(lead(partition) over w, partition) \n then format('Group %s Ends', partition)\n when partition = lag(partition) over w\n then '' \n else format('Group %s Starts', partition)\n end as \"group\",\n partition\n from groups\nwindow w as (order by date);\n"
},
{
"answer_id": 74562318,
"author": "jian",
"author_id": 15603477,
"author_profile": "https://Stackoverflow.com/users/15603477",
"pm_score": 0,
"selected": false,
"text": "SELECT DISTINCT ON (date,status)\n date,\n status,\n coalesce(date_d, CURRENT_DATE) AS date_end\nFROM\n do_part t\n LEFT JOIN (\n SELECT\n date AS date_d\n FROM\n do_part\n WHERE\n status = 'approved'\n ORDER BY\n date) s ON s.date_d >= t.date\nORDER BY\n date,status,\n date_d;\n WITH cte AS (\n SELECT DISTINCT ON (date,\n status)\n date,\n status,\n coalesce(date_d, CURRENT_DATE) AS date_end\n FROM\n do_part t\n LEFT JOIN (\n SELECT\n date AS date_d\n FROM\n do_part\n WHERE\n status = 'approved'\n ORDER BY\n date) s ON s.date_d >= t.date\n ORDER BY\n date,\n status,\n date_d\n),\ncte1 AS (\n SELECT\n *,\n date_end - first_value(date) OVER (PARTITION BY date_end ORDER BY date) AS date_gap,\n dense_rank() OVER (ORDER BY date_end),\n CASE WHEN (date = first_value(date) OVER (PARTITION BY date_end ORDER BY date)) THEN\n 'group begin'\n WHEN (status = 'approved') THEN\n 'group end '\n ELSE\n NULL\n END AS grp\nFROM\n cte\n)\nSELECT\n *,\n CASE WHEN grp IS NOT NULL THEN\n grp || dense_rank::text\n END\nFROM\n cte1;\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10866435/"
] |
74,548,467
|
<p>I am trying to check if an entered value is in a list of values and then use it if it does using the <code>any</code> command in an <code>if</code> statement. But for some reason when the command finished iterating through the list it won't let me use this value.<br>Can someone where do I neeed to change my code to make it work?.
I want to print the <code>key</code> in the end.
<br>This is the mentioned if statement:</p>
<pre><code>if any(SHA3_256.new(key.export_key()).hexdigest() == hashed_pk for key in publicKeys):
print(key)
</code></pre>
<h2><strong>Code Parameters:</strong></h2>
<ul>
<li><code>publicKeys</code> is a list of string:<br><code>["key1", "key2"]</code>...</li>
<li><code>hashed_ok</code> is the entered string: <code>"0c22352b43d1696ac069a15a3561c9fc4c731e4e458edb7f648544b779f341dd"</code>.</li>
</ul>
|
[
{
"answer_id": 74548518,
"author": "Amin",
"author_id": 10281248,
"author_profile": "https://Stackoverflow.com/users/10281248",
"pm_score": 1,
"selected": false,
"text": "for key in publicKeys:\n if SHA3_256.new(key.export_key()).hexdigest() == hashed_pk:\n print(key)\n # Use `break` here if you want\n"
},
{
"answer_id": 74548527,
"author": "Edward Peters",
"author_id": 6016064,
"author_profile": "https://Stackoverflow.com/users/6016064",
"pm_score": 0,
"selected": false,
"text": "any print(key) for key in publicKeys: "
},
{
"answer_id": 74548596,
"author": "jsbueno",
"author_id": 108205,
"author_profile": "https://Stackoverflow.com/users/108205",
"pm_score": 2,
"selected": true,
"text": "any next key = next((key for key in publicKeys if SHA3_256.new(key.export_key()).hexdigest() == hashed_pk), \"Key not found\")\nprint(key)\n"
},
{
"answer_id": 74548646,
"author": "Steven Summers",
"author_id": 4831822,
"author_profile": "https://Stackoverflow.com/users/4831822",
"pm_score": 1,
"selected": false,
"text": ":= lst = [1, 2, 3]\nif any((key := k) == 2 for k in lst):\n print(key)\n if any(SHA3_256.new((key := k).export_key()).hexdigest()) == hashed_pk for k in publicKeys):\n print(key)\n"
},
{
"answer_id": 74548661,
"author": "charon25",
"author_id": 16114044,
"author_profile": "https://Stackoverflow.com/users/16114044",
"pm_score": 1,
"selected": false,
"text": ":= if any(SHA3_256.new((correct_key:=key).export_key()).hexdigest() == hashed_pk for key in publicKeys):\n print(correct_key)\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19916855/"
] |
74,548,475
|
<p>I am trying to create a new Azure CosmosDB account in terraform account using:</p>
<p><strong>create_mode = "Restore"</strong></p>
<p>Basically I am trying to restore from an existing DB, and the code needs another input attribute, of the source DB:</p>
<p><strong>"source_cosmosdb_account_id"</strong> = "/subscriptions/33f91226-e87e-4cdf67a1dae4e/providers/Microsoft.DocumentDB/locations/westeu/restorableDatabaseAccounts/test-source-db-name"</p>
<p>I am following the format indicated by the docs:</p>
<p><em><strong>The example is /subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts/{restorableDatabaseAccountName}</strong></em></p>
<p>However when I apply the code, I get the following error:</p>
<blockquote>
<p>Code="BadRequest" Message="Failed to parse uri
/subscriptions/33f91226-e87e-4ca1dae4e/providers/Microsoft.DocumentDB/locations/westeu/restorableDatabaseAccounts/test-source-db-name</p>
</blockquote>
<p>The issue seems to be the way I write the location inside the source ID, but I can't find any relevant info on how is the correct way.</p>
<p>I would really appreciate an example of <strong>source_cosmosdb_account_id</strong> if anyone did this successfully in terraform.</p>
<p>Thanks</p>
<p>Configuration used:</p>
<pre><code> backup = [
{
type = "Continuous"
interval_in_minutes = null
retention_in_hours = null
storage_redundancy = null
}
]
restore = [
{
"source_cosmosdb_account_id" = "/subscriptions/33f6-e87e-4cdf-9480-7b1dae/providers/Microsoft.DocumentDB/locations/westeu/restorableDatabaseAccounts/test-source-db-name"
"restore_timestamp_in_utc" = "2022-11-18T14:00:00.00Z"
"database" = []
}
]
</code></pre>
|
[
{
"answer_id": 74548518,
"author": "Amin",
"author_id": 10281248,
"author_profile": "https://Stackoverflow.com/users/10281248",
"pm_score": 1,
"selected": false,
"text": "for key in publicKeys:\n if SHA3_256.new(key.export_key()).hexdigest() == hashed_pk:\n print(key)\n # Use `break` here if you want\n"
},
{
"answer_id": 74548527,
"author": "Edward Peters",
"author_id": 6016064,
"author_profile": "https://Stackoverflow.com/users/6016064",
"pm_score": 0,
"selected": false,
"text": "any print(key) for key in publicKeys: "
},
{
"answer_id": 74548596,
"author": "jsbueno",
"author_id": 108205,
"author_profile": "https://Stackoverflow.com/users/108205",
"pm_score": 2,
"selected": true,
"text": "any next key = next((key for key in publicKeys if SHA3_256.new(key.export_key()).hexdigest() == hashed_pk), \"Key not found\")\nprint(key)\n"
},
{
"answer_id": 74548646,
"author": "Steven Summers",
"author_id": 4831822,
"author_profile": "https://Stackoverflow.com/users/4831822",
"pm_score": 1,
"selected": false,
"text": ":= lst = [1, 2, 3]\nif any((key := k) == 2 for k in lst):\n print(key)\n if any(SHA3_256.new((key := k).export_key()).hexdigest()) == hashed_pk for k in publicKeys):\n print(key)\n"
},
{
"answer_id": 74548661,
"author": "charon25",
"author_id": 16114044,
"author_profile": "https://Stackoverflow.com/users/16114044",
"pm_score": 1,
"selected": false,
"text": ":= if any(SHA3_256.new((correct_key:=key).export_key()).hexdigest() == hashed_pk for key in publicKeys):\n print(correct_key)\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20582841/"
] |
74,548,479
|
<p>I'm calling a part of a table from a razor component to a component that can be viewed. But the the problem is that there is an audio element i want to separate so it can be called at a different place.</p>
<p>Right now the audio element is included in the call in the loop. Is there any way the audio element can be separated in the <code>CallComponent.razor</code>, such that it can be called at a different loaction in <code>index.razor</code>?</p>
<p>Here is some code:</p>
<p><code>Index.razor</code></p>
<pre><code>//I want to call the separated audio element here
...
<tbody>
@foreach (var fileGroup in GroupedAndSorted)
{
<CallComponent fileGroup="fileGroup" />
}
</tbody>
...
</code></pre>
<p><code>CallComponent.razor</code></p>
<pre><code><audio src="@audioUrl" controls>
</audio>
<tr>
<td>
<a @onclick="@(() => PlayAudio(Mp3.Url))"
class="link-primary"
role="button">
@fileGroup.Key
</a>
</td>
</tr>
...
</code></pre>
|
[
{
"answer_id": 74549598,
"author": "Mister Magoo",
"author_id": 2658697,
"author_profile": "https://Stackoverflow.com/users/2658697",
"pm_score": 1,
"selected": false,
"text": "@childMarkup\n\n<Component1 ExtraMarkup=@( em => childMarkup = em) />\n\n@code \n{\n RenderFragment childMarkup;\n}\n \n<h1>Component1</h1>\n\n@code \n{\n [Parameter] public EventCallback<RenderFragment> ExtraMarkup { get;set;}\n\n protected override void OnInitialized()\n {\n ExtraMarkup.InvokeAsync( @<div>I am extra markup</div> );\n }\n}\n Component1 EventCallback<RenderFragment> RenderFragment Component1"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20373344/"
] |
74,548,486
|
<h1>Request</h1>
<p>I want to list all the table names in a schema in association with the list of that table attributes. I'm using DBeaver, but I can download other software if it works. I don't mind about the output data extension: txt, excel, csv etc., but I'm not searching for an ER diagram.</p>
<h1>Example</h1>
<p>If the database schema contains these three tables</p>
<p><strong>TABLE_A</strong></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ATTRIBUTE_A_1</th>
<th>ATTRIBUTE_A_2</th>
<th>ATTRIBUTE_A_3</th>
</tr>
</thead>
</table>
</div>
<p><strong>TABLE_B</strong></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ATTRIBUTE_B_1</th>
</tr>
</thead>
</table>
</div>
<p><strong>TABLE_C</strong></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ATTRIBUTE_C_1</th>
<th>ATTRIBUTE_C_2</th>
</tr>
</thead>
</table>
</div>
<p>I want to extract something like this:</p>
<pre><code>TABLE_A
ATTRIBUTE_A_1
ATTRIBUTE_A_2
ATTRIBUTE_A_3
TABLE_B
ATTRIBUTE_B_1
TABLE_C
ATTRIBUTE_C_1
ATTRIBUTE_C_2
</code></pre>
<p>Thanks in advance!</p>
|
[
{
"answer_id": 74549598,
"author": "Mister Magoo",
"author_id": 2658697,
"author_profile": "https://Stackoverflow.com/users/2658697",
"pm_score": 1,
"selected": false,
"text": "@childMarkup\n\n<Component1 ExtraMarkup=@( em => childMarkup = em) />\n\n@code \n{\n RenderFragment childMarkup;\n}\n \n<h1>Component1</h1>\n\n@code \n{\n [Parameter] public EventCallback<RenderFragment> ExtraMarkup { get;set;}\n\n protected override void OnInitialized()\n {\n ExtraMarkup.InvokeAsync( @<div>I am extra markup</div> );\n }\n}\n Component1 EventCallback<RenderFragment> RenderFragment Component1"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14976735/"
] |
74,548,503
|
<p>I have a serious problem with my Riverpod. Specifically, I am using StateProvider in Riverpod package. But when I update state, the widget tree does not rebuild. I checked the new state whether is updated by printing out state to see, I see that they are actually updated.
I have some same situations but when I click hot restart/reload page/scroll up,down mouse to change size chrome window, the widget tree rebuild one time.
Please help me and explain everything the most detail and easy to understand. Thank you very much
<a href="https://i.stack.imgur.com/9W1fD.png" rel="nofollow noreferrer">new state print out but UI not update</a></p>
<pre><code>import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:math';
void main() {
runApp(const ProviderScope(child: MyApp()));
}
class Data {
final String data;
Data({required this.data});
}
final helloWorldProvider = StateProvider<Data?>((ref) => Data(data: 'No data'));
class MyApp extends ConsumerStatefulWidget {
const MyApp({super.key});
@override
ConsumerState<MyApp> createState() => _MyAppState();
}
class _MyAppState extends ConsumerState<MyApp> {
@override
void initState() {
// TODO: implement initState4
print("Init state");
super.initState();
// getData();
}
// getData() async {
// // http.Response response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/todos/1'));
// // final title = jsonDecode(response.body)["title"];;
// // ref.read(helloWorldProvider.notifier).update((state) => title);
// SharedPreferences prefs = await SharedPreferences.getInstance();
// prefs.setString('valueTemp', 'newValue');
// String? valueTemp = prefs.getString('valueTemp');
// String value = valueTemp ?? '';
// Data data = Data(data: value);
// ref.read(helloWorldProvider.notifier).update((state) => data);
// print("Đã thực hiện xong");
// }
void _change() {
print("change");
final rawString = generateRandomString(5);
Data data = new Data(data: rawString);
ref.watch(helloWorldProvider.notifier).update((state) => data);
print(ref.read(helloWorldProvider.notifier).state?.data);
}
String generateRandomString(int len) {
var r = Random();
return String.fromCharCodes(List.generate(len, (index) => r.nextInt(33) + 89));
}
@override
Widget build(BuildContext context) {
print('Rebuild');
final data = ref.watch(helloWorldProvider.notifier).state;
final dataText = data?.data ?? 'No text';
print(dataText);
return MaterialApp(
title: 'Google Docs Clone',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
body: Center(
child: Column(children: [
Text(dataText)
]
)
),
floatingActionButton: FloatingActionButton(
onPressed: _change,
tooltip: 'Change',
child: const Icon(Icons.add),
),
));
}
}
</code></pre>
<p>I don't want to use other pattern as Provider, Bloc, StateNotifierProvider, ChangeNotifierProvider... I only want to run StateProvider successfully. I have refered to many articles and stackoverflows answer but I did't found any useful helps to my case.</p>
|
[
{
"answer_id": 74554350,
"author": "Randal Schwartz",
"author_id": 22483,
"author_profile": "https://Stackoverflow.com/users/22483",
"pm_score": 2,
"selected": true,
"text": "final data = ref.watch(helloWorldProvider.notifier).state;\n final data = ref.watch(helloWorldProvider);\n"
},
{
"answer_id": 74571571,
"author": "Ska Lee",
"author_id": 14695961,
"author_profile": "https://Stackoverflow.com/users/14695961",
"pm_score": 0,
"selected": false,
"text": "import 'package:flutter/material.dart';\nimport 'package:flutter_riverpod/flutter_riverpod.dart';\nimport 'dart:math';\n\nvoid main() {\n runApp(const ProviderScope(child: MyApp()));\n}\n\nclass Data {\n final String data;\n Data({required this.data});\n}\n\nfinal helloWorldProvider = StateProvider<Data?>((ref) => Data(data: 'No data'));\n\nclass MyApp extends ConsumerStatefulWidget {\n const MyApp({super.key});\n\n @override\n ConsumerState<MyApp> createState() => _MyAppState();\n}\n\nclass _MyAppState extends ConsumerState<MyApp> {\n @override\n void initState() {\n // TODO: implement initState4\n print(\"Init state\");\n super.initState();\n // getData();\n }\n // getData() async {\n // // http.Response response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/todos/1'));\n // // final title = jsonDecode(response.body)[\"title\"];;\n // // ref.read(helloWorldProvider.notifier).update((state) => title);\n // SharedPreferences prefs = await SharedPreferences.getInstance();\n // prefs.setString('valueTemp', 'newValue');\n // String? valueTemp = prefs.getString('valueTemp');\n // String value = valueTemp ?? '';\n // Data data = Data(data: value);\n // ref.read(helloWorldProvider.notifier).update((state) => data);\n // print(\"Đã thực hiện xong\");\n // }\n\n void _change() {\n print(\"change\");\n final rawString = generateRandomString(5);\n Data data = Data(data: rawString);\n ref.read(helloWorldProvider.notifier).update((state) => data);\n print(ref.read(helloWorldProvider.notifier).state?.data);\n }\n\n String generateRandomString(int len) {\n var r = Random();\n return String.fromCharCodes(\n List.generate(len, (index) => r.nextInt(33) + 89));\n }\n\n @override\n Widget build(BuildContext context) {\n print('Rebuild');\n final data = ref.watch(helloWorldProvider)?.data;\n final dataText = data ?? 'No text';\n print(dataText);\n return MaterialApp(\n title: 'Google Docs Clone',\n debugShowCheckedModeBanner: false,\n theme: ThemeData(\n primarySwatch: Colors.blue,\n ),\n home: Scaffold(\n body: Center(\n child: Column(children: [Text(dataText)]),\n ),\n floatingActionButton: FloatingActionButton(\n onPressed: _change,\n tooltip: 'Change',\n child: const Icon(Icons.add),\n ),\n ),\n );\n }\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20582783/"
] |
74,548,508
|
<p>I need your help. I want to connect the device locally (not an emulator). <a href="https://i.stack.imgur.com/5tDIF.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>But I stopped at this problem that I can't solve.<a href="https://i.stack.imgur.com/Zy5Bt.png" rel="nofollow noreferrer">enter image description here</a></p>
|
[
{
"answer_id": 74554350,
"author": "Randal Schwartz",
"author_id": 22483,
"author_profile": "https://Stackoverflow.com/users/22483",
"pm_score": 2,
"selected": true,
"text": "final data = ref.watch(helloWorldProvider.notifier).state;\n final data = ref.watch(helloWorldProvider);\n"
},
{
"answer_id": 74571571,
"author": "Ska Lee",
"author_id": 14695961,
"author_profile": "https://Stackoverflow.com/users/14695961",
"pm_score": 0,
"selected": false,
"text": "import 'package:flutter/material.dart';\nimport 'package:flutter_riverpod/flutter_riverpod.dart';\nimport 'dart:math';\n\nvoid main() {\n runApp(const ProviderScope(child: MyApp()));\n}\n\nclass Data {\n final String data;\n Data({required this.data});\n}\n\nfinal helloWorldProvider = StateProvider<Data?>((ref) => Data(data: 'No data'));\n\nclass MyApp extends ConsumerStatefulWidget {\n const MyApp({super.key});\n\n @override\n ConsumerState<MyApp> createState() => _MyAppState();\n}\n\nclass _MyAppState extends ConsumerState<MyApp> {\n @override\n void initState() {\n // TODO: implement initState4\n print(\"Init state\");\n super.initState();\n // getData();\n }\n // getData() async {\n // // http.Response response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/todos/1'));\n // // final title = jsonDecode(response.body)[\"title\"];;\n // // ref.read(helloWorldProvider.notifier).update((state) => title);\n // SharedPreferences prefs = await SharedPreferences.getInstance();\n // prefs.setString('valueTemp', 'newValue');\n // String? valueTemp = prefs.getString('valueTemp');\n // String value = valueTemp ?? '';\n // Data data = Data(data: value);\n // ref.read(helloWorldProvider.notifier).update((state) => data);\n // print(\"Đã thực hiện xong\");\n // }\n\n void _change() {\n print(\"change\");\n final rawString = generateRandomString(5);\n Data data = Data(data: rawString);\n ref.read(helloWorldProvider.notifier).update((state) => data);\n print(ref.read(helloWorldProvider.notifier).state?.data);\n }\n\n String generateRandomString(int len) {\n var r = Random();\n return String.fromCharCodes(\n List.generate(len, (index) => r.nextInt(33) + 89));\n }\n\n @override\n Widget build(BuildContext context) {\n print('Rebuild');\n final data = ref.watch(helloWorldProvider)?.data;\n final dataText = data ?? 'No text';\n print(dataText);\n return MaterialApp(\n title: 'Google Docs Clone',\n debugShowCheckedModeBanner: false,\n theme: ThemeData(\n primarySwatch: Colors.blue,\n ),\n home: Scaffold(\n body: Center(\n child: Column(children: [Text(dataText)]),\n ),\n floatingActionButton: FloatingActionButton(\n onPressed: _change,\n tooltip: 'Change',\n child: const Icon(Icons.add),\n ),\n ),\n );\n }\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20561359/"
] |
74,548,514
|
<p>I'm trying to get some youtube videos data from a channel using the google api v3.</p>
<p>When I run the url in my browser the information I get looks good.
<code>https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCBYyJBCtCvgqA4NwtoPMwpQ&maxResults=10&order=date&type=video&key={MYAPIKEY}</code></p>
<pre><code>{
"kind": "youtube#searchListResponse",
"etag": "lP1l3Vk-JQNUN9moIFDXVlQt9uY",
"nextPageToken": "CAoQAA",
"regionCode": "NL",
"pageInfo": {
"totalResults": 4109,
"resultsPerPage": 10
},
"items": [
{
"kind": "youtube#searchResult",
"etag": "DIARyKavv5X4EEGZzoIYKd2hzGY",
"id": {
"kind": "youtube#video",
"videoId": "N54TzfCbJOU"
},
"snippet": {
"publishedAt": "2022-11-22T16:00:07Z",
"channelId": "UCBYyJBCtCvgqA4NwtoPMwpQ",
"title": "The Wild Project #171 | ¿Engañaron a Jordi?, Qatar ridículo inaugural, Desastre con Ley del Sí es Sí",
"description": "Como cada semana, nueva tertulia en The Wild Project, comentando las noticias más destacadas de los últimos días. En este ...",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/N54TzfCbJOU/default.jpg",
"width": 120,
"height": 90
},
"medium": {
"url": "https://i.ytimg.com/vi/N54TzfCbJOU/mqdefault.jpg",
"width": 320,
"height": 180
},
"high": {
"url": "https://i.ytimg.com/vi/N54TzfCbJOU/hqdefault.jpg",
"width": 480,
"height": 360
}
},
"channelTitle": "The Wild Project",
"liveBroadcastContent": "none",
"publishTime": "2022-11-22T16:00:07Z"
}
}, ...ETC
</code></pre>
<p>If I run a curl call in my terminal the response is also good.</p>
<p>But, when I try to run it in Axios NodeJS the response I get is different, and the data portion seems encrypted.</p>
<pre><code>response = await this.axios.get(`https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCBYyJBCtCvgqA4NwtoPMwpQ&maxResults=10&order=date&type=video&key={MYAPIKEY}`);
</code></pre>
<p>I get a 200 status response, but in the body of the data I see this:</p>
<pre><code>data: '\x1F�\b\x00\x00\x00\x00\x00\x02��Ks�\x11���)Pު��\x10��$��˶dy�\x1E�ʦ\\\x10\t��A�\x06@=��/��\x1Es�Cjo{IU��Ҡ$\x07����"N�V��\x19\n' +
'h\x00\x7F��?..ETC
</code></pre>
<p>Does anyone have any idea?</p>
|
[
{
"answer_id": 74549353,
"author": "Bench Vue",
"author_id": 8054998,
"author_profile": "https://Stackoverflow.com/users/8054998",
"pm_score": 3,
"selected": true,
"text": "Accept-Encoding gzip const axios = require('axios')\nconst config = require('./my-key.json');\n\nconst getVideo = async () => {\n try {\n const resp = await axios.get(\n 'https://www.googleapis.com/youtube/v3/search',\n {\n headers: {\n 'Content-Type': 'application/json',\n 'Accept-Encoding': 'application/json',\n },\n params: {\n 'part': 'snippet',\n 'channelId': 'UCBYyJBCtCvgqA4NwtoPMwpQ',\n 'maxResults': '1',\n 'order': 'date',\n 'type': 'video',\n 'key': config.API_KEY\n }\n }\n );\n console.log(JSON.stringify(resp.data, null, 4));\n } catch (err) {\n // Handle Error Here\n console.error(err);\n }\n};\n\ngetVideo();\n {\n \"API_KEY\" : \"AIz..your-API-key...xUs\"\n}\n $ node get-video.js\n{\n \"kind\": \"youtube#searchListResponse\",\n \"etag\": \"wu-L26udDmyHfzoJalUtCRCGeKs\",\n \"nextPageToken\": \"CAEQAA\",\n \"regionCode\": \"US\",\n \"pageInfo\": {\n \"totalResults\": 4103,\n \"resultsPerPage\": 1\n },\n \"items\": [\n {\n \"kind\": \"youtube#searchResult\",\n \"etag\": \"DIARyKavv5X4EEGZzoIYKd2hzGY\",\n \"id\": {\n \"kind\": \"youtube#video\",\n \"videoId\": \"N54TzfCbJOU\"\n },\n \"snippet\": {\n \"publishedAt\": \"2022-11-22T16:00:07Z\",\n \"channelId\": \"UCBYyJBCtCvgqA4NwtoPMwpQ\",\n \"title\": \"The Wild Project #171 | ¿Engañaron a Jordi?, Qatar ridículo inaugural, Desastre con Ley del Sí es Sí\",\n \"description\": \"Como cada semana, nueva tertulia en The Wild Project, comentando las noticias más destacadas de los últimos días. En este ...\",\n \"thumbnails\": {\n \"default\": {\n \"url\": \"https://i.ytimg.com/vi/N54TzfCbJOU/default.jpg\",\n \"width\": 120,\n \"height\": 90\n },\n \"medium\": {\n \"url\": \"https://i.ytimg.com/vi/N54TzfCbJOU/mqdefault.jpg\",\n \"width\": 320,\n \"height\": 180\n },\n \"high\": {\n \"url\": \"https://i.ytimg.com/vi/N54TzfCbJOU/hqdefault.jpg\",\n \"width\": 480,\n \"height\": 360\n }\n },\n \"channelTitle\": \"The Wild Project\",\n \"liveBroadcastContent\": \"none\",\n \"publishTime\": \"2022-11-22T16:00:07Z\"\n }\n }\n ]\n}\n"
},
{
"answer_id": 74606645,
"author": "Joust Knight",
"author_id": 4633408,
"author_profile": "https://Stackoverflow.com/users/4633408",
"pm_score": 0,
"selected": false,
"text": "\"axios\": \"^1.1.3\",\n \"the config transformResponse sends data as binary instead of string\"\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6445726/"
] |
74,548,570
|
<p>Compare the outputs of these two functions:</p>
<pre><code>from itertools import repeat
def rand_list1():
l = lambda: np.random.rand(3)
return list(repeat(l(), 5))
def rand_list2():
return [np.random.rand(3) for i in range(5)]
</code></pre>
<p>We see that <code>rand_list1</code> who uses <code>itetools.repeat</code> always generates the same 3 numbers. why is this? Can it be avoided, so each call of <code>rand_list()</code> will generate new numbers?</p>
<p>For example, the output of <code>rand_list1()</code>:</p>
<pre><code>[[0.07678796 0.22623777 0.07533145]
[0.07678796 0.22623777 0.07533145]
[0.07678796 0.22623777 0.07533145]
[0.07678796 0.22623777 0.07533145]
[0.07678796 0.22623777 0.07533145]]
</code></pre>
<p>and the output of <code>rand_list2()</code>:</p>
<pre><code>[[0.77863856 0.30345662 0.7007517 ]
[0.56422447 0.97138115 0.47976387]
[0.20576279 0.92875791 0.06518335]
[0.2992384 0.89726684 0.16917078]
[0.8440534 0.38016789 0.51691172]]
</code></pre>
|
[
{
"answer_id": 74548749,
"author": "jsbueno",
"author_id": 108205,
"author_profile": "https://Stackoverflow.com/users/108205",
"pm_score": 2,
"selected": false,
"text": "l l() l() repeat repeat repeat repeat return [l() for _ in range(5)]\n l() l l 1"
},
{
"answer_id": 74548890,
"author": "Constantin Hong",
"author_id": 20307768,
"author_profile": "https://Stackoverflow.com/users/20307768",
"pm_score": 0,
"selected": false,
"text": "list(repeat(l(), 5)) itertools.repeat() l() list(repeat(l(), 5)) l l() list(repeat(l(), 5))\n list(repeat([some numbers], 5))\n list(repeat([some numbers], 5)) --> [some numbers], [some numbers], [some numbers], [some numbers], [some numbers]\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4809113/"
] |
74,548,574
|
<p>How can I make the following code short:</p>
<pre><code>q=0.34
density=''
</code></pre>
<pre><code> if abs(q) ==0:
density='Null'
elif abs(q) <= 0.09:
density='negligible'
elif abs(q) <= 0.49:
density='slight'
elif abs(q) <= 0.69:
density='strong'
else:
density='very strong'
print(q,", ", density)
</code></pre>
<p>Expected output :</p>
<pre><code>0.34, 'slight'
</code></pre>
<p>I think there is a solution by using <code>dictionaries</code>,</p>
<p>Any help from your side will be highly appreciated !</p>
|
[
{
"answer_id": 74548813,
"author": "Raida",
"author_id": 13763683,
"author_profile": "https://Stackoverflow.com/users/13763683",
"pm_score": 2,
"selected": false,
"text": "def f(q):\n # List of your limits values and their density values\n values = [(0, \"Null\"), (0.09, \"negligible\"), (0.49, \"slight\"), (0.69, \"strong\")]\n # Default value of the density, i.e. your else statement\n density = \"very strong\"\n\n # Search the good density and stop when it is found\n for (l, d) in values:\n if abs(q) <= l:\n density = d\n break\n\n print(q, \", \", density)\n"
},
{
"answer_id": 74548844,
"author": "Steinn Hauser Magnusson",
"author_id": 13819183,
"author_profile": "https://Stackoverflow.com/users/13819183",
"pm_score": 1,
"selected": false,
"text": "import numpy as np\nvals = [0, 0.09,0.49,0.69,]\nmsgs = ['Null', 'negligible', 'slight', 'strong', 'very strong']\n\nq=0.5\ndensity=''\n\ndef calc_density(q:float) -> str:\n are_greater_than = q>np.array(vals)\n if all(are_greater_than): bools = -1\n else: bools = np.argmin(are_greater_than)\n return msgs[bools]\n\nfor q in [-0.1, 0.0, 0.2, 0.07, 0.8]:\n print(q, calc_density(q))\n\n# >>> -0.1 Null\n# >>> 0.0 Null\n# >>> 0.2 slight\n# >>> 0.07 negligible\n# >>> 0.8 very strong\n"
},
{
"answer_id": 74548862,
"author": "jsbueno",
"author_id": 108205,
"author_profile": "https://Stackoverflow.com/users/108205",
"pm_score": 1,
"selected": false,
"text": "def _range_to_str(ranges, value):\n for threshold, description in ranges.items():\n if value <= threshold:\n return description\n raise ValueError(f\"{value} out of range for {ranges}\")\n\ndensities = {0: \"\", 0.09:\"negligible\", 0.49: \"slight\", ...}\n\ndef density_description(value):\n return _range_to_str(densities, value)\n"
},
{
"answer_id": 74549157,
"author": "eroc1234",
"author_id": 16480816,
"author_profile": "https://Stackoverflow.com/users/16480816",
"pm_score": 2,
"selected": true,
"text": "q=0.34\ndensity=''\nconditions = [\n(0,'null'),\n(0.09, 'negligible'),\n(0.49, 'slight'),\n(0.69, 'strong')\n]\n# loops through the conditions and check if they are smaller\n# if they are, immediately exit the loop, retaining the correct density value\nfor limit, density in conditions:\n if q <= limit:\n break\n# this if statement checks if its larger than the last condition\n# this ensures that even if it never reached any condition, it doesn't\n# just output the last value\nif q > conditions[-1][0]:\n density = 'very strong'\n\nprint(q,\", \", density)\n q=0.34\nc = [(0,'null'),(0.09,'negligible'),(0.49,'slight'),(0.69,'strong'), (9999,'very strong')]\nprint(q,',',[j for i,j in c if q<=i][0])\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15852600/"
] |
74,548,601
|
<p>So what I am trying to do is to create a Bug ticket after a test run fails in DevOps. I have a screenshot in my Attachments area but when I try to create a Bug ticket only error messages, the stack trace and other kinds of information is automatically displayed in the Repro Steps of the Bug.</p>
<p>When I create the Bug ticket I also want the screenshot to be included in it to be previewed but the Attachment tab of the Bug ticket is empty.</p>
<p>Is there a way to add it there? Or anywhere else (bug, test run, etc) so It can be previewed? Right now, from the test run the screenshot can only be downloaded or deleted; the option for preview is disabled.</p>
<p><img src="https://i.stack.imgur.com/LNnrx.png" alt="Preview not available" /></p>
<p>Repro Steps:</p>
<ol>
<li>Write an automated test (with SetUp, TearDown <- Screenshot is taken from here, etc)</li>
<li>Right-click the test from the "Test Explorer" and then click "Associate to Test Case"; add the test case ID and save.</li>
<li>Push the code to the repo.</li>
<li>Build the pipeline in DevOps based on the new code.</li>
<li>Go to the "Test Suite" that has that test case and in "Define" tab, execute one test with "Run with options".</li>
<li>From there select test type and runner with the option "Automated tests using release stage".</li>
<li>From the same window select a build, the release pipeline and stage then click "Run".</li>
<li>After the execution is complete, double click the test case and then the latest outcome.</li>
<li>You are redirected to that specific test run.</li>
<li>The "Attachments" tab has one item within (because the test failed and the trigger from the TearDown).But it cannot be previewed.</li>
<li>From above "Summary" you can create a bug for this, prepopulating Retro Steps with the information I mentioned in the comments.
Howerver, for this Bug item the "Attachments" tab is empty. So it does not take the file from the test run.</li>
</ol>
<p>This is the code for creating a screenshot (present in TearDown method):</p>
<pre><code>if (TestContext.CurrentContext.Result.Outcome != ResultState.Success)
{
Screenshot screenshot = ((ITakesScreenshot)Page.GetDriver()).GetScreenshot();
string path = Directory.GetCurrentDirectory() + $"{DateTime.Now:yyyy-MM-dd_HH-mm-ss.fffff}.png";
screenshot.SaveAsFile(path, ScreenshotImageFormat.Png);
TestContext.AddTestAttachment(path);
}
</code></pre>
<p>Thank you!</p>
|
[
{
"answer_id": 74548813,
"author": "Raida",
"author_id": 13763683,
"author_profile": "https://Stackoverflow.com/users/13763683",
"pm_score": 2,
"selected": false,
"text": "def f(q):\n # List of your limits values and their density values\n values = [(0, \"Null\"), (0.09, \"negligible\"), (0.49, \"slight\"), (0.69, \"strong\")]\n # Default value of the density, i.e. your else statement\n density = \"very strong\"\n\n # Search the good density and stop when it is found\n for (l, d) in values:\n if abs(q) <= l:\n density = d\n break\n\n print(q, \", \", density)\n"
},
{
"answer_id": 74548844,
"author": "Steinn Hauser Magnusson",
"author_id": 13819183,
"author_profile": "https://Stackoverflow.com/users/13819183",
"pm_score": 1,
"selected": false,
"text": "import numpy as np\nvals = [0, 0.09,0.49,0.69,]\nmsgs = ['Null', 'negligible', 'slight', 'strong', 'very strong']\n\nq=0.5\ndensity=''\n\ndef calc_density(q:float) -> str:\n are_greater_than = q>np.array(vals)\n if all(are_greater_than): bools = -1\n else: bools = np.argmin(are_greater_than)\n return msgs[bools]\n\nfor q in [-0.1, 0.0, 0.2, 0.07, 0.8]:\n print(q, calc_density(q))\n\n# >>> -0.1 Null\n# >>> 0.0 Null\n# >>> 0.2 slight\n# >>> 0.07 negligible\n# >>> 0.8 very strong\n"
},
{
"answer_id": 74548862,
"author": "jsbueno",
"author_id": 108205,
"author_profile": "https://Stackoverflow.com/users/108205",
"pm_score": 1,
"selected": false,
"text": "def _range_to_str(ranges, value):\n for threshold, description in ranges.items():\n if value <= threshold:\n return description\n raise ValueError(f\"{value} out of range for {ranges}\")\n\ndensities = {0: \"\", 0.09:\"negligible\", 0.49: \"slight\", ...}\n\ndef density_description(value):\n return _range_to_str(densities, value)\n"
},
{
"answer_id": 74549157,
"author": "eroc1234",
"author_id": 16480816,
"author_profile": "https://Stackoverflow.com/users/16480816",
"pm_score": 2,
"selected": true,
"text": "q=0.34\ndensity=''\nconditions = [\n(0,'null'),\n(0.09, 'negligible'),\n(0.49, 'slight'),\n(0.69, 'strong')\n]\n# loops through the conditions and check if they are smaller\n# if they are, immediately exit the loop, retaining the correct density value\nfor limit, density in conditions:\n if q <= limit:\n break\n# this if statement checks if its larger than the last condition\n# this ensures that even if it never reached any condition, it doesn't\n# just output the last value\nif q > conditions[-1][0]:\n density = 'very strong'\n\nprint(q,\", \", density)\n q=0.34\nc = [(0,'null'),(0.09,'negligible'),(0.49,'slight'),(0.69,'strong'), (9999,'very strong')]\nprint(q,',',[j for i,j in c if q<=i][0])\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15300316/"
] |
74,548,608
|
<p>Im having an error with this query, I'm using a the latest SQL server and management studio</p>
<p>See the query below</p>
<pre><code>CREATE TABLE messages_server (
Id int unsigned NOT NULL AUTO_INCREMENT,
SentTime datetime,
MessageRead BIT,
Content varchar(8000),
MessageCategory varchar(255),
MessageUser varchar(255),
PRIMARY KEY (Id)
)
</code></pre>
|
[
{
"answer_id": 74548813,
"author": "Raida",
"author_id": 13763683,
"author_profile": "https://Stackoverflow.com/users/13763683",
"pm_score": 2,
"selected": false,
"text": "def f(q):\n # List of your limits values and their density values\n values = [(0, \"Null\"), (0.09, \"negligible\"), (0.49, \"slight\"), (0.69, \"strong\")]\n # Default value of the density, i.e. your else statement\n density = \"very strong\"\n\n # Search the good density and stop when it is found\n for (l, d) in values:\n if abs(q) <= l:\n density = d\n break\n\n print(q, \", \", density)\n"
},
{
"answer_id": 74548844,
"author": "Steinn Hauser Magnusson",
"author_id": 13819183,
"author_profile": "https://Stackoverflow.com/users/13819183",
"pm_score": 1,
"selected": false,
"text": "import numpy as np\nvals = [0, 0.09,0.49,0.69,]\nmsgs = ['Null', 'negligible', 'slight', 'strong', 'very strong']\n\nq=0.5\ndensity=''\n\ndef calc_density(q:float) -> str:\n are_greater_than = q>np.array(vals)\n if all(are_greater_than): bools = -1\n else: bools = np.argmin(are_greater_than)\n return msgs[bools]\n\nfor q in [-0.1, 0.0, 0.2, 0.07, 0.8]:\n print(q, calc_density(q))\n\n# >>> -0.1 Null\n# >>> 0.0 Null\n# >>> 0.2 slight\n# >>> 0.07 negligible\n# >>> 0.8 very strong\n"
},
{
"answer_id": 74548862,
"author": "jsbueno",
"author_id": 108205,
"author_profile": "https://Stackoverflow.com/users/108205",
"pm_score": 1,
"selected": false,
"text": "def _range_to_str(ranges, value):\n for threshold, description in ranges.items():\n if value <= threshold:\n return description\n raise ValueError(f\"{value} out of range for {ranges}\")\n\ndensities = {0: \"\", 0.09:\"negligible\", 0.49: \"slight\", ...}\n\ndef density_description(value):\n return _range_to_str(densities, value)\n"
},
{
"answer_id": 74549157,
"author": "eroc1234",
"author_id": 16480816,
"author_profile": "https://Stackoverflow.com/users/16480816",
"pm_score": 2,
"selected": true,
"text": "q=0.34\ndensity=''\nconditions = [\n(0,'null'),\n(0.09, 'negligible'),\n(0.49, 'slight'),\n(0.69, 'strong')\n]\n# loops through the conditions and check if they are smaller\n# if they are, immediately exit the loop, retaining the correct density value\nfor limit, density in conditions:\n if q <= limit:\n break\n# this if statement checks if its larger than the last condition\n# this ensures that even if it never reached any condition, it doesn't\n# just output the last value\nif q > conditions[-1][0]:\n density = 'very strong'\n\nprint(q,\", \", density)\n q=0.34\nc = [(0,'null'),(0.09,'negligible'),(0.49,'slight'),(0.69,'strong'), (9999,'very strong')]\nprint(q,',',[j for i,j in c if q<=i][0])\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15714952/"
] |
74,548,612
|
<p>I feel like I'm going insane because I can't figure out what feels like should be a simple problem! I want to generate fake data in a numpy array and I can't figure out how to repeat a row of observations. I'd rather generate thousands of rows and I can't figure out how to repeat a row whenever I feel like.</p>
<p>For example, here's my current code:</p>
<pre><code>voters = np.array(
[
['Democrat', 'Republican', 'Third'],
['Democrat', 'Republican', 'Third'],
['Democrat', 'Republican', 'Third'],
['Democrat', 'Republican', 'Third'],
['Democrat', 'Republican', 'Third'],
['Democrat', 'Third', 'Republican'],
['Democrat', 'Third', 'Republican'],
['Democrat', 'Third', 'Republican'],
['Democrat', 'Third', 'Republican'],
]
)
</code></pre>
<p>But I just want to be able to condense this. It's obviously not manageable to make large datasets this way!</p>
<p>Thank you</p>
|
[
{
"answer_id": 74548791,
"author": "robinood",
"author_id": 8814229,
"author_profile": "https://Stackoverflow.com/users/8814229",
"pm_score": 1,
"selected": false,
"text": "np.array([['Democrat', 'Republican', 'Third']]* 10000)\n"
},
{
"answer_id": 74549089,
"author": "obchardon",
"author_id": 4363864,
"author_profile": "https://Stackoverflow.com/users/4363864",
"pm_score": 3,
"selected": true,
"text": "np.repeat() voters = np.array([['row1', 'row1', 'row1'],\n ['row2', 'row2', 'row2']])\n\n# We repeat 2 times the first row and 4 times the second row.\nnp.repeat(voters,[2,4],axis=0)\n# voters.repeat([2,4],axis=0) produce the same result.\n array([['row1', 'row1', 'row1'],\n ['row1', 'row1', 'row1'],\n ['row2', 'row2', 'row2'],\n ['row2', 'row2', 'row2'],\n ['row2', 'row2', 'row2'],\n ['row2', 'row2', 'row2']])\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13298650/"
] |
74,548,631
|
<p>I have a time series dataset on which I am running the auto arima model. The dataset has multiple columns that are independent of each other, so basically it's like multiple auto arima analysis.</p>
<p>The code I currently have loops through all the columns in the dataframe and stores the order values of p,d,q for each column in a list. What I want to achieve is : to store the p,d,q values for each column in a dataframe row wise.</p>
<p>Time Series Dataframe</p>
<pre><code>date Col1 Col2 Col3 Col4 Col5 Col6 Col7 Col8 Col9
2022-01-02 10:30:00 24 24 24.8 24.8 25 25 25.5 26.3 26.9
2022-01-02 10:45:00 59 58 60 60.3 59.3 59.2 58.4 56.9 58.0
2022-01-02 11:00:00 43.7 43.9 48 48 48.1 48.9 49 49.5 49.5
</code></pre>
<p>Code</p>
<pre><code>##Auto arima
# def arimamodel(series):
autoarima_results=[]
series = df.columns
for col in series:
print("Auto Arima for : ", {col})
ARIMA_model = pm.auto_arima(
df[col],
start_p=1,
start_q=1,
test="adf",
max_p=5,
max_q=5,
d=None,
trace=True,
error_action="ignore",
suppress_warnings=True,
stepwise=True,
)
ARIMA_model.summary()
autoarima_results.append(ARIMA_model.order)
</code></pre>
<p>This returns a list that looks like : [(1,1,0), (2,1,1), (1,1,1)]</p>
<p>For example, the orders of p,d,q suggested by auto arima are, Col1 : 1,1,0 , Col2 : 2,1,1 , Col3 : 1,1,1 and so on.</p>
<p>The final output should be a dataframe that would look like is as below. Where every row represents one column and its p,d,q values:</p>
<pre class="lang-py prettyprint-override"><code>Results pdq_values
Col1 (1,1,0)
Col2 (2,1,1)
Col3 (1,1,1)
</code></pre>
|
[
{
"answer_id": 74548791,
"author": "robinood",
"author_id": 8814229,
"author_profile": "https://Stackoverflow.com/users/8814229",
"pm_score": 1,
"selected": false,
"text": "np.array([['Democrat', 'Republican', 'Third']]* 10000)\n"
},
{
"answer_id": 74549089,
"author": "obchardon",
"author_id": 4363864,
"author_profile": "https://Stackoverflow.com/users/4363864",
"pm_score": 3,
"selected": true,
"text": "np.repeat() voters = np.array([['row1', 'row1', 'row1'],\n ['row2', 'row2', 'row2']])\n\n# We repeat 2 times the first row and 4 times the second row.\nnp.repeat(voters,[2,4],axis=0)\n# voters.repeat([2,4],axis=0) produce the same result.\n array([['row1', 'row1', 'row1'],\n ['row1', 'row1', 'row1'],\n ['row2', 'row2', 'row2'],\n ['row2', 'row2', 'row2'],\n ['row2', 'row2', 'row2'],\n ['row2', 'row2', 'row2']])\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20059373/"
] |
74,548,636
|
<p>I've added identity and authentication to an already existing API that was written in .net core 2.1.</p>
<p>There is for sure something funky going on as I am getting no roles returned when calling GetRolesAsync() like so:</p>
<pre><code>var user = await _userManager.FindByEmailAsync(email);
var roles = await _userManager.GetRolesAsync(user);
</code></pre>
<p>I am able to create users ok using the following code:</p>
<pre><code> var newUser = new User
{
UserName = model.Email,
Email = model.Email,
IsEnabled = true,
Name = model.FirstName + " " + model.LastName,
FirstName = model.FirstName,
LastName = model.LastName,
CreatedDate = DateTime.Now,
CreatedBy = user.Identity.Name
};
var result = await _userManager.CreateAsync(newUser, model.Password);
if (result.Succeeded)
{
foreach (var role in model.Roles)
{
result = await _userManager.AddToRoleAsync(newUser, role.ToString());
}
return newUser;
}
</code></pre>
<p>This call adds the new user to AspnetUsers and also adds the user roles to AspNetUserRoles.</p>
<p>I am setting up authorisation in startup.cs like so:</p>
<pre><code> var key = Encoding.ASCII.GetBytes(Configuration.GetValue<string>("JwtSettings:Secret"));
services
.AddAuthorization()
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
});
services.AddIdentity<User, ApplicationRole>()
.AddEntityFrameworkStores<AccountContext>()
.AddDefaultTokenProviders();
</code></pre>
<p>User class inherits IdentityUser:</p>
<pre><code> public partial class User : IdentityUser
{
// Some extra members
}
</code></pre>
<p>ApplicationRole inherits IdentityRole:</p>
<pre><code> public partial class ApplicationRole : IdentityRole
{
// No members
}
</code></pre>
<p>I am storing all entries in postgres database and values are being written and read ok.</p>
<p>The entries in AspNetUserRoles have been added manually but I added some using RoleManager then and same issue.</p>
<p>Why would I get no roles returned when I call GetRolesAsync() for a user that has been verified to exist?</p>
<p>I've tried a lot of the suggestions here but none have figured this out for me.</p>
|
[
{
"answer_id": 74556084,
"author": "Chen",
"author_id": 18789859,
"author_profile": "https://Stackoverflow.com/users/18789859",
"pm_score": 1,
"selected": false,
"text": "model.Roles RoleManager _userManager.FindByEmailAsync(email) user"
},
{
"answer_id": 74602540,
"author": "Dermo909",
"author_id": 11545419,
"author_profile": "https://Stackoverflow.com/users/11545419",
"pm_score": 0,
"selected": false,
"text": "public partial class User : IdentityUser\n{\n public string Id { get; set; }\n ... and more\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11545419/"
] |
74,548,659
|
<p>I am creating a text based game for a Python class.</p>
<p>I created a dictionary for my rooms and created a list for my directions:</p>
<pre class="lang-py prettyprint-override"><code>rooms = {
'Great Hall': {
'name': 'Great Hall',
'South': 'Bedroom'
},
'Bedroom': {
'name': 'Bedroom',
'North': 'Great Hall',
'East': 'Cellar'
},
'Cellar': {
'name': 'Cellar',
'West': 'Bedroom'
}
}
directions = [
'North',
'South',
'East',
'West'
]
</code></pre>
<p>Here is the code snippet with my <code>if</code> statement:</p>
<pre class="lang-py prettyprint-override"><code>current_room = rooms['Great Hall']
while True:
print('You are in', current_room['name'])
command = input('What would you like to do? ')
if command in directions:
if command in current_room:
current_room = rooms[current_room[command]]
else:
print('Nothing happened')
elif command == 'Quit':
print('Goodbye')
break
</code></pre>
<p>The <code>if</code> statement returns <code>True</code> if the user inputs the command something like <code>South</code>, but does not return <code>True</code> if the user inputs the command <code>Go South</code>. If the string <code>South</code> is in the string <code>Go South</code>, why wouldn't this return <code>True</code>? What can I change for it to return <code>True</code>?</p>
|
[
{
"answer_id": 74548774,
"author": "Bill Lynch",
"author_id": 47453,
"author_profile": "https://Stackoverflow.com/users/47453",
"pm_score": 2,
"selected": false,
"text": " directions = ['South', 'North', 'East', 'West']\n command = 'South'\n if command in directions:\n print('This works as LaLoba expects')\n \n command = 'Go South'\n if command in directions:\n print('This line of code does not execute, but LaLoba would like it to.')\n def is_element_in_container(thing_im_searching_for, container):\n for element in container:\n if element == thing_im_searching_for:\n return True\n return False\n 'Go South'"
},
{
"answer_id": 74548892,
"author": "Liran_k",
"author_id": 7448090,
"author_profile": "https://Stackoverflow.com/users/7448090",
"pm_score": 0,
"selected": false,
"text": "if command in directions: command directions command direction if any(single_direction in command for single_direction in directions)\n rooms"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20334526/"
] |
74,548,703
|
<p>Does the storing of local variables into stack memory, depends on using their values in function calls?</p>
<p>While doing some simple excercises with the "C" programming language and more specificly - with pointers, I've noticed the following anomaly (<em>I know it's not anomaly, it's just me with lack of proper understanding</em>) about initialized local varialbes.</p>
<p>When I define and initialize a couple of variables, and try to print the address (via the "printf()" function) of the first, and the last variable, I expect the address progression to corespond to the order of the listing of the variables. The first variable to have the highest address, and the last variable to occupy the (address of the first variable's memory block, minuns N memory blocks, where N is the count of the remaining variables, besides the first). Like that:</p>
<pre><code>v1 = memory block 10;
v2 = memory block 09;
v3 = memory block 08;
v4 = memory block 07;
</code></pre>
<p>And when I'm making the program to print just the address of v1 and v4, I expect it to print:</p>
<pre><code>Address of v1 is block 10;
Address of v4 is block 07;
</code></pre>
<p>Here comes to so-called "anomaly". When the program prints the address of these variables, it actually prints:</p>
<pre><code>Address of v1 is block10; (as it should be)
Address of v4 is block09; (isn't v2 supposed to be stored here?)
</code></pre>
<p>Here is the code example:</p>
<pre><code>#include <stdio.h>
int main()
{
char a = 1, b = 23, c = 123, d = 12;
printf("address of a: %p\naddress of d: %p", &a, &d);
return 0;
}
</code></pre>
<p>The output is:</p>
<pre><code>address of a: 0x7fffa86fc724
address of d: 0x7fffa86fc725
</code></pre>
<p>Now, if I add a third variable as an argument in the "printf()" function, the address of the first variable remains the same, all three variables will share adjacent memory blocks, following the order of defining the variables. Let's take the above four variables v1, v2, v3 and v4. If I print the addresses of v1, v3 and v4, I receive the following result:</p>
<pre><code>v1 = block10;
v3 = block09;
v4 = block08;
</code></pre>
<p>The order of listing the variable's addresses in the argument list of the "printf()" function has no effect on the ordering the addresses of the variables. I can see that the program still follows the order of defining the variables - the variable, which is defined first, will occupy the highest address, and every next variable, passed as argument to the function, will occuppy memory location, adjacent to the memory location of the previous variable, depending on the order of defining.</p>
<p>Code example:</p>
<pre><code>#include <stdio.h>
int main()
{
char a = 1, b = 23, c = 123, d = 12;
printf("address of c: %p\naddress of a: %p\naddress of d: %p", &c, &a, &d);
return 0;
}
</code></pre>
<p>Output will be:</p>
<pre><code>address of c: 0x7ffd970e27d5
address of a: 0x7ffd970e27d4
address of d: 0x7ffd970e27d6
</code></pre>
<p>Furthermore, If the variables are being passed at least once as arguments to a function call (different function besides "printf()"), then printing the address of v1 and v4 only, will produce the output, which I initially expected.</p>
<p>Code example:</p>
<pre><code>#include <stdio.h>
int main()
{
char a, b, c, d;
scanf(" %hhi %hhi %hhi %hhi", &a, &b, &c, &d);
printf("address of c: %p\naddress of a: %p\naddress of d: %p", &c, &a, &d);
return 0;
}
</code></pre>
<p>Output will be:</p>
<pre><code>address of a: 0x7ffeaac3c4a4
address of d: 0x7ffeaac3c4a7
</code></pre>
<p>Thus, I'm reaching the conclusion, that only a variables which are passed as an argument to a function call, are being stored in stack memory. What is happening, and more important - why is happening like this?</p>
<p>Does the compiler "throws out" of the program (during compilation process), variables, which despite being initialized with some value, are not used by any function as its arguments?</p>
|
[
{
"answer_id": 74549068,
"author": "hyde",
"author_id": 1717300,
"author_profile": "https://Stackoverflow.com/users/1717300",
"pm_score": 2,
"selected": false,
"text": "volatile"
},
{
"answer_id": 74549094,
"author": "0___________",
"author_id": 6110094,
"author_profile": "https://Stackoverflow.com/users/6110094",
"pm_score": 1,
"selected": false,
"text": "void foo(int x)\n{\n int z = x;\n printf(\"%d\\n\", z);\n}\n\nint main(void)\n{\n int y = 5;\n foo(y);\n}\n .string \"%d\\n\"\nfoo:\n mov esi, edi\n xor eax, eax\n mov edi, OFFSET FLAT:.LC0\n jmp printf\nmain:\n push rax\n mov edi, 5\n call foo\n xor eax, eax\n pop rdx\n ret\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11648577/"
] |
74,548,720
|
<p>HAVE
<br/>
M1234TESTABC
<br/>
M34567TESTABC
<br/>
M100023459ABC
<br/>
M234TEST
<br/></p>
<p>WANT
<br/>
TESTABC
<br/>
TESTABC
<br/>
ABC
<br/>
TEST</p>
|
[
{
"answer_id": 74549068,
"author": "hyde",
"author_id": 1717300,
"author_profile": "https://Stackoverflow.com/users/1717300",
"pm_score": 2,
"selected": false,
"text": "volatile"
},
{
"answer_id": 74549094,
"author": "0___________",
"author_id": 6110094,
"author_profile": "https://Stackoverflow.com/users/6110094",
"pm_score": 1,
"selected": false,
"text": "void foo(int x)\n{\n int z = x;\n printf(\"%d\\n\", z);\n}\n\nint main(void)\n{\n int y = 5;\n foo(y);\n}\n .string \"%d\\n\"\nfoo:\n mov esi, edi\n xor eax, eax\n mov edi, OFFSET FLAT:.LC0\n jmp printf\nmain:\n push rax\n mov edi, 5\n call foo\n xor eax, eax\n pop rdx\n ret\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2008558/"
] |
74,548,729
|
<p>Folks, could you please advise how I can rebase existing class so that it <strong>doesn't</strong> have particular interface in its parents ?</p>
<p>For example</p>
<pre><code>interface One {
fun one(): Unit
}
interface Two {
fun two(): Unit
}
class Test: One, Two {
// implementation of one() and two()
}
val newClass = ByteBuddy()
.rebase(Test::class.java)
.name("com.test.Test2")
.implement(Two::class.java)
.make()
.load(this.javaClass.classLoader, ClassLoadingStrategy.Default.WRAPPER)
.loaded
val inst = newClass.declaredConstructors.first().newInstance()
val isOne = inst is One
</code></pre>
<p>Unfortunately <code>isOne</code> is still true. What am I missing ?</p>
|
[
{
"answer_id": 74563476,
"author": "expert",
"author_id": 226895,
"author_profile": "https://Stackoverflow.com/users/226895",
"pm_score": 1,
"selected": true,
"text": "val fieldDelegate = \"delegate\"\nval unloaded = ByteBuddy()\n .subclass(Any::class.java)\n .defineField(fieldDelegate, Test::class.java, Opcodes.ACC_PRIVATE or Opcodes.ACC_FINAL)\n .name(Test::class.java.canonicalName + \"Wrapper\")\n .implement(Two::class.java)\n .defineConstructor(Visibility.PUBLIC)\n .withParameters(Test::class.java)\n .intercept(MethodCall.invoke(Object::class.java.getConstructor()).andThen(FieldAccessor.ofField(fieldDelegate).setsArgumentAt(0)))\n .method(ElementMatchers.isAbstract())\n .intercept(MethodDelegation.toField(fieldDelegate))\n .make()\n\nval clazz = unloaded\n .load(Test::class.java.classLoader, ClassLoadingStrategy.Default.WRAPPER)\n .loaded\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/226895/"
] |
74,548,748
|
<p>I have a database of polymorphic structure: a "base" type table and two "derived" types:</p>
<pre><code>CREATE TABLE ContactMethod(
id integer PRIMARY KEY
person_id integer
priority integer
allow_solicitation boolean
FOREIGN KEY(person_id) REFERENCES People(id)
)
CREATE TABLE PhoneNumbers(
contact_method_id integer PRIMARY KEY
phone_number varchar
FOREIGN KEY(contact_method_id) REFERENCES ContactMethod(id)
)
CREATE TABLE EmailAddresses(
contact_method_id integer PRIMARY KEY
email_address varchar
FOREIGN KEY(contact_method_id) REFERENCES ContactMethod(id)
)
</code></pre>
<p>I want to prevent orphaned <code>ContactMethod</code> records from existing, that is, a <code>ContactMethod</code> record with neither a corresponding <code>PhoneNumber</code> record nor an <code>EmailAddress</code> record. I've seen techniques for ensuring exclusivity (preventing a <code>ContactMethod</code> record with both a related <code>PhoneNumber</code> and <code>EmailAddress</code>), but not for preventing orphans.</p>
<p>One idea is a CHECK constraint that executes a custom function that executes queries. However, executing queries via functions in CHECK constraints is a bad idea.</p>
<p>Another idea is a View that will trigger a violation if an orphaned <code>ContactMethod</code> record is added. The "obvious" way to do this is to put a constraint on the View, but that's not allowed. So it has to be some sort of trick, probably involving an index on the View. Is that really the best (only?) way to enforce no orphans? If so, what is a working example?</p>
<p>Are there other ways? I could get rid of <code>ContactMethod</code> table and duplicate shared columns on the other two tables, but I don't want to do that. I'm primarily curious about capabilities available in MySQL and SQLite, but a solution in any SQL engine would be helpful.</p>
|
[
{
"answer_id": 74549284,
"author": "Olivier Jacot-Descombes",
"author_id": 880990,
"author_profile": "https://Stackoverflow.com/users/880990",
"pm_score": 0,
"selected": false,
"text": "ContactMethod ContactMethod"
},
{
"answer_id": 74551665,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 3,
"selected": true,
"text": "CREATE TABLE ContactMethod(\n id integer PRIMARY KEY\n person_id integer\n priority integer\n allow_solicitation boolean,\n phone_number varchar DEFAULT NULL\n email_address varchar DEFAULT NULL \n FOREIGN KEY(person_id) REFERENCES People(id)\n CHECK (COALESCE(phone_number, email_address) IS NOT NULL)\n)\n CREATE TABLE ContactMethod(\n id integer PRIMARY KEY\n person_id integer\n priority integer\n allow_solicitation boolean,\n phone_number_id integer DEFAULT NULL\n email_address_id integer DEFAULT NULL \n FOREIGN KEY(person_id) REFERENCES People(id)\n FOREIGN KEY(phone_number_id) REFERENCES PhoneNumbers(id)\n FOREIGN KEY(email_address_id) REFERENCES EmailAddresses(id)\n CHECK (COALESCE(phone_number_id, email_address_id) IS NOT NULL)\n)\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7535740/"
] |
74,548,792
|
<p>This is my code for react native for a carousel its a slider type thingy. I want the slider to scroll aswell with the other components but its not working as scroll view has already been used.</p>
<pre><code>import React, { useState } from "react";
import { SafeAreaView, StyleSheet, ScrollView, Text, Dimensions, View, Image } from "react-native";
function slider(){
const images = [
'https://iili.io/yzQepI.png',
'https://iili.io/yzQvIt.png'
]
const WIDTH = Dimensions.get('window').width;
const HEIGHT = Dimensions.get('window').height
const Slider = () =>{
const [imgActive, setimgActive] = useState(0);
onchange = (nativeEvent)=>{
if(nativeEvent){
const slide = Math.ceil(nativeEvent.contentOffset.x / nativeEvent.layoutMeasurement.width);
if(slide != imgActive){
setimgActive(slide);
}
}
}
return(
<SafeAreaView style={styles.container}>
<View style={styles.wrap}>
<ScrollView
onScroll={({nativeEvent}) => onchange(nativeEvent)}
showsHorizontalScrollIndicator={false}
pagingEnabled
horizontal
style={styles.wrap}
>
{
images.map((e,index) =>
<Image
key={e}
resizeMode='stretch'
style={styles.wrap}
source={{uri: e}}
/>
)
}
</ScrollView>
<View style={styles.wrapDot}>
{
images.map((e,index) =>
<Text
key={e}
style={imgActive == index ? styles.dotActive : styles.dot}
>
●
</Text>
)
}
</View>
</View>
</SafeAreaView>
)
}
const styles = StyleSheet.create({
container:{
flex:1
},
wrap:{
width: WIDTH,
height: HEIGHT * 0.25
},
wrapDot: {
position: 'absolute',
bottom: 0,
flexDirection:'row',
alignSelf: 'center'
},
dotActive:{
margin: 3,
color: 'black'
},
dot: {
margin: 3,
color: 'white'
}
})
}
export default Slider;
</code></pre>
<p>I have to make it scrollable vertically too but I have tried many ways its not working</p>
|
[
{
"answer_id": 74549284,
"author": "Olivier Jacot-Descombes",
"author_id": 880990,
"author_profile": "https://Stackoverflow.com/users/880990",
"pm_score": 0,
"selected": false,
"text": "ContactMethod ContactMethod"
},
{
"answer_id": 74551665,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 3,
"selected": true,
"text": "CREATE TABLE ContactMethod(\n id integer PRIMARY KEY\n person_id integer\n priority integer\n allow_solicitation boolean,\n phone_number varchar DEFAULT NULL\n email_address varchar DEFAULT NULL \n FOREIGN KEY(person_id) REFERENCES People(id)\n CHECK (COALESCE(phone_number, email_address) IS NOT NULL)\n)\n CREATE TABLE ContactMethod(\n id integer PRIMARY KEY\n person_id integer\n priority integer\n allow_solicitation boolean,\n phone_number_id integer DEFAULT NULL\n email_address_id integer DEFAULT NULL \n FOREIGN KEY(person_id) REFERENCES People(id)\n FOREIGN KEY(phone_number_id) REFERENCES PhoneNumbers(id)\n FOREIGN KEY(email_address_id) REFERENCES EmailAddresses(id)\n CHECK (COALESCE(phone_number_id, email_address_id) IS NOT NULL)\n)\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20583080/"
] |
74,548,875
|
<p>Very simple task: extract the region from an AWS arn.</p>
<p>Example:</p>
<pre><code>arn:aws:lambda:eu-west-2:12345678912:layer:my-awsome-layer:3
</code></pre>
<p>I need to extract <code>eu-west-2</code></p>
<p>I have a working regex for this: <a href="https://regex101.com/r/Apyhb8/1" rel="nofollow noreferrer"><code>^(?:[^:]+:){3}([^:]+).*</code></a></p>
<p>I tried this command, but it returns the entire string:</p>
<pre><code>echo "arn:aws:lambda:eu-west-2:12345678912:layer:my-awsome-layer:3" | grep -oP '^(?:[^:]+:){3}([^:]+).*'
</code></pre>
<p>output: <code>arn:aws:lambda:eu-west-2:12345678912:layer:my-awsome-layer:3</code></p>
<p>What is wrong with the above?</p>
|
[
{
"answer_id": 74549105,
"author": "Kappacake",
"author_id": 4220401,
"author_profile": "https://Stackoverflow.com/users/4220401",
"pm_score": 2,
"selected": false,
"text": "echo \"arn:aws:lambda:eu-west-2:12345678912:layer:my-awsome-layer:3\" | cut -d':' -f4\n eu-west-2"
},
{
"answer_id": 74550450,
"author": "Gilles Quenot",
"author_id": 465183,
"author_profile": "https://Stackoverflow.com/users/465183",
"pm_score": 2,
"selected": false,
"text": "grep -oP '\\w{2}-\\w+-\\d+'\n"
},
{
"answer_id": 74553187,
"author": "The fourth bird",
"author_id": 5424988,
"author_profile": "https://Stackoverflow.com/users/5424988",
"pm_score": 2,
"selected": false,
"text": ".* -oP \\K grep -oP '^(?:[^:]+:){3}\\K[^:]+'\n awk : awk -F: '{print $4}'\n sed sed 's/^\\([^:]\\+:\\)\\{3\\}\\([^:]\\+\\).*/\\2/'\n eu-west-2\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4220401/"
] |
74,548,895
|
<p>In this code when I am not using row then proceed button is not expanding but when I am using Row for adding one more widget then that is expanding.</p>
<p>This is my code.</p>
<pre><code>Stack(
alignment: Alignment.centerRight,
children: [
Container(
margin: EdgeInsets.all(5),
height: 150,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(
'assets/assets_allocation_image.png',
),
fit: BoxFit.fill)),
),
Column(
children: [
Text(
"Know your\nASSET ALLOCATION",
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontSize: tSize18,
fontWeight: FontWeight.w600),
overflow: TextOverflow.ellipsis,
maxLines: 2,
),
Padding(
padding: const EdgeInsets.only(
top: 20,
),
child: Container(
padding: const EdgeInsets.only(
left: 10, right: 10, top: 5, bottom: 5),
decoration: BoxDecoration(
color: orangeColor,
border: Border.all(
color: orangeColor, width: 2.0, style: BorderStyle.solid),
borderRadius: BorderRadius.all(
Radius.circular(3),
),
),
child: Row( // here
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Proceed',
style: TextStyle(
fontSize: tSize12,
fontWeight: FontWeight.w500,
color: whiteColor),
textAlign: TextAlign.center,
),
SizedBox(width: 3,),
Icon(
Icons.arrow_circle_right_outlined,
color: Colors.white,
size: 18,
)
],
),
),
),
],
),
],
);
</code></pre>
<p>This is my ui
<a href="https://i.stack.imgur.com/e5Cco.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e5Cco.jpg" alt="enter image description here" /></a></p>
<p>I want UI like this</p>
<p><a href="https://i.stack.imgur.com/IZIap.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IZIap.png" alt="enter image description here" /></a></p>
<h2>How to possible without wrapping in container and without giving width Becouse if I will give fix width then if user changed text size from mobile device then it will give me overflow error.
so how to fix it?</h2>
|
[
{
"answer_id": 74549105,
"author": "Kappacake",
"author_id": 4220401,
"author_profile": "https://Stackoverflow.com/users/4220401",
"pm_score": 2,
"selected": false,
"text": "echo \"arn:aws:lambda:eu-west-2:12345678912:layer:my-awsome-layer:3\" | cut -d':' -f4\n eu-west-2"
},
{
"answer_id": 74550450,
"author": "Gilles Quenot",
"author_id": 465183,
"author_profile": "https://Stackoverflow.com/users/465183",
"pm_score": 2,
"selected": false,
"text": "grep -oP '\\w{2}-\\w+-\\d+'\n"
},
{
"answer_id": 74553187,
"author": "The fourth bird",
"author_id": 5424988,
"author_profile": "https://Stackoverflow.com/users/5424988",
"pm_score": 2,
"selected": false,
"text": ".* -oP \\K grep -oP '^(?:[^:]+:){3}\\K[^:]+'\n awk : awk -F: '{print $4}'\n sed sed 's/^\\([^:]\\+:\\)\\{3\\}\\([^:]\\+\\).*/\\2/'\n eu-west-2\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15610685/"
] |
74,548,898
|
<p>I have installed ngx-toastr and imported in app.module.ts but getting this error while compiling
<a href="https://i.stack.imgur.com/yzrQ6.png" rel="nofollow noreferrer">enter image description here</a>...is it because i have set the properties of toaster in service file which I created like below?<a href="https://i.stack.imgur.com/coKP0.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>I tried adding @import '~ngx-toastr/toastr.css'; in styles.css still no effect. Does anyone know what might be the reason for this error and how to fix it</p>
|
[
{
"answer_id": 74561913,
"author": "Jhonatan Martinez",
"author_id": 20591545,
"author_profile": "https://Stackoverflow.com/users/20591545",
"pm_score": 2,
"selected": false,
"text": "npm install --save ngx-toastr@15.2.0"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20583120/"
] |
74,548,901
|
<p>I have following data in my mongoDb database and I want to find the student from the array of students objects by iterating on all my students field of my database with the id the students array objects have.</p>
<p>I want to do it with the help of mongoose please help me find the solution as I am unable to find it.</p>
<p>Here is my database:</p>
<pre><code>[
{
"_id": "637ddf6d68a8284187a4d7e7",
"college": "MIT"
"students": [
{
"name": "Morgan Freeman",
"image": "/public/morg.jpg",
"_id": "637ddf6d68a8284187a4d7e8"
},
{
"name": "John Smith",
"image": "/public/john.jpg",
"_id": "637ddf6d68a8284187a4d7e9"
}
]
},
{
"_id": "637ddf6d68a8284187a4dfhd",
"college": "DOT"
"students": [
{
"name": "Windy rona",
"image": "/public/windy.jpg",
"_id": "637ddf6d68a8284187a4dvh3"
},
{
"name": "Richard",
"image": "/public/richard.jpg",
"_id": "637ddf6d68a8284187a4duhd"
}
]
},
]
</code></pre>
<p>I tried using:</p>
<pre><code> database.find({}).select('students').where('_id':req.params.id)
</code></pre>
<p>but it didnot work</p>
|
[
{
"answer_id": 74561913,
"author": "Jhonatan Martinez",
"author_id": 20591545,
"author_profile": "https://Stackoverflow.com/users/20591545",
"pm_score": 2,
"selected": false,
"text": "npm install --save ngx-toastr@15.2.0"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20583013/"
] |
74,548,906
|
<p>I have two models EcommerceOrders and Medicines</p>
<pre><code>class EcommerceOrders extends Model
{
use HasFactory;
protected $table = 'ecommerce_orders';
protected $fillable = [
'user_id',
'manager_id',
'first_name',
'last_name',
'phone_number',
'email',
'address',
'city',
'zip_code',
'other_info',
'products',
'total_price',
'qr_code',
'status',
'assigned_to',
'save_client_info',
];
class Medicines extends Model
{
use HasFactory;
use Notifiable;
use SoftDeletes;
/**
* The attributes that are mass assignable.
*
* @var string[]
*/
protected $table = 'medicines';
protected $fillable = [
'name',
'subcategory_id',
'group',
'unity',
'description',
'price',
'discount',
'type',
'photo_path',
'slug'
];
</code></pre>
<p>In the EcommerceOrders Model the products field holds info about the items purchased by a client
What I'm trying to do is to get the data about those products.This is how i have created the relationships in each model</p>
<p>EcommerceOrders</p>
<pre><code>public function items()
{
return $this->hasMany(Medicines::class,'id');
}
</code></pre>
<p>Medicines</p>
<pre><code> public function ecomOrders()
{
return $this->belongsTo(EcommerceOrders::class);
}
</code></pre>
<p>However when i try to get the data It only displays the information about the first item in products</p>
<pre><code> EcommerceOrders::where('id',3)->with('items')->get()
Illuminate\Database\Eloquent\Collection {#3313
all: [
App\Models\EcommerceOrders {#3298
id: 3,
user_id: 2,
manager_id: 3,
first_name: "test",
last_name: "test1",
phone_number: "3550123456",
email: "asd@test.com",
address: "addsss",
city: "qwerr",
zip_code: "625",
other_info: null,
products: "{"2":1,"3":1}", //id: quantity
total_price: "8309,00",
qr_code: "2416718593exKrLbcNEpVm3nYI6S31652402",
status: "ordered",
assigned_to: null,
save_client_info: 1,
created_at: "2022-11-22 17:35:32",
updated_at: "2022-11-22 17:35:32",
items: Illuminate\Database\Eloquent\Collection {#3315
all: [
App\Models\Medicines {#3327
id: 3,
group: 11,
name: "quisquam",
subcategory_id: 8,
unity: "499mg",
description: "Quo autem aut quibusdam dolorem aut sit.",
price: 6935.0,
discount: 9.0,
type: 0,
photo_path: "https://via.placeholder.com/640x480.png/009900?text=laudantium",
slug: "quisquam",
created_at: "2022-11-21 11:39:29",
updated_at: "2022-11-21 11:39:29",
deleted_at: null,
},
],
},
},
],
}
</code></pre>
|
[
{
"answer_id": 74561913,
"author": "Jhonatan Martinez",
"author_id": 20591545,
"author_profile": "https://Stackoverflow.com/users/20591545",
"pm_score": 2,
"selected": false,
"text": "npm install --save ngx-toastr@15.2.0"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20211699/"
] |
74,548,910
|
<p>android {
compileSdkVersion 33
ndkVersion flutter.ndkVersion</p>
<p>added the 33 and this is the output :</p>
<p>/C:/flutter/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core-1.24.0/lib/src/firebase_app.dart:18:25: Error: Member not found: 'FirebaseAppPlatform.verifyExtends'.
FirebaseAppPlatform.verifyExtends(_delegate);</p>
<p>FAILURE: Build failed with an exception.</p>
<ul>
<li><p>Where:
Script 'C:\flutter\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1159</p>
</li>
<li><p>What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.</p>
</li>
</ul>
<blockquote>
<p>Process 'command 'C:\flutter\flutter\bin\flutter.bat'' finished with non-zero exit value 1</p>
</blockquote>
<ul>
<li>Try:</li>
</ul>
<blockquote>
<p>Run with --stacktrace option to get the stack trace.
Run with --info or --debug option to get more log output.
Run with --scan to get full insights.</p>
</blockquote>
<ul>
<li>Get more help at <a href="https://help.gradle.org" rel="nofollow noreferrer">https://help.gradle.org</a></li>
</ul>
<p>BUILD FAILED in 17s
Exception: Gradle task assembleDebug failed with exit code 1</p>
|
[
{
"answer_id": 74548953,
"author": "powerman23rus",
"author_id": 6163011,
"author_profile": "https://Stackoverflow.com/users/6163011",
"pm_score": 1,
"selected": false,
"text": "compileSdkVersion build.gradle path_to_your_project/android/app/build.gradle \n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20582929/"
] |
74,548,919
|
<p>Is there a way to get the value of a JS variable into a Velocity variable?</p>
<p>In a page script, I have some JS code and I'd like to just parse an output to a Velocity variable but I can't seem to find a way.</p>
<p>The other way around seems to work though, I can use the <code>$!pageContext.put</code> and .get to read a Velocity variable and use it's value into some JS code.</p>
<p>I was also trying to create a page parameter, and I could use the <code>$pageParameter.VARIABLE.valUE()</code> to read the parameter value, which didn't help me.</p>
<p>What I'm trying to do is, inside a page script, have a variable that stores how many work items ranging from today-7d to today. I thought this should work with something like
<code>#set($newSrFilter = $transaction.workItems.search.query("type:changerequest AND created:[$today-7d$ TO $today$]"))</code> but the $today variable doesn't work in page scripts for some reason.</p>
|
[
{
"answer_id": 74613511,
"author": "Julien Llanes",
"author_id": 13183060,
"author_profile": "https://Stackoverflow.com/users/13183060",
"pm_score": 1,
"selected": true,
"text": " #set($releaseOverdueCompleteFilter = $transaction.workItems.search.query(\"type:changerequest AND NOT HAS_VALUE:resolution AND status:ApprovedComplete2 AND updated:[$aWeekAgo TO 30000000]\"))\n #set($releaseOverdueComplete = $releaseOverdueCompleteFilter.size())\n $!pageContext.put(\"releaseOverdueComplete\", $releaseOverdueComplete)\n $releaseOverdueComplete\n $pageContext.put() $pageContext.get(\"releaseOverdueComplete\")"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13183060/"
] |
74,548,921
|
<p>I have a list of addresses in a text document and I want to add a comma after address line 1, and then save it all to a new text document.</p>
<p>example my list of addresses are</p>
<pre><code>Address 1404 756 48 Stockholm
Address 9 756 52 Stockholm
Address 53 B lgh 1001 619 34 Stockholm
Address 72 B lgh 1101 619 30 Stockholm
Address 52 A 619 33 Stockholm
</code></pre>
<p>What I want the output to be</p>
<pre><code>Address 1404, 756 48 Stockholm
Address 9, 756 52 Stockholm
Address 53 B lgh 1001, 619 34 Stockholm
Address 72 B lgh 1101, 619 30 Stockholm
Address 52 A, 619 33 Stockholm
</code></pre>
<p>I can't figure out how to accurately place the comma at the right place (before the zip code) since the amount of whitespace isn't the same for all addresses. The zip code consists of 5 digits for instance (756 48).</p>
|
[
{
"answer_id": 74549151,
"author": "Fedor Soldatkin",
"author_id": 14370531,
"author_profile": "https://Stackoverflow.com/users/14370531",
"pm_score": 0,
"selected": false,
"text": "str.rstrip() file_line = 'Address 72 B lgh 1101 619 30 Stockholm'\n\n# Use maxsplit=3\nfirst_line, *second_line = address.rsplit(' ', 3)\n\nnew_address = f'{first_line}, {' '.join(second_line)}'\n"
},
{
"answer_id": 74549163,
"author": "chrslg",
"author_id": 20037042,
"author_profile": "https://Stackoverflow.com/users/20037042",
"pm_score": 2,
"selected": false,
"text": "import re\nre.sub(r'\\s(\\d{3}\\s\\d{2}\\s.*)$', ', \\\\1', 'Address 53 B lgh 1001 619 34 Stockholm')\n# 'Address 53 B lgh 1001, 619 34\\xa0Stockholm'\n \\xa0"
},
{
"answer_id": 74549170,
"author": "Remzinho",
"author_id": 2484591,
"author_profile": "https://Stackoverflow.com/users/2484591",
"pm_score": -1,
"selected": true,
"text": "with open('sample.txt') as file:\n df = file.read()\n for line in df.split('\\n'):\n split_line = line.split()\n split_line.insert(-3, ',')\n new_line = \" \".join(elem for elem in split_line).strip()\n print(new_line)\n Address 1404 , 756 48 Stockholm\nAddress 9 , 756 52 Stockholm\nAddress 53 B lgh 1001 , 619 34 Stockholm\nAddress 72 B lgh 1101 , 619 30 Stockholm\nAddress 52 A , 619 33 Stockholm\n strip()"
},
{
"answer_id": 74549367,
"author": "Ammar_Asim_23",
"author_id": 18134093,
"author_profile": "https://Stackoverflow.com/users/18134093",
"pm_score": 0,
"selected": false,
"text": "s='''Address 1404 756 48 Stockholm\nAddress 9 756 52 Stockholm\nAddress 53 B lgh 1001 619 34 Stockholm\nAddress 72 B lgh 1101 619 30 Stockholm\nAddress 52 A 619 33 Stockholm'''\nlis=s.split('\\n')\nlis1=[i.split(' ') for i in lis]\nfor i in lis1:\n for j in i:\n if i.index(j) == 1:\n lis1[lis1.index(i)][i.index(j)] = j +','\n\nlis1=[' '.join(i) for i in lis1]\nlis1='\\n'.join(lis1)\nprint(lis1)\n"
},
{
"answer_id": 74550347,
"author": "larapsodia",
"author_id": 1333623,
"author_profile": "https://Stackoverflow.com/users/1333623",
"pm_score": 0,
"selected": false,
"text": ">>> import re\n>>> address_list = ['Address 1404 756 48 Stockholm', 'Address 9 756 52 Stockholm', \n'Address 53 B lgh 1001 619 34 Stockholm', 'Address 72 B lgh 1101 619 30 Stockholm', \n'Address 52 A 619 33 Stockholm']\n\n# Define regex pattern as space+3digits+space+2digits+word.\n# Parens capture both that pattern and everything before it (.*)\n>>> p = re.compile(r\"(.*)( \\d{3} \\d{2} \\w+)\")\n\n# Create a new list, replacing each item with group1+comma+group2\n>>> new_addresses = [re.sub(p, r\"\\1,\\2\", a) for a in address_list]\n\n>>> for a in new_addresses: print(a) \n\n'Address 1404, 756 48 Stockholm'\n'Address 9, 756 52 Stockholm'\n'Address 53 B lgh 1001, 619 34 Stockholm'\n'Address 72 B lgh 1101, 619 30 Stockholm'\n'Address 52 A, 619 33 Stockholm'\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16302076/"
] |
74,548,982
|
<p>I'm trying to create a to-do-list. I think I've created the <strong>CSS</strong> design and done all the <strong>HTML</strong> markup correctly. However, when I'm trying to use <code>clearElement()</code> to remove my HTML markup of the <code>taskContainer</code> to allow the user input their own task (blank value as default). But my code does not seem to work.</p>
<p><strong>HTML Code:</strong></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" />
<link
href="https://fonts.googleapis.com/css2?family=Ruda:wght@400;500;600;700&display=swap"
rel="stylesheet"
/>
<link rel="stylesheet" href="style.css" />
<script defer src="script.js"></script>
<title>To-do List</title>
</head>
<body>
<h1 class="title">To-Do List</h1>
<div class="all-tasks">
<h2 class="task-list-title">Task list</h2>
<ul class="task-list" data-lists>
<li class="list-name active-list">Work</li>
<li class="list-name">Study</li>
<li class="list-name">Youtube</li>
</ul>
<form class="center-newlistname" action="" data-new-list-form>
<input
type="text"
class="new-list"
data-new-list-input
placeholder="New list name"
aria-label="New list name"
/>
<button class="btn-create" aria-label="create new list">Add</button>
</form>
</div>
<div class="todo-list" data-list-display-container>
<div class="todo-header">
<h2 class="list-title" data-list-title>Daily Task</h2>
<p class="task-count" data-list-count>3 task remaining</p>
</div>
<div class="todo-body">
<div class="tasks" data-tasks></div>
<div class="task">
<input type="checkbox" id="task-1" />
<label for="task-1">
<span class="custom-checkbox"></span>
Task 1
</label>
</div>
<!-- Task 1 -->
<div class="task">
<input type="checkbox" id="task-2" />
<label for="task-2">
<span class="custom-checkbox"></span>
Task 2
</label>
</div>
<!-- Task 2 -->
<div class="task">
<input type="checkbox" id="task-3" />
<label for="task-3">
<span class="custom-checkbox"></span>
Task 3
</label>
</div>
<!-- Task 3 -->
<div class="new-task-creator">
<form action="" data-new-task-form>
<input
type="text"
data-new-task-input
class="new-list"
placeholder="New task"
aria-label="New task"
/>
<button class="btn-task" aria-label="create new task">+</button>
</form>
</div>
<div class="task-delete">
<button class="btn delete">Clear task</button>
<button class="btn delete" data-delete-list-btn>Delete list</button>
</div>
</div>
</div>
<template id="task-template">
<div class="task">
<input type="checkbox" id="task-3" />
<label for="task-3">
<span class="custom-checkbox"></span>
</label>
</div>
</template>
</body>
</html>
</code></pre>
<p><strong>Javascript Code:</strong></p>
<pre><code>const listsContainer = document.querySelector('[data-lists]')
const newListForm = document.querySelector('[data-new-list-form]')
const newListInput = document.querySelector('[data-new-list-input]')
const deleteListButton = document.querySelector('[data-delete-list-btn]')
const listDisplayContainer = document.querySelector('[data-list-display-container]')
const listTitlElement = document.querySelector('[data-list-title]')
const listCountElement = document.querySelector('[data-list-count]')
const taskContainer = document.querySelector('[data-tasks]')
const taskTemplate = document.getElementById('task-template')
const newTaskForm = document.querySelector('[data-new-task-form]')
const newTaskInput = document.querySelector('[data-new-task-input]')
const LOCAL_STORAGE_LIST_KEY = 'task.list'
const LOCAL_STORAGE_SELECTED_LIST_ID_KEY = 'task.selectedListID'
let lists = JSON.parse(localStorage.getItem(LOCAL_STORAGE_LIST_KEY))||[]
let selectedListId = localStorage.getItem(LOCAL_STORAGE_SELECTED_LIST_ID_KEY)
listsContainer.addEventListener('click', e =>{
if (e.target.tagName.toLowerCase() === 'li'){
selectedListId = e.target.dataset.listId
saveAndRender()
}
})
newListForm.addEventListener('submit', e =>{
e.preventDefault()
const listName = newListInput.value
if (listName == null || listName === '') return
const list = createList(listName)
newListInput.value = null
lists.push(list)
saveAndRender()
})
newTaskForm.addEventListener('submit', e =>{
e.preventDefault()
const taskName = newTaskInput.value
if (taskName == null || taskName === '') return
const task = createTask(taskName)
newTaskInput.value = null
const selectedList = lists.find(list => list.id === selectedListId)
selectedList.task.push(task)
saveAndRender()
})
deleteListButton.addEventListener('click', e =>{
lists = lists.filter(list => list.id !== selectedListId)
selectedListId = null
saveAndRender()
})
function createList(name){
return {id: Date.now().toString(), name: name, tasks: []}
}
function createTask(name){
return {id: Date.now().toString(), name: name, complete: false}
}
function saveAndRender(){
save()
render()
}
function save(){
localStorage.setItem(LOCAL_STORAGE_LIST_KEY, JSON.stringify(lists))
localStorage.setItem(LOCAL_STORAGE_SELECTED_LIST_ID_KEY, selectedListId)
}
function render(){
clearElement(listsContainer)
renderLists()
const selectedList = lists.find(list => list.id === selectedListId)
if(selectedListId == null){
listDisplayContainer.style.display = 'none'
} else {
listDisplayContainer.style.display = ''
listTitlElement.innerText = selectedList.name
renderTaskCount(selectedList)
clearElement(taskContainer)
renderTasks(selectedList)
}
}
function renderTasks(selectedList){
selectedList.tasks.forEach(task =>{
const taskElement = document.importNode(taskTemplate.content, true)
const checkbox = taskElement.querySelector('input')
checkbox.id = task.id
checkbox.checked = task.complete
const label = taskElement.querySelector('label')
label.htmlFor = task.id
label.append(task.name)
taskContainer.appendChild(taskElement)
})
}
function renderTaskCount(selectedList){
const incompleteTaskCount = selectedList.tasks.filter(task => !task.complete).length
const taskString = incompleteTaskCount === 1 ? "task" : "tasks"
listCountElement.innerText = `${incompleteTaskCount} ${taskString} remaining`
}
function renderLists(){
lists.forEach(list =>{
const listElement = document.createElement('li')
listElement.dataset.listId = list.id
listElement.classList.add("list-name")
listElement.innerText = list.name
if (list.id === selectedListId){
listElement.classList.add('active-list')
}
listsContainer.appendChild(listElement)
})
}
function clearElement(element){
while (element.firstChild){
element.removeChild(element.firstChild)
}
}
render()
</code></pre>
<p>What I had expected to happen is: the tasks on the right side should disappear (<em>Task 1</em>, <em>Task 2</em>, <em>Task 3</em>) and allow the user to input their own tasks.</p>
|
[
{
"answer_id": 74549151,
"author": "Fedor Soldatkin",
"author_id": 14370531,
"author_profile": "https://Stackoverflow.com/users/14370531",
"pm_score": 0,
"selected": false,
"text": "str.rstrip() file_line = 'Address 72 B lgh 1101 619 30 Stockholm'\n\n# Use maxsplit=3\nfirst_line, *second_line = address.rsplit(' ', 3)\n\nnew_address = f'{first_line}, {' '.join(second_line)}'\n"
},
{
"answer_id": 74549163,
"author": "chrslg",
"author_id": 20037042,
"author_profile": "https://Stackoverflow.com/users/20037042",
"pm_score": 2,
"selected": false,
"text": "import re\nre.sub(r'\\s(\\d{3}\\s\\d{2}\\s.*)$', ', \\\\1', 'Address 53 B lgh 1001 619 34 Stockholm')\n# 'Address 53 B lgh 1001, 619 34\\xa0Stockholm'\n \\xa0"
},
{
"answer_id": 74549170,
"author": "Remzinho",
"author_id": 2484591,
"author_profile": "https://Stackoverflow.com/users/2484591",
"pm_score": -1,
"selected": true,
"text": "with open('sample.txt') as file:\n df = file.read()\n for line in df.split('\\n'):\n split_line = line.split()\n split_line.insert(-3, ',')\n new_line = \" \".join(elem for elem in split_line).strip()\n print(new_line)\n Address 1404 , 756 48 Stockholm\nAddress 9 , 756 52 Stockholm\nAddress 53 B lgh 1001 , 619 34 Stockholm\nAddress 72 B lgh 1101 , 619 30 Stockholm\nAddress 52 A , 619 33 Stockholm\n strip()"
},
{
"answer_id": 74549367,
"author": "Ammar_Asim_23",
"author_id": 18134093,
"author_profile": "https://Stackoverflow.com/users/18134093",
"pm_score": 0,
"selected": false,
"text": "s='''Address 1404 756 48 Stockholm\nAddress 9 756 52 Stockholm\nAddress 53 B lgh 1001 619 34 Stockholm\nAddress 72 B lgh 1101 619 30 Stockholm\nAddress 52 A 619 33 Stockholm'''\nlis=s.split('\\n')\nlis1=[i.split(' ') for i in lis]\nfor i in lis1:\n for j in i:\n if i.index(j) == 1:\n lis1[lis1.index(i)][i.index(j)] = j +','\n\nlis1=[' '.join(i) for i in lis1]\nlis1='\\n'.join(lis1)\nprint(lis1)\n"
},
{
"answer_id": 74550347,
"author": "larapsodia",
"author_id": 1333623,
"author_profile": "https://Stackoverflow.com/users/1333623",
"pm_score": 0,
"selected": false,
"text": ">>> import re\n>>> address_list = ['Address 1404 756 48 Stockholm', 'Address 9 756 52 Stockholm', \n'Address 53 B lgh 1001 619 34 Stockholm', 'Address 72 B lgh 1101 619 30 Stockholm', \n'Address 52 A 619 33 Stockholm']\n\n# Define regex pattern as space+3digits+space+2digits+word.\n# Parens capture both that pattern and everything before it (.*)\n>>> p = re.compile(r\"(.*)( \\d{3} \\d{2} \\w+)\")\n\n# Create a new list, replacing each item with group1+comma+group2\n>>> new_addresses = [re.sub(p, r\"\\1,\\2\", a) for a in address_list]\n\n>>> for a in new_addresses: print(a) \n\n'Address 1404, 756 48 Stockholm'\n'Address 9, 756 52 Stockholm'\n'Address 53 B lgh 1001, 619 34 Stockholm'\n'Address 72 B lgh 1101, 619 30 Stockholm'\n'Address 52 A, 619 33 Stockholm'\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16107968/"
] |
74,548,983
|
<p>My input has multiple layers of nested arrays from which I need to concatenate these fields: <code>employeeName</code>, <code>subject</code>, <code>text</code> to form comment text.</p>
<p>I then need to <code>label</code> the type of comment text and create an output that is a single array array with multiple objects, that contain grouped key value pairs. My spec is generating an array, with one object that contains an array with many members.</p>
<p>Here is a representation of my input:</p>
<pre class="lang-json prettyprint-override"><code>{
"accounts": [
{
"comments": [
{
"outgetcommentstext": [
{
"text": "accountObject1 comment text1"
}
],
"employeeName": "John Doe",
"subject": "acct1-obj1-subject"
},
{
"outgetcommentstext": [
{
"text": "accountObject1 comment text2"
}
],
"employeeName": "Jane Doe",
"subject": "acct1-obj2-subject"
},
{
"outgetcommentstext": [
{
"text": "accountObject1 comment text3"
}
],
"employeeName": "Jax Doe",
"subject": "acct1-obj3-subject"
}
]
},
{
"comments": [
{
"outgetcommentstext": [
{
"text": "account2-Object1 comment text1"
}
],
"employeeName": "Jill Doe",
"subject": "acct2-obj1-subject"
},
{
"outgetcommentstext": [
{
"text": "account2-Object2 comment text2"
}
],
"employeeName": "Janet Doe",
"subject": "acct2-obj2-subject"
},
{
"outgetcommentstext": [
{
"text": "account2Object3 comment text3"
}
],
"employeeName": "Jacob Doe",
"subject": "acct2-obj3-subject"
}
]
}
]
}
</code></pre>
<p>Here is my spec</p>
<pre class="lang-json prettyprint-override"><code>[
{
"spec": {
"accounts": {
"*": {
"comments": {
"*": {
"outgetcommentstext": {
"*": {
"CommentText": "=concat(@(3,employeeName),'-',@(3,subject),'-',@(1,text))"
}
}
}
}
}
}
},
"operation": "modify-overwrite-beta"
},
{
"operation": "shift",
"spec": {
"accounts": {
"*": {
"comments": {
"*": {
"outgetcommentstext": {
"*": {
"CommentText": "Job.JobCommentList[&3].CommentText",
"#XYZ": "Job.JobCommentList[&3].CommentType"
}
}
}
}
}
}
}
}
]
</code></pre>
<p>Here is my current output:</p>
<pre class="lang-json prettyprint-override"><code>{
"Job" : {
"JobCommentList" : [ {
"CommentText" : [ "John Doe-acct1-obj1-subject-accountObject1 comment text1", "Jill Doe-acct2-obj1-subject-account2-Object1 comment text1" ],
"CommentType" : [ "XYZ", "XYZ" ]
}, {
"CommentText" : [ "Jane Doe-acct1-obj2-subject-accountObject1 comment text2", "Janet Doe-acct2-obj2-subject-account2-Object2 comment text2" ],
"CommentType" : [ "XYZ", "XYZ" ]
}, {
"CommentText" : [ "Jax Doe-acct1-obj3-subject-accountObject1 comment text3", "Jacob Doe-acct2-obj3-subject-account2Object3 comment text3" ],
"CommentType" : [ "XYZ", "XYZ" ]
} ]
}
}
</code></pre>
<p>This is my desired output:</p>
<pre class="lang-json prettyprint-override"><code>{
"Job": {
"JobCommentList": [
{
"CommentText": "John Doe-acct1-obj1-subject-accountObject1 comment text1",
"CommentType": "XYZ"
},
{
"CommentText": "Jill Doe-acct2-obj1-subject-account2-Object1 comment text1",
"CommentType": "XYZ"
},
{
"CommentText": "Jane Doe-acct1-obj2-subject-accountObject1 comment text2",
"CommentType": "XYZ"
},
{
"CommentText": "Jacob Doe-acct2-obj3-subject-account2Object3 comment text3",
"CommentType": "XYZ"
}
]
}
}
</code></pre>
<p><strong>Note:</strong> my input could have one or many account objects. I found that my spec works if there is only one account object</p>
|
[
{
"answer_id": 74549151,
"author": "Fedor Soldatkin",
"author_id": 14370531,
"author_profile": "https://Stackoverflow.com/users/14370531",
"pm_score": 0,
"selected": false,
"text": "str.rstrip() file_line = 'Address 72 B lgh 1101 619 30 Stockholm'\n\n# Use maxsplit=3\nfirst_line, *second_line = address.rsplit(' ', 3)\n\nnew_address = f'{first_line}, {' '.join(second_line)}'\n"
},
{
"answer_id": 74549163,
"author": "chrslg",
"author_id": 20037042,
"author_profile": "https://Stackoverflow.com/users/20037042",
"pm_score": 2,
"selected": false,
"text": "import re\nre.sub(r'\\s(\\d{3}\\s\\d{2}\\s.*)$', ', \\\\1', 'Address 53 B lgh 1001 619 34 Stockholm')\n# 'Address 53 B lgh 1001, 619 34\\xa0Stockholm'\n \\xa0"
},
{
"answer_id": 74549170,
"author": "Remzinho",
"author_id": 2484591,
"author_profile": "https://Stackoverflow.com/users/2484591",
"pm_score": -1,
"selected": true,
"text": "with open('sample.txt') as file:\n df = file.read()\n for line in df.split('\\n'):\n split_line = line.split()\n split_line.insert(-3, ',')\n new_line = \" \".join(elem for elem in split_line).strip()\n print(new_line)\n Address 1404 , 756 48 Stockholm\nAddress 9 , 756 52 Stockholm\nAddress 53 B lgh 1001 , 619 34 Stockholm\nAddress 72 B lgh 1101 , 619 30 Stockholm\nAddress 52 A , 619 33 Stockholm\n strip()"
},
{
"answer_id": 74549367,
"author": "Ammar_Asim_23",
"author_id": 18134093,
"author_profile": "https://Stackoverflow.com/users/18134093",
"pm_score": 0,
"selected": false,
"text": "s='''Address 1404 756 48 Stockholm\nAddress 9 756 52 Stockholm\nAddress 53 B lgh 1001 619 34 Stockholm\nAddress 72 B lgh 1101 619 30 Stockholm\nAddress 52 A 619 33 Stockholm'''\nlis=s.split('\\n')\nlis1=[i.split(' ') for i in lis]\nfor i in lis1:\n for j in i:\n if i.index(j) == 1:\n lis1[lis1.index(i)][i.index(j)] = j +','\n\nlis1=[' '.join(i) for i in lis1]\nlis1='\\n'.join(lis1)\nprint(lis1)\n"
},
{
"answer_id": 74550347,
"author": "larapsodia",
"author_id": 1333623,
"author_profile": "https://Stackoverflow.com/users/1333623",
"pm_score": 0,
"selected": false,
"text": ">>> import re\n>>> address_list = ['Address 1404 756 48 Stockholm', 'Address 9 756 52 Stockholm', \n'Address 53 B lgh 1001 619 34 Stockholm', 'Address 72 B lgh 1101 619 30 Stockholm', \n'Address 52 A 619 33 Stockholm']\n\n# Define regex pattern as space+3digits+space+2digits+word.\n# Parens capture both that pattern and everything before it (.*)\n>>> p = re.compile(r\"(.*)( \\d{3} \\d{2} \\w+)\")\n\n# Create a new list, replacing each item with group1+comma+group2\n>>> new_addresses = [re.sub(p, r\"\\1,\\2\", a) for a in address_list]\n\n>>> for a in new_addresses: print(a) \n\n'Address 1404, 756 48 Stockholm'\n'Address 9, 756 52 Stockholm'\n'Address 53 B lgh 1001, 619 34 Stockholm'\n'Address 72 B lgh 1101, 619 30 Stockholm'\n'Address 52 A, 619 33 Stockholm'\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14566248/"
] |
74,548,993
|
<p>I would like to know if it is possible to use the function itself in its default parameter.</p>
<pre><code>function somename(a,b=somename()){
return a+b;
}
somename(10);
</code></pre>
|
[
{
"answer_id": 74549097,
"author": "CertainPerformance",
"author_id": 9515207,
"author_profile": "https://Stackoverflow.com/users/9515207",
"pm_score": 3,
"selected": true,
"text": "function somename(a, b = somename(3, 5)) {\n return a + b;\n}\nconsole.log(somename(10));"
},
{
"answer_id": 74556798,
"author": "pope_maverick",
"author_id": 3065781,
"author_profile": "https://Stackoverflow.com/users/3065781",
"pm_score": 0,
"selected": false,
"text": "eg: someName() // invoking the function someName\n someName // will search for the variable definition along the scope chain.\n eg:\nfunction someName(a = someName) {\n someName(); // Now you are invoking the function with the signature :()\"\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74548993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11662563/"
] |
74,549,027
|
<p>I attach you an example with my attempts because I am not able to manage / arrange data through R code. I have a datraframe that first column is the taxonomic lineage of microorganisms. And each column is a DNA sequence recodified by ASV1 and so on.</p>
<p>For each column, only some of its values will have value ==1. The rest will be 0.</p>
<p>I attach below the code to be reproducible. The RData to load the dataframe file is freely-available on: <a href="https://www.jottacloud.com/s/191545e30dc99e14823959fadba6d189be5" rel="nofollow noreferrer">https://www.jottacloud.com/s/191545e30dc99e14823959fadba6d189be5 </a></p>
<pre><code>
data<-read_xlsx("combined_allranks_mpa.xlsx")
datastackoverchange <- data
datastackoverchange <- as.data.frame(datastackoverchange)
names(datastackoverchange)[2:3812] <- sprintf("ASV_%d",seq(1:3811))
save.image("stackoverflow_data.RData")
# I perform a subset of the first two columns
data1<-datastackoverchange[ , c(1,2)]
# Each column has a plenty of zeros except for the lineage that correspond.
# I remove all zeroes that are not of interest by:
data1[data1==0] <- NA
data1<-data1[complete.cases(data1),]
</code></pre>
<p>And I obtain the next table (see the link of the image)</p>
<p>[The column ASV1 have 4 rows of value "1" because each "1" value arrives to a specific lineage rank]
(<a href="https://i.stack.imgur.com/OZi9W.jpg" rel="nofollow noreferrer">https://i.stack.imgur.com/OZi9W.jpg</a>)</p>
<p>In the first example (subset c(1,2) I have that the most
complete ASV1 (most length) it is
k__Bacteria|p__Firmicutes|c__Clostridia|o__Clostridiales. Usually,
the longest ASV lineage it will appear in the last position in the dataframe.</p>
<p>Nevertheless, from this step I would like to create
maybe from an empty datafame or list that copies me for example:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Column A</th>
<th>Column B</th>
</tr>
</thead>
<tbody>
<tr>
<td>ASV1</td>
<td>k__Bacteria/p__Firmicutes/c__Clostridia/o__Clostridiales</td>
</tr>
<tr>
<td>ASV2</td>
<td>and so on</td>
</tr>
</tbody>
</table>
</div>
<p>The "/" are "|" in the dataframe.</p>
<p>and so on for each column (ASV2, ASV3...) creating a loop to iterize it</p>
<p>In order to exploit the data (I have 3811 different ASV) for further analysis.</p>
<p>Thanks on advance for your hints and helps about how can I overcome this situation.</p>
|
[
{
"answer_id": 74550770,
"author": "Camillionnaire",
"author_id": 16453562,
"author_profile": "https://Stackoverflow.com/users/16453562",
"pm_score": 1,
"selected": false,
"text": "values <- apply(datastackoverchange[,2:ncol(datastackoverchange)],2,FUN = function(x)datastackoverchange$Classification[which(x==1) %>% dplyr::last()])\n\nid <- colnames(datastackoverchange[,2:ncol(datastackoverchange)])\n\ndf <- data.frame(id, values)\n"
},
{
"answer_id": 74550780,
"author": "MagíBC",
"author_id": 17437839,
"author_profile": "https://Stackoverflow.com/users/17437839",
"pm_score": 0,
"selected": false,
"text": "load(\"stackoverflow_data.RData\")\ndatastackoverchange <-as.data.frame(datastackoverchange)\n\nlibrary(tidyverse)\n\ndat_clean_def <- datastackoverchange %>% \n remove_rownames %>%\n column_to_rownames(var=\"Classification\") \n\nidx <- which(dat_clean_def == \"1\", arr.ind=TRUE) \nresults <- data.frame(Row=rownames(dat_clean_def)[idx[, 1]],\n Col=colnames(dat_clean_def)[idx[, 2]],\n Val=dat_clean_def[idx])\nresults\n"
},
{
"answer_id": 74558183,
"author": "Camillionnaire",
"author_id": 16453562,
"author_profile": "https://Stackoverflow.com/users/16453562",
"pm_score": 1,
"selected": false,
"text": "function(x){ \n data_1 <- datastackoverchange$Classification[which(x==1)] \n id_max <- which.max(str_count(datastackoverchange$Classification[which(x==1)], \"_\"))\nreturn(data_1[id_max])\n}\n library(stringr)\nresults %>% group_by(Col) %>% filter(Row == Row[which.max(str_count(Row,\"_\"))])\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74549027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20522749/"
] |
74,549,045
|
<p>I have a FastAPI web application using Jinja2 templates, which is working fine on <code>localhost</code>, but <strong>not</strong> in production. The problem is that is not generating URLs for JavaScript and other <code>static</code> files correctly. I have deployed it on EC2 instance using <code>gunicorn</code> and <code>nginx</code>.</p>
<p>I have this line of code in my HTML file:</p>
<pre class="lang-html prettyprint-override"><code><script src="{{ url_for('static', path='js/login_signup.js') }}"></script>
</code></pre>
<p>The problem is that it is generating the URL like this:</p>
<pre class="lang-html prettyprint-override"><code><script src="http://127.0.0.1:8000/static/js/login_signup.js"></script>
</code></pre>
<p>What I want is to generate something like this:</p>
<pre class="lang-html prettyprint-override"><code><script src="http://my_domain.com/static/js/login_signup.js"></script>
</code></pre>
|
[
{
"answer_id": 74550770,
"author": "Camillionnaire",
"author_id": 16453562,
"author_profile": "https://Stackoverflow.com/users/16453562",
"pm_score": 1,
"selected": false,
"text": "values <- apply(datastackoverchange[,2:ncol(datastackoverchange)],2,FUN = function(x)datastackoverchange$Classification[which(x==1) %>% dplyr::last()])\n\nid <- colnames(datastackoverchange[,2:ncol(datastackoverchange)])\n\ndf <- data.frame(id, values)\n"
},
{
"answer_id": 74550780,
"author": "MagíBC",
"author_id": 17437839,
"author_profile": "https://Stackoverflow.com/users/17437839",
"pm_score": 0,
"selected": false,
"text": "load(\"stackoverflow_data.RData\")\ndatastackoverchange <-as.data.frame(datastackoverchange)\n\nlibrary(tidyverse)\n\ndat_clean_def <- datastackoverchange %>% \n remove_rownames %>%\n column_to_rownames(var=\"Classification\") \n\nidx <- which(dat_clean_def == \"1\", arr.ind=TRUE) \nresults <- data.frame(Row=rownames(dat_clean_def)[idx[, 1]],\n Col=colnames(dat_clean_def)[idx[, 2]],\n Val=dat_clean_def[idx])\nresults\n"
},
{
"answer_id": 74558183,
"author": "Camillionnaire",
"author_id": 16453562,
"author_profile": "https://Stackoverflow.com/users/16453562",
"pm_score": 1,
"selected": false,
"text": "function(x){ \n data_1 <- datastackoverchange$Classification[which(x==1)] \n id_max <- which.max(str_count(datastackoverchange$Classification[which(x==1)], \"_\"))\nreturn(data_1[id_max])\n}\n library(stringr)\nresults %>% group_by(Col) %>% filter(Row == Row[which.max(str_count(Row,\"_\"))])\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74549045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19296108/"
] |
74,549,071
|
<p>I am relatively new to the field of Android Application development, and I have been meaning to ask this problem I have been trying to resolve for hours. The issue is that every time I click a card view from the fragment with the RecyclerView, the app crashes showing this error from the "Problem" tab.</p>
<p><a href="https://i.stack.imgur.com/cf1uw.png" rel="nofollow noreferrer">Error from "Problem" tab</a></p>
<p>What I expect to happen is to print a Toast message showing the corresponding User ID of a card view.
<a href="https://i.stack.imgur.com/bVZdz.png" rel="nofollow noreferrer">Clickable Card Views</a></p>
<p>Here is the code of the Fragment with with cards and recycler view:</p>
<pre><code>class UserDetailsFragment : Fragment() {
private lateinit var userDetailsViewModel: UserDetailsViewModel
// private lateinit var binding: FragmentUserDetailsBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val binding: FragmentUserDetailsBinding = DataBindingUtil.inflate(
inflater,
R.layout.fragment_user_details,
container,
false
)
val application = requireNotNull(this.activity).application
val dao = RegisterDatabase.getInstance(application).registerDatabaseDao
val repository = RegisterRepository(dao)
val factory = UserDetailsViewModelFactory(repository, application)
userDetailsViewModel = ViewModelProvider(this, factory).get(UserDetailsViewModel::class.java)
binding.userDetailsLayout = userDetailsViewModel
val adapter = MyRecycleViewAdapter(RegisterEntityListener { userId ->
Toast.makeText(activity, userId.toString(), Toast.LENGTH_LONG).show()
})
binding.usersRecyclerView.adapter = adapter
userDetailsViewModel.users.observe(viewLifecycleOwner, Observer {
it?.let {
adapter.submitList(it)
}
})
binding.lifecycleOwner = this
userDetailsViewModel.navigateTo.observe(viewLifecycleOwner, Observer { hasFinished ->
if (hasFinished == true) {
val action = UserDetailsFragmentDirections.actionUserDetailsFragmentToLoginFragment()
NavHostFragment.findNavController(this).navigate(action)
userDetailsViewModel.doneNavigating()
}
})
binding.usersRecyclerView.layoutManager = LinearLayoutManager(this.context)
return binding.root
}
}
</code></pre>
<p>Here is the code of the RecyclerView adapter using ListAdapter</p>
<pre><code>class MyRecycleViewAdapter(val clickListener: RegisterEntityListener): ListAdapter<RegisterEntity, MyRecycleViewAdapter.MyViewHolder>(DiffCallBack()) {
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val item = getItem(position)
holder.bind(item!!, clickListener)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
return MyViewHolder.from(parent)
}
class MyViewHolder (val binding: ListItemBinding): RecyclerView.ViewHolder(binding.root) {
fun bind(user: RegisterEntity, clickListener: RegisterEntityListener) {
binding.clickListener = clickListener
binding.FirstNameTextView.text = user.firstName
binding.secondNameTextView.text = user.lastName
binding.userTextField.text = user.userName
}
companion object {
fun from(parent: ViewGroup): MyViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding = ListItemBinding.inflate(layoutInflater, parent, false)
return MyViewHolder(binding)
}
}
}
}
class DiffCallBack: DiffUtil.ItemCallback<RegisterEntity>() {
override fun areItemsTheSame(oldItem: RegisterEntity, newItem: RegisterEntity): Boolean {
return oldItem.userId == newItem.userId
}
override fun areContentsTheSame(oldItem: RegisterEntity, newItem: RegisterEntity): Boolean {
return oldItem == newItem
}
}
class RegisterEntityListener(val clickListener: (userId: Int) -> Unit) {
fun onClick(user: RegisterEntity) = clickListener(user.userId)
}
</code></pre>
<p>Here is the layout of the ViewHolder</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="user"
type="com.example.login_register.database.RegisterEntity" />
<variable
name="clickListener"
type="com.example.login_register.userDetails.RegisterEntityListener" />
</data>
<LinearLayout
android:id="@+id/linear_layout_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:orientation="vertical">
<androidx.cardview.widget.CardView
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:clickable="true"
android:focusable="true"
android:onClick="@{() -> clickListener.onClick(user)}"
app:cardBackgroundColor="@color/black"
app:cardCornerRadius="10dp"
app:cardElevation="10dp">
<LinearLayout
android:id="@+id/list_item_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="@+id/linear_layout_2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="@+id/First_name_text_View"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="TextView"
android:textColor="@color/cardview_light_background"
android:textSize="30dp"
android:textStyle="bold" />
<TextView
android:id="@+id/second_name_text_View"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="TextView"
android:textColor="@color/cardview_light_background"
android:textSize="30dp"
android:textStyle="bold" />
</LinearLayout>
<TextView
android:id="@+id/user_TextField"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="TextView"
android:textColor="@color/cardview_light_background"
android:textSize="20dp"
android:textStyle="bold" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
</layout>
</code></pre>
<p>I tried searching for hours and unfortunately, I was not able to resolve the problem because I cannot find other similar problems or whenever I found something somehow similar, I cannot understand it because they are written in Java. If there are additional information needed (e.g., other source code files of the android project), I am very much obliged to provide them. Any response would be highly appreciated Thank you very much!</p>
<p>I would also like to inform that I am using <a href="https://developer.android.com/codelabs/kotlin-android-training-interacting-with-items?continue=https%3A%2F%2Fdeveloper.android.com%2Fcourses%2Fpathways%2Fandroid-development-with-kotlin-10%23codelab-https%3A%2F%2Fdeveloper.android.com%2Fcodelabs%2Fkotlin-android-training-interacting-with-items#3" rel="nofollow noreferrer">this</a> learning material as a reference to achieve what my goal for this android project or exploration.</p>
|
[
{
"answer_id": 74550770,
"author": "Camillionnaire",
"author_id": 16453562,
"author_profile": "https://Stackoverflow.com/users/16453562",
"pm_score": 1,
"selected": false,
"text": "values <- apply(datastackoverchange[,2:ncol(datastackoverchange)],2,FUN = function(x)datastackoverchange$Classification[which(x==1) %>% dplyr::last()])\n\nid <- colnames(datastackoverchange[,2:ncol(datastackoverchange)])\n\ndf <- data.frame(id, values)\n"
},
{
"answer_id": 74550780,
"author": "MagíBC",
"author_id": 17437839,
"author_profile": "https://Stackoverflow.com/users/17437839",
"pm_score": 0,
"selected": false,
"text": "load(\"stackoverflow_data.RData\")\ndatastackoverchange <-as.data.frame(datastackoverchange)\n\nlibrary(tidyverse)\n\ndat_clean_def <- datastackoverchange %>% \n remove_rownames %>%\n column_to_rownames(var=\"Classification\") \n\nidx <- which(dat_clean_def == \"1\", arr.ind=TRUE) \nresults <- data.frame(Row=rownames(dat_clean_def)[idx[, 1]],\n Col=colnames(dat_clean_def)[idx[, 2]],\n Val=dat_clean_def[idx])\nresults\n"
},
{
"answer_id": 74558183,
"author": "Camillionnaire",
"author_id": 16453562,
"author_profile": "https://Stackoverflow.com/users/16453562",
"pm_score": 1,
"selected": false,
"text": "function(x){ \n data_1 <- datastackoverchange$Classification[which(x==1)] \n id_max <- which.max(str_count(datastackoverchange$Classification[which(x==1)], \"_\"))\nreturn(data_1[id_max])\n}\n library(stringr)\nresults %>% group_by(Col) %>% filter(Row == Row[which.max(str_count(Row,\"_\"))])\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74549071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20583098/"
] |
74,549,077
|
<p>Assume I have data in a CSV that I've imported in R. This is a simplified version- the real sheet has 4700+ rows. There are months in 1 digits and there are months in 2 digits.</p>
<pre><code>| | Posted.On |
|1| 5/18/2022 |
|2| 07/04/2022|
|3| 6/20/2022 |
</code></pre>
<p>I would like to change all months in 1 digits to 2 digits (e.g. 5/18/2022 to 05/18/2022). How can I do this?</p>
|
[
{
"answer_id": 74550770,
"author": "Camillionnaire",
"author_id": 16453562,
"author_profile": "https://Stackoverflow.com/users/16453562",
"pm_score": 1,
"selected": false,
"text": "values <- apply(datastackoverchange[,2:ncol(datastackoverchange)],2,FUN = function(x)datastackoverchange$Classification[which(x==1) %>% dplyr::last()])\n\nid <- colnames(datastackoverchange[,2:ncol(datastackoverchange)])\n\ndf <- data.frame(id, values)\n"
},
{
"answer_id": 74550780,
"author": "MagíBC",
"author_id": 17437839,
"author_profile": "https://Stackoverflow.com/users/17437839",
"pm_score": 0,
"selected": false,
"text": "load(\"stackoverflow_data.RData\")\ndatastackoverchange <-as.data.frame(datastackoverchange)\n\nlibrary(tidyverse)\n\ndat_clean_def <- datastackoverchange %>% \n remove_rownames %>%\n column_to_rownames(var=\"Classification\") \n\nidx <- which(dat_clean_def == \"1\", arr.ind=TRUE) \nresults <- data.frame(Row=rownames(dat_clean_def)[idx[, 1]],\n Col=colnames(dat_clean_def)[idx[, 2]],\n Val=dat_clean_def[idx])\nresults\n"
},
{
"answer_id": 74558183,
"author": "Camillionnaire",
"author_id": 16453562,
"author_profile": "https://Stackoverflow.com/users/16453562",
"pm_score": 1,
"selected": false,
"text": "function(x){ \n data_1 <- datastackoverchange$Classification[which(x==1)] \n id_max <- which.max(str_count(datastackoverchange$Classification[which(x==1)], \"_\"))\nreturn(data_1[id_max])\n}\n library(stringr)\nresults %>% group_by(Col) %>% filter(Row == Row[which.max(str_count(Row,\"_\"))])\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74549077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19375357/"
] |
74,549,078
|
<p>I am a c++ newbie so I'm not sure how to write this, but basically I want a function that takes in a few parameters and returns a function pointer that does not need any parameters and can be executed for later use. Exactly like a closure.</p>
<p>I know c++ does not have closures, but can get some of the same effects with lambda expessions. I'm just not sure if it can do what I want it to do. Again I don't know much c++. I have been going through tutorials and reading posts about how lambdas work in c++, but I can't figure out how do get this code to work.</p>
<p>Here is some example code of what I'm trying to in typescript</p>
<pre><code>let myVariable;
const myClosure = (param1: number, param2: number, param3, string, ) => {
return () => {
// Do something with params
console.log(param1, param2, param3);
}
}
function whereInitalized() {
myVariable = myClosure(1,2,"name");
}
function whereExecuted() {
myVariable(); // prints the params
}
whereInitalized();
whereExecuted();
</code></pre>
<p>This is what I want in c++, but it's wrong</p>
<pre><code>// Not correct syntax or type
// Having trouble getting typing for this variable;
std::function<void(param1: T, param2: P, param3: V)> (*myVariable)() = myClosure;
std::function<void()> myClosure(param1: T, param2: P, param3: V) {
return []() { // Returns a function that does not take a parameter
param1.someMethod();
param2->Call(blah, blah);
// ... More work
};
}
void functionWhereInitalized() {
myVariable = myClosure(param1, param2, param3);
}
void functionWhereExecuted() {
myVariable();
}
</code></pre>
<p>And here is what I have in c++, works, but cannot take in parameter</p>
<pre><code>std::function<void()> myVariable = myClosure;
std::function<void()> myClosure() {
return [num = 99]() mutable {
// Test code to see it gets called
num++;
std::cout << num << " -- " << "\n";
};
}
void functionWhereInitalized() {
myVariable = myClosure();
}
void functionWhereExecuted() {
myVariable();
}
</code></pre>
<p>I appreciate any responses in advance!</p>
|
[
{
"answer_id": 74550770,
"author": "Camillionnaire",
"author_id": 16453562,
"author_profile": "https://Stackoverflow.com/users/16453562",
"pm_score": 1,
"selected": false,
"text": "values <- apply(datastackoverchange[,2:ncol(datastackoverchange)],2,FUN = function(x)datastackoverchange$Classification[which(x==1) %>% dplyr::last()])\n\nid <- colnames(datastackoverchange[,2:ncol(datastackoverchange)])\n\ndf <- data.frame(id, values)\n"
},
{
"answer_id": 74550780,
"author": "MagíBC",
"author_id": 17437839,
"author_profile": "https://Stackoverflow.com/users/17437839",
"pm_score": 0,
"selected": false,
"text": "load(\"stackoverflow_data.RData\")\ndatastackoverchange <-as.data.frame(datastackoverchange)\n\nlibrary(tidyverse)\n\ndat_clean_def <- datastackoverchange %>% \n remove_rownames %>%\n column_to_rownames(var=\"Classification\") \n\nidx <- which(dat_clean_def == \"1\", arr.ind=TRUE) \nresults <- data.frame(Row=rownames(dat_clean_def)[idx[, 1]],\n Col=colnames(dat_clean_def)[idx[, 2]],\n Val=dat_clean_def[idx])\nresults\n"
},
{
"answer_id": 74558183,
"author": "Camillionnaire",
"author_id": 16453562,
"author_profile": "https://Stackoverflow.com/users/16453562",
"pm_score": 1,
"selected": false,
"text": "function(x){ \n data_1 <- datastackoverchange$Classification[which(x==1)] \n id_max <- which.max(str_count(datastackoverchange$Classification[which(x==1)], \"_\"))\nreturn(data_1[id_max])\n}\n library(stringr)\nresults %>% group_by(Col) %>% filter(Row == Row[which.max(str_count(Row,\"_\"))])\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74549078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7741858/"
] |
74,549,091
|
<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>.footer_image {
height: 60rem;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer>
<div class="footer_image">
<img src="https://via.placeholder.com/200x200" style="margin-left:20px">
</div>
</footer></code></pre>
</div>
</div>
</p>
<p>I cant seem to target the properties to change my image in my footer, what am I doing wrong?</p>
|
[
{
"answer_id": 74550770,
"author": "Camillionnaire",
"author_id": 16453562,
"author_profile": "https://Stackoverflow.com/users/16453562",
"pm_score": 1,
"selected": false,
"text": "values <- apply(datastackoverchange[,2:ncol(datastackoverchange)],2,FUN = function(x)datastackoverchange$Classification[which(x==1) %>% dplyr::last()])\n\nid <- colnames(datastackoverchange[,2:ncol(datastackoverchange)])\n\ndf <- data.frame(id, values)\n"
},
{
"answer_id": 74550780,
"author": "MagíBC",
"author_id": 17437839,
"author_profile": "https://Stackoverflow.com/users/17437839",
"pm_score": 0,
"selected": false,
"text": "load(\"stackoverflow_data.RData\")\ndatastackoverchange <-as.data.frame(datastackoverchange)\n\nlibrary(tidyverse)\n\ndat_clean_def <- datastackoverchange %>% \n remove_rownames %>%\n column_to_rownames(var=\"Classification\") \n\nidx <- which(dat_clean_def == \"1\", arr.ind=TRUE) \nresults <- data.frame(Row=rownames(dat_clean_def)[idx[, 1]],\n Col=colnames(dat_clean_def)[idx[, 2]],\n Val=dat_clean_def[idx])\nresults\n"
},
{
"answer_id": 74558183,
"author": "Camillionnaire",
"author_id": 16453562,
"author_profile": "https://Stackoverflow.com/users/16453562",
"pm_score": 1,
"selected": false,
"text": "function(x){ \n data_1 <- datastackoverchange$Classification[which(x==1)] \n id_max <- which.max(str_count(datastackoverchange$Classification[which(x==1)], \"_\"))\nreturn(data_1[id_max])\n}\n library(stringr)\nresults %>% group_by(Col) %>% filter(Row == Row[which.max(str_count(Row,\"_\"))])\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74549091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20573306/"
] |
74,549,113
|
<p>When I read this doc: <a href="https://developers.google.com/android/guides/google-services-plugin" rel="nofollow noreferrer">https://developers.google.com/android/guides/google-services-plugin</a> they say :</p>
<blockquote>
<p>As part of enabling Google APIs or Firebase services in your Android application you may have to add the google-services plugin to
your build.gradle file:</p>
<pre><code>dependencies {
classpath 'com.google.gms:google-services:4.3.14'
// ...
}
</code></pre>
</blockquote>
<p>then they say also :</p>
<blockquote>
<p>Add dependencies for basic libraries required for the services you
have enabled. This step requires that you apply the Google Services
Gradle plugin in your app/build.gradle file, like so: apply plugin:
'com.google.gms.google-services'</p>
</blockquote>
<p>so i start a blank new android project in the very last version of android studio and I have for the root build.gradle:</p>
<pre><code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
id 'com.android.application' version '7.3.1' apply false
id 'com.android.library' version '7.3.1' apply false
}
</code></pre>
<p>and in app/build.gradle:</p>
<pre><code>plugins {
id 'com.android.application'
}
android {
namespace 'app.dependencieswalker'
compileSdk 32
defaultConfig {
applicationId "app.dependencieswalker"
minSdk 21
targetSdk 32
versionCode 1
versionName "1.0"
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation "com.alcinoe:alcinoe-firebase:1.0.0"
}
</code></pre>
<p>so where I must add the</p>
<pre><code>dependencies {
classpath 'com.google.gms:google-services:4.3.14'
// ...
}
</code></pre>
<p>and</p>
<pre><code>apply plugin: 'com.google.gms.google-services' ?
</code></pre>
|
[
{
"answer_id": 74550770,
"author": "Camillionnaire",
"author_id": 16453562,
"author_profile": "https://Stackoverflow.com/users/16453562",
"pm_score": 1,
"selected": false,
"text": "values <- apply(datastackoverchange[,2:ncol(datastackoverchange)],2,FUN = function(x)datastackoverchange$Classification[which(x==1) %>% dplyr::last()])\n\nid <- colnames(datastackoverchange[,2:ncol(datastackoverchange)])\n\ndf <- data.frame(id, values)\n"
},
{
"answer_id": 74550780,
"author": "MagíBC",
"author_id": 17437839,
"author_profile": "https://Stackoverflow.com/users/17437839",
"pm_score": 0,
"selected": false,
"text": "load(\"stackoverflow_data.RData\")\ndatastackoverchange <-as.data.frame(datastackoverchange)\n\nlibrary(tidyverse)\n\ndat_clean_def <- datastackoverchange %>% \n remove_rownames %>%\n column_to_rownames(var=\"Classification\") \n\nidx <- which(dat_clean_def == \"1\", arr.ind=TRUE) \nresults <- data.frame(Row=rownames(dat_clean_def)[idx[, 1]],\n Col=colnames(dat_clean_def)[idx[, 2]],\n Val=dat_clean_def[idx])\nresults\n"
},
{
"answer_id": 74558183,
"author": "Camillionnaire",
"author_id": 16453562,
"author_profile": "https://Stackoverflow.com/users/16453562",
"pm_score": 1,
"selected": false,
"text": "function(x){ \n data_1 <- datastackoverchange$Classification[which(x==1)] \n id_max <- which.max(str_count(datastackoverchange$Classification[which(x==1)], \"_\"))\nreturn(data_1[id_max])\n}\n library(stringr)\nresults %>% group_by(Col) %>% filter(Row == Row[which.max(str_count(Row,\"_\"))])\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74549113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1114043/"
] |
74,549,120
|
<p>This is my data looks like</p>
<p><code>my_list = [('Australia',), ('Europe',)]</code></p>
<p>I need to remove the comma "," after every element.</p>
<p><code>new_list = [('Australia'), ('Europe')]</code></p>
<p>I can achieve this using a loop and extracting one element at a time and replacing it. Is there a better way to achieve the same. Thank you</p>
|
[
{
"answer_id": 74550770,
"author": "Camillionnaire",
"author_id": 16453562,
"author_profile": "https://Stackoverflow.com/users/16453562",
"pm_score": 1,
"selected": false,
"text": "values <- apply(datastackoverchange[,2:ncol(datastackoverchange)],2,FUN = function(x)datastackoverchange$Classification[which(x==1) %>% dplyr::last()])\n\nid <- colnames(datastackoverchange[,2:ncol(datastackoverchange)])\n\ndf <- data.frame(id, values)\n"
},
{
"answer_id": 74550780,
"author": "MagíBC",
"author_id": 17437839,
"author_profile": "https://Stackoverflow.com/users/17437839",
"pm_score": 0,
"selected": false,
"text": "load(\"stackoverflow_data.RData\")\ndatastackoverchange <-as.data.frame(datastackoverchange)\n\nlibrary(tidyverse)\n\ndat_clean_def <- datastackoverchange %>% \n remove_rownames %>%\n column_to_rownames(var=\"Classification\") \n\nidx <- which(dat_clean_def == \"1\", arr.ind=TRUE) \nresults <- data.frame(Row=rownames(dat_clean_def)[idx[, 1]],\n Col=colnames(dat_clean_def)[idx[, 2]],\n Val=dat_clean_def[idx])\nresults\n"
},
{
"answer_id": 74558183,
"author": "Camillionnaire",
"author_id": 16453562,
"author_profile": "https://Stackoverflow.com/users/16453562",
"pm_score": 1,
"selected": false,
"text": "function(x){ \n data_1 <- datastackoverchange$Classification[which(x==1)] \n id_max <- which.max(str_count(datastackoverchange$Classification[which(x==1)], \"_\"))\nreturn(data_1[id_max])\n}\n library(stringr)\nresults %>% group_by(Col) %>% filter(Row == Row[which.max(str_count(Row,\"_\"))])\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74549120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11402025/"
] |
74,549,121
|
<p>I am trying to find all substrings within a multi string in python 3, I want to find all words in between the word 'Colour:':</p>
<p>example string:</p>
<pre><code>str = """
Colour: Black
Colour: Green
Colour: Black
Colour: Red
Colour: Orange
Colour: Blue
Colour: Green
"""
</code></pre>
<p>I want to get all of the colours into a list like:</p>
<pre><code>x = ['Black', 'Green', 'Black', 'Red', 'Orange', 'Blue', 'Green']
</code></pre>
<p>I want to do this using Python re</p>
<p>Whats the fastest way of doing this with re.search , re.findall, re.finditer or even another method.</p>
<p>I've tried doing this as a list comprehension:</p>
<pre><code>z = [x.group() for x in re.finditer('Colour:(.*?)Colour:', str)]
</code></pre>
<p>but it returns an empty list ?</p>
<p>any ideas?</p>
|
[
{
"answer_id": 74549298,
"author": "charon25",
"author_id": 16114044,
"author_profile": "https://Stackoverflow.com/users/16114044",
"pm_score": 2,
"selected": true,
"text": ". colours = re.findall(r'Colour: (.+)', str)\n re.findall colours = [line.split()[1] for line in str.splitlines()]\n"
},
{
"answer_id": 74549403,
"author": "Roxy",
"author_id": 13007041,
"author_profile": "https://Stackoverflow.com/users/13007041",
"pm_score": 0,
"selected": false,
"text": "Colour: list(filter(None, str.replace(\"\\n\", \"\").replace(\" \", \"\").split(\"Colour:\")))\n ['Black', 'Green', 'Black', 'Red', 'Orange', 'Blue', 'Green']\n"
},
{
"answer_id": 74549575,
"author": "RufusVS",
"author_id": 925592,
"author_profile": "https://Stackoverflow.com/users/925592",
"pm_score": 0,
"selected": false,
"text": "x = re.findall(\"Colour: (.*)\",str)\n str"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74549121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16798681/"
] |
74,549,139
|
<p>I need to show notice/pop ups upon hitting of a button. Similar approaches are working in other views and controllers of the app but here on this Import button things are not working since long. None of the <code>redirect_to</code> works in the controller while their similar usage in other controller works.</p>
<p><code>routes.rb</code>:</p>
<pre class="lang-rb prettyprint-override"><code>Rails.application.routes.draw do
namespace :admin do
get '', to: 'dashboard#index', as: 'root'
# resourceful routes
resources :oauth_clients
resources :tenants do
resources :sites do
#resources :production_shifts
resources :units do
resources :log_data_fields, only: [:import, :create, :index, :destroy, :download_csv] do
get :download_csv
# collection route
collection do
post :import #post action
end
end
</code></pre>
<p><code>log_data_fields_controller.rb</code>:</p>
<pre class="lang-rb prettyprint-override"><code>class Admin::LogDataFieldsController < Admin::BaseController
require 'csv'
# import request(this is gonna be a POST action)
def import
logger.debug("*****Testing the logger.*****")
file = params[:log_data_field][:file]
# return redirect_to [:admin, @tenant, @site, @unit], notice: "Only CSV please !!" unless file.content_type == "text/csv"
return redirect_to admin_tenant_site_unit_log_data_fields_url, notice: "Only CSV please !!" unless file.content_type == "text/csv"
file = File.open(file)
csv = CSV.parse(file, headers: true)
# csv = CSV.parse(file, headers: true, col_sep: ";")
@unit = Unit.find_by_id(params[:unit_id])
# p @unit.id
total_rows = CSV.read(file).count
count = 1
# binding.b
csv.each do |row|
tag_hash = {}
tag_hash[:name] = row["Name"]
tag_hash[:alias] = row["Alias"]
tag_hash[:column_type] = row["Type"]
tag_hash[:unit_id] = @unit.id
tag_hash[:is_active] = row["Active"]
# binding.b
# p row
logger.debug("+++++++++++Mapping++++++++++++++")
@log_data_field = LogDataField.create(tag_hash)
# binding.b
if @log_data_field.save
count += 1
logger.debug("--------Saves--------")
# return redirect_to admin_tenant_site_unit_log_data_fields_path(@tenant, @site, @unit),
else
# return redirect_to admin_tenant_site_unit_log_data_fields_path(@tenant, @site, @unit),
# render :_importtags
end
end
logger.debug("-------------Going down----------")
if count == total_rows && count > 1
logger.debug("-------------All succeeded----------")
redirect_to admin_tenant_site_unit_log_data_fields_path(@tenant, @site, @unit), flash: { :notice => "Success"}
# flash.notice = "Success : Tags imported from CSV !"
elsif total_rows == 0
logger.debug("-------------All zero----------")
flash.alert = "Import Failure : CSV cant be empty"
render :action => 'index', :notice => "Import Failure : CSV cant be empty."
else
logger.debug("-------------Failed down----------")
flash.alert = "Import Failure"
render :action => 'index', :notice => "Import Failure"
end
redirect_to import_admin_tenant_site_unit_log_data_fields_url(@tenant, @site, @unit), notice:"Imported tags !"
end
</code></pre>
<p><code>_importtags.html.haml</code>:</p>
<pre class="lang-rb prettyprint-override"><code>%p{:style => "color: green"}= notice
= form_with model:@log_data_field, url: import_admin_tenant_site_unit_log_data_fields_path, method: :post do |form|
- if @log_data_field.errors.any?
#error_explanation
%h2= "#{pluralize(@log_data_field.errors.count, "error")} prohibited this log_data_field from being saved:"
%ul
- @log_data_field.errors.full_messages.each do |message|
%li= message
-# = link_to 'Download sample csv', [:admin, @tenant, @site, @unit, @log_data_field], method: :get
= form.file_field :file, accept: ".csv"
-# = form.file_field :file
<br>
<br>
-#button.btn.primary{:type => "submit", data: { disable_with: "Please wait..."}}
%button.btn.primary{:type => "submit"}
= "Import"
</code></pre>
<p>Comments are the things I have tried.</p>
<p>Sorry if you find the question or its structure very unprofessional but I am beginner and learning regularly. I need to render the view again upon hitting that <code>Import</code> button to show either any errors if availabe or success on importing tags from csv. There is also issue of notice not being visible or popping up and redirect_to not working when non-csv document is submitted in the form which should give a warning too but it is not coming.</p>
<p>I believe the solution will be very short or some typo or silly mistake in understanding the path vs url routes.</p>
<p><em><strong>EDIT</strong></em> As per <code>@markets</code> suggestion I made all the redirect_to with <code>return</code> which are used in between so the notice are working but they appear only on refresh. Still can't get them instantly on button click:</p>
<pre class="lang-rb prettyprint-override"><code>class Admin::LogDataFieldsController < Admin::BaseController
before_action :set_tenant
before_action :set_site
before_action :set_unit
require 'csv'
# import request(this is gonna be a POST action)
def import
logger.debug("*****Testing the logger.*****")
file = params[:log_data_field][:file]
# return redirect_to [:admin, @tenant, @site, @unit], notice: "Only CSV please !!" unless file.content_type == "text/csv"
return redirect_to admin_tenant_site_unit_log_data_fields_path(@tenant, @site, @unit), notice: "Only CSV please !!" unless file.content_type == "text/csv"
file = File.open(file)
csv = CSV.parse(file, headers: true)
# csv = CSV.parse(file, headers: true, col_sep: ";")
@unit = Unit.find_by_id(params[:unit_id])
# p @unit.id
total_rows = CSV.read(file).count
count = 1
# binding.b
csv.each do |row|
tag_hash = {}
tag_hash[:name] = row["Name"]
tag_hash[:alias] = row["Alias"]
tag_hash[:column_type] = row["Type"]
tag_hash[:unit_id] = @unit.id
tag_hash[:is_active] = row["Active"]
# binding.b
# p row
logger.debug("+++++++++++Mapping++++++++++++++")
@log_data_field = LogDataField.create(tag_hash)
# binding.b
if @log_data_field.save
count += 1
logger.debug("--------Saves--------")
# return redirect_to admin_tenant_site_unit_log_data_fields_path(@tenant, @site, @unit),
# else
# return redirect_to admin_tenant_site_unit_log_data_fields_path(@tenant, @site, @unit),
# render :_importtags
end
end
logger.debug("-------------Going down----------")
if count == total_rows && count > 1
logger.debug("-------------All succeeded----------")
return redirect_to admin_tenant_site_unit_log_data_fields_path(@tenant, @site, @unit), flash: { :notice => "Success : Tags imported from CSV !"}
elsif total_rows == 0
logger.debug("-------------All zero----------")
return redirect_to admin_tenant_site_unit_log_data_fields_path(@tenant, @site, @unit), flash: { :notice => "Import Failure : CSV cant be empty"}
else
logger.debug("-------------Failed down----------")
return redirect_to admin_tenant_site_unit_log_data_fields_path(@tenant, @site, @unit), flash: { :notice => "Import Failure : PLease check CSV"}
end
redirect_to import_admin_tenant_site_unit_log_data_fields_url(@tenant, @site, @unit), notice:"Imported tags !"
end
</code></pre>
|
[
{
"answer_id": 74549611,
"author": "markets",
"author_id": 3033649,
"author_profile": "https://Stackoverflow.com/users/3033649",
"pm_score": 0,
"selected": false,
"text": "render redirect_to return return redirect_to(...)\n redirect_to(...) and return\n"
},
{
"answer_id": 74582181,
"author": "Meet Makwana",
"author_id": 17796286,
"author_profile": "https://Stackoverflow.com/users/17796286",
"pm_score": 2,
"selected": true,
"text": "form_with form_for _importtags.html.haml = form_for @log_data_field, url: import_admin_tenant_site_unit_log_data_fields_url do |f|\n - if @log_data_field.errors.any?\n #error_explanation\n %ul\n - @log_data_field.errors.full_messages.each do |message|\n %li= message\n\n .input-field.m0\n = f.file_field :file, accept: \".csv\"\n -# = f.file_field :file\n %br\n %br\n %br\n\n .row\n .col.s5\n %button.btn.primary{type: 'submit', data: { disable_with: \"Please wait...\"}}\n Save\n method: :post"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74549139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17796286/"
] |
74,549,165
|
<p>I'm trying to dockerize a spring boot app but i'm having trouble building a jar file with maven.
I Already tried to follow <a href="https://stackoverflow.com/questions/27767264/how-to-dockerize-maven-project-and-how-many-ways-to-accomplish-it">this tutorial</a> but somehow my .jar isn't being updated by the 'mvn package' command inside the Dockerfile.</p>
<p>If I manually run 'mvn package' and then build the image, it works.</p>
<p>this is my dockerfile</p>
<pre><code>FROM openjdk:11
FROM maven:3.8-jdk-11 as maven_build
COPY pom.xml pom.xml
COPY src src
RUN mvn clean package
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java","-jar","/app.jar"]
</code></pre>
<p>my project structure</p>
<pre><code>Demo
└── src
| ├── main
| │ ├── java
| │ └── com
| │ └── App.java
| │
| │
| └── test
|
├──── Dockerfile
├──── pom.xml
</code></pre>
|
[
{
"answer_id": 74551436,
"author": "victor",
"author_id": 20583190,
"author_profile": "https://Stackoverflow.com/users/20583190",
"pm_score": 1,
"selected": true,
"text": "./mvnw spring-boot:build-image\n"
},
{
"answer_id": 74551601,
"author": "Ronak Jain",
"author_id": 2718939,
"author_profile": "https://Stackoverflow.com/users/2718939",
"pm_score": 1,
"selected": false,
"text": "COPY ${JAR_FILE} app.jar\n COPY --from=maven_build /path/to/target/*.jar /app.jar\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74549165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20583190/"
] |
74,549,175
|
<p>i'm trying to do a program that counts the sequence of binary numbers, let me give an example
the input is [0,0,0,1,1,0,0,0,1,1,1,1]
The output should be [0(the first number),3(number of 0 in sequence),2 (number of 1 in sequence),3,4]
the input size is infinite and it needs to be a list, so far what I have done is this:</p>
<pre><code>list([H|T],[X|Y]):-
T = [], X is H, Y is 1.
list([H|T],[X|Y]):-
T \= [], X is H,X1 is 1, contlist([H|T],[X1,Y]).
contlist([H|T],[X,_]):-
T \= [],
H =:= [T|_},
T1 i
contlist([H|T],[X,_]):-
X1 is X+1.
</code></pre>
<p>I don't know how to compare the head with the head of the tail and how to continue from there, maybe someone can help me?</p>
|
[
{
"answer_id": 74552065,
"author": "Nicholas Carey",
"author_id": 467473,
"author_profile": "https://Stackoverflow.com/users/467473",
"pm_score": 0,
"selected": false,
"text": "?- run_length_encoding( [a,b,b,c,c,c] , Rs ) .\n Rs = [ a:1, b:2, c:3 ]\n run_length_encoding( Xs, Ys ) :- nonvar(Xs), ! , rle_encode(Xs,Ys) .\nrun_length_encoding( Xs, Ys ) :- nonvar(Ys), rle_decode(Ys,Xs) .\n \nrle_encode( [] , [] ) .\nrle_encode( [X|Xs] , Rs ) :- rle_encode(Xs,X:1,Rs) .\n\nrle_encode( [X|Xs] , Y:N , [Y:N|Rs] ) :- X \\= Y , ! , rle_encode(Xs,X:1,Rs) .\nrle_encode( [X|Xs] , X:N , Rs ) :- M is N+1 , ! , rle_encode(Xs,X:M,Rs) .\nrle_encode( [] , X:N , [X:N] ) .\n\nrle_decode( [] , [] ) .\nrle_decode( [X:N|Xs] , [X|Ys] ) :- N > 0, !, M is N-1, rle_decode([X:M|Xs],Ys) .\nrle_decode( [_:0|Xs] , Ys ) :- rle_decode(Xs,Ys) .\n"
},
{
"answer_id": 74553594,
"author": "gusbro",
"author_id": 463243,
"author_profile": "https://Stackoverflow.com/users/463243",
"pm_score": 1,
"selected": false,
"text": "rle_binary([B|Seq], [B|BRLE]):-\n binary(B),\n rle_binary(Seq, B, 1, BRLE).\n \nrle_binary([], _, N, [N]).\nrle_binary([B|Seq], B, N, BRLE):-\n succ(N, N1),\n rle_binary(Seq, B, N1, BRLE).\nrle_binary([B1|Seq], B, N, [N|BRLE1]):-\n binary(B1),\n B \\= B1,\n rle_binary(Seq, B1, 1, BRLE1).\n\nbinary(0).\nbinary(1).\n ?- rle_binary( [0,0,0,1,1,0,0,0,1,1,1,1], BRLE).\nBRLE = [0, 3, 2, 3, 4] ;\nfalse.\n"
},
{
"answer_id": 74554214,
"author": "slago",
"author_id": 11535940,
"author_profile": "https://Stackoverflow.com/users/11535940",
"pm_score": 0,
"selected": false,
"text": "rle([X|Xs], [X|V]) :-\n clumped([X|Xs], P),\n pairs_values(P, V).\n ?- rle([0,0,0,1,1,0,0,0,1,1,1,1], L).\nL = [0, 3, 2, 3, 4].\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74549175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20488471/"
] |
74,549,196
|
<p>I have the following:</p>
<blockquote>
<pre><code> ID Value1 Value2 Code
0001 3.3 432 A
0001 0 654 A
0001 0 63 A
0002 0 78 B
0002 1 98 B
0003 0 22 C
0003 0 65 C
0003 0 91 C
</code></pre>
</blockquote>
<p>I need the following:</p>
<blockquote>
<pre><code> ID Value1 Value2 Code
0001 3.3 432 A
0001 0 0 A
0001 0 0 A
0002 0 0 B
0002 1 98 B
0003 0 22 C
0003 0 65 C
0003 0 91 C
</code></pre>
</blockquote>
<p>i.e., for the same "Code" if there is at least one row with Value1 !=0 then all the other rows referred to the same Code will be set to 0 (meaning that 654 and 63 for 0001 relative to Value2 will be set to 0). If this is not the case (like for 0003 nothing will be done).</p>
<p>Can anyone help me please?</p>
<p>Thank you in advance</p>
|
[
{
"answer_id": 74549351,
"author": "MrFlick",
"author_id": 2372064,
"author_profile": "https://Stackoverflow.com/users/2372064",
"pm_score": 0,
"selected": false,
"text": "if_else library(dplyr)\ndd %>% \n group_by(ID) %>% \n mutate(Value2=if_else(any(Value1!=0) & Value1==0, 0L, Value2))\n any()"
},
{
"answer_id": 74549357,
"author": "r2evans - GO NAVY BEAT ARMY",
"author_id": 3358272,
"author_profile": "https://Stackoverflow.com/users/3358272",
"pm_score": 3,
"selected": true,
"text": "library(dplyr)\nquux %>%\n group_by(Code) %>%\n mutate(Value2 = if_else(abs(Value1) > 0 | !any(abs(Value1) > 0), \n Value2, 0L)) %>%\n ungroup()\n# # A tibble: 8 x 4\n# ID Value1 Value2 Code \n# <int> <dbl> <int> <chr>\n# 1 1 3.3 432 A \n# 2 1 0 0 A \n# 3 1 0 0 A \n# 4 2 0 0 B \n# 5 2 1 98 B \n# 6 3 0 22 C \n# 7 3 0 65 C \n# 8 3 0 91 C \n quux |>\n transform(Value2 = ifelse(ave(abs(Value1), Code, FUN = function(v) abs(v) > 0 | !any(abs(v) > 0)), \n Value2, 0L))\n# ID Value1 Value2 Code\n# 1 1 3.3 432 A\n# 2 1 0.0 0 A\n# 3 1 0.0 0 A\n# 4 2 0.0 0 B\n# 5 2 1.0 98 B\n# 6 3 0.0 22 C\n# 7 3 0.0 65 C\n# 8 3 0.0 91 C\n library(data.table)\nas.data.table(quux)[, Value2 := fifelse(abs(Value1) > 0 | !any(abs(Value1) > 0), Value2, 0L), by = Code][]\n# ID Value1 Value2 Code\n# <int> <num> <int> <char>\n# 1: 1 3.3 432 A\n# 2: 1 0.0 0 A\n# 3: 1 0.0 0 A\n# 4: 2 0.0 0 B\n# 5: 2 1.0 98 B\n# 6: 3 0.0 22 C\n# 7: 3 0.0 65 C\n# 8: 3 0.0 91 C\n quux <- structure(list(ID = c(1L, 1L, 1L, 2L, 2L, 3L, 3L, 3L), Value1 = c(3.3, 0, 0, 0, 1, 0, 0, 0), Value2 = c(432L, 654L, 63L, 78L, 98L, 22L, 65L, 91L), Code = c(\"A\", \"A\", \"A\", \"B\", \"B\", \"C\", \"C\", \"C\")), class = \"data.frame\", row.names = c(NA, -8L))\n"
},
{
"answer_id": 74549358,
"author": "Juan C",
"author_id": 9462829,
"author_profile": "https://Stackoverflow.com/users/9462829",
"pm_score": 1,
"selected": false,
"text": "df %>% group_by(Code) %>% \nmutate(Value2 = if_else(row_number() == 1 & any(Value1 != 0), Value2, 0)) \n\n# A tibble: 8 × 4\n# Groups: Code [3]\n# ID Value1 Value2 Code \n# <int> <dbl> <dbl> <fct>\n# 1 1 3.3 432 A \n# 2 1 0 0 A \n# 3 1 0 0 A \n# 4 2 0 78 B \n# 5 2 1 0 B \n# 6 3 0 0 C \n# 7 3 0 0 C \n# 8 3 0 0 C \n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74549196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19938845/"
] |
74,549,273
|
<p>I'm trying to use min in a list that came from a .csv and some of the values are <em><strong>''</strong></em> how can I ignore those and also <em><strong>"0"</strong></em>?</p>
<p>I tried</p>
<pre><code>index1 = (life_expectancy.index(min(life_expectancy,)))
print(life_expectancy[index1])
</code></pre>
<p>and got nothing, when i tried:</p>
<pre><code>index1 = (life_expectancy.index(min(life_expectancy, key=int)))
</code></pre>
<p>I got:</p>
<blockquote>
<p>ValueError: invalid literal for int() with base 10: ''</p>
</blockquote>
<p>Because this is the value that the function treats at the min</p>
|
[
{
"answer_id": 74549441,
"author": "Stef",
"author_id": 3080723,
"author_profile": "https://Stackoverflow.com/users/3080723",
"pm_score": 2,
"selected": false,
"text": "min filter min int def int_or_zero(s):\n try:\n return int(s)\n except ValueError:\n return 0\n\ndef nonzero_min(seq):\n return min(filter(None, map(int_or_zero, seq)))\n\nprint( nonzero_min(['hello', '0', '12', '3', '0', '5', '']) )\n# 3\n for def nonzero_min2(seq):\n m = 9999999\n for x in seq:\n try:\n x = int(x)\n if x < m and x != 0:\n m = x\n except ValueError:\n pass\n return m\n\nprint( nonzero_min2(['hello', '0', '12', '3', '0', '5', '']) )\n# 3\n"
},
{
"answer_id": 74549486,
"author": "Hunter",
"author_id": 15076691,
"author_profile": "https://Stackoverflow.com/users/15076691",
"pm_score": -1,
"selected": true,
"text": "new_life_expectancy = [value for value in life_expectancy if value != '' and value != '0']\n '' 0"
},
{
"answer_id": 74549587,
"author": "Ammar_Asim_23",
"author_id": 18134093,
"author_profile": "https://Stackoverflow.com/users/18134093",
"pm_score": -1,
"selected": false,
"text": "#You can simply remove all 0 terms and string terms from your list and then use min\nl=[1,34,6,4,1,4,0]\nl1=l\nwhile True:\n try:\n l1.remove(0)\n except ValueError:\n break \nprint(min(l1)) \n"
},
{
"answer_id": 74549727,
"author": "LoneWanderer",
"author_id": 7237062,
"author_profile": "https://Stackoverflow.com/users/7237062",
"pm_score": 1,
"selected": false,
"text": "life_expectancy= [2,3,5,7,11,13, \"\", 0, \"\", 3.14, 1.414, \"\", 1.712, \"\", 1.618, 0]\nindex1 = (life_expectancy.index(min(life_expectancy,)))\nTypeError: '<' not supported between instances of 'str' and 'int'\n\nindex1 = (life_expectancy.index(min(life_expectancy,key=int)))\nValueError: invalid literal for int() with base 10: ''\n life_expectancy= [2,3,5,7,11,13, None, 0, None, 3.14, 1.414, None, 1.712, None, 1.618, 0]\nindex1 = (life_expectancy.index(min(life_expectancy,)))\nTypeError: '<' not supported between instances of 'NoneType' and 'int'\n\nindex1 = (life_expectancy.index(min(life_expectancy,key=int)))\nTypeError: int() argument must be a string, a bytes-like object or a real number, not 'NoneType'\n life_expectancy= [2,3,5,7,11,13, \"\", \"0\", \"\", \"3.14\", 1.414, \"\", 1.712, \"\", 1.618, 0]\nnew_list = [e for e in life_expectancy if e and type(e) != str]\nnew_list\n>>> [2, 3, 5, 7, 11, 13, 1.414, 1.712, 1.618]\n"
},
{
"answer_id": 74551669,
"author": "Dava",
"author_id": 16376445,
"author_profile": "https://Stackoverflow.com/users/16376445",
"pm_score": 0,
"selected": false,
"text": "df_temp = df.loc[df[\"column_name\"]!=\"\"]\n\ndf_temp = df_temp.loc[df_temp[\"column_name\"]>0]\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74549273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20583292/"
] |
74,549,279
|
<p>I am using popovers as part of an input validation process. I have the idea but I can't work out the syntax on how to get this to work.</p>
<p><a href="https://jsbin.com/sufitelodo/1/edit?html,js,output" rel="nofollow noreferrer">https://jsbin.com/sufitelodo/1/edit?html,js,output</a></p>
<p>This JSBin is the basis of it.</p>
<p>I don't know how to write the HTML for a hidden Bootstrap 5.2 popover that comes up only when called in an <code>if</code> statement. To run this, type the number 0 into input A and any number into input B and the same number again into input C. The first error should be that input A = 0 and then you change that to any non-zero and then the second error should happen when you try and submit. I would like to change from the alert boxes to popovers.</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 popoverTriggerList = [].slice.call(
document.querySelectorAll('[data-bs-toggle="popover"]')
);
const popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
return new bootstrap.Popover(popoverTriggerEl, { html: true });
});
document.getElementById("button").addEventListener("click", testMe);
function testMe() {
let inputA = parseFloat(document.getElementById("aInput").value);
let inputB = parseFloat(document.getElementById("bInput").value);
let inputC = parseFloat(document.getElementById("cInput").value);
let popoverTest1 = document.getElementById("popoverTest1");
let popoverTest2 = document.getElementById("popoverTest2");
if (inputA === 0) {
// Make popoverTest1 come up here
//alert("This is when popoverTest1 should fire");
bootstrap.Popover.getOrCreateInstance('#popoverTest1').show()
return false;
} else if (inputB === inputC) {
// Make popoverTest2 come up here
//alert("This is when popoverTest2 should fire");
bootstrap.Popover.getOrCreateInstance('#popoverTest2').show()
return false;
}
}
document.getElementById("close1").addEventListener("click", closePop);
function closePop () {
bootstrap.Popover.getInstance('#popoverTest1').hide();
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<label for="aInput">A Input</label>
<input type="number" id="aInput">
<span id="popoverTest1"
data-bs-container="body"
data-bs-toggle="popover"
data-bs-trigger="manual"
data-bs-content="Top popover"
data-bs-title='This is zero <a href="" id="close1">x</a>'
data-bs-content='Change it to something non-zero'>
</span>
<br><br>
<label for="bInput">B Input</label>
<input type="number" id="bInput">
<span id="popoverTest2"
data-bs-container="body"
data-bs-toggle="popover"
data-bs-trigger="manual"
data-bs-content="Top popover"
data-bs-title="This is the same as Input C"
data-bs-content="Change it so it's not the same as Input C">
</span>
<br> <br>
<label for="cInput">C Input</label>
<input type="number" id="cInput">
<button type="button" class="btn btn-warning" id="button">Hit Me</button>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script></code></pre>
</div>
</div>
</p>
<p>So, instead of the alerts I would like a cleaner popover from Bootstrap, but the syntax and getting them to work (even after trying to decipher the documentation) isn't on my side. Then after the popover is opened it needs to be able to be closed again.</p>
<p>I tried <code>data-bs-trigger="focus"</code> but this does not seem to have enabled closing.</p>
<p>Thanks kindly for your help on this.</p>
<p>*** Edit - I have updated the code to allow for just using Vanilla but there is an error with using the close button... I can't seem to dispose of the popover.</p>
|
[
{
"answer_id": 74549441,
"author": "Stef",
"author_id": 3080723,
"author_profile": "https://Stackoverflow.com/users/3080723",
"pm_score": 2,
"selected": false,
"text": "min filter min int def int_or_zero(s):\n try:\n return int(s)\n except ValueError:\n return 0\n\ndef nonzero_min(seq):\n return min(filter(None, map(int_or_zero, seq)))\n\nprint( nonzero_min(['hello', '0', '12', '3', '0', '5', '']) )\n# 3\n for def nonzero_min2(seq):\n m = 9999999\n for x in seq:\n try:\n x = int(x)\n if x < m and x != 0:\n m = x\n except ValueError:\n pass\n return m\n\nprint( nonzero_min2(['hello', '0', '12', '3', '0', '5', '']) )\n# 3\n"
},
{
"answer_id": 74549486,
"author": "Hunter",
"author_id": 15076691,
"author_profile": "https://Stackoverflow.com/users/15076691",
"pm_score": -1,
"selected": true,
"text": "new_life_expectancy = [value for value in life_expectancy if value != '' and value != '0']\n '' 0"
},
{
"answer_id": 74549587,
"author": "Ammar_Asim_23",
"author_id": 18134093,
"author_profile": "https://Stackoverflow.com/users/18134093",
"pm_score": -1,
"selected": false,
"text": "#You can simply remove all 0 terms and string terms from your list and then use min\nl=[1,34,6,4,1,4,0]\nl1=l\nwhile True:\n try:\n l1.remove(0)\n except ValueError:\n break \nprint(min(l1)) \n"
},
{
"answer_id": 74549727,
"author": "LoneWanderer",
"author_id": 7237062,
"author_profile": "https://Stackoverflow.com/users/7237062",
"pm_score": 1,
"selected": false,
"text": "life_expectancy= [2,3,5,7,11,13, \"\", 0, \"\", 3.14, 1.414, \"\", 1.712, \"\", 1.618, 0]\nindex1 = (life_expectancy.index(min(life_expectancy,)))\nTypeError: '<' not supported between instances of 'str' and 'int'\n\nindex1 = (life_expectancy.index(min(life_expectancy,key=int)))\nValueError: invalid literal for int() with base 10: ''\n life_expectancy= [2,3,5,7,11,13, None, 0, None, 3.14, 1.414, None, 1.712, None, 1.618, 0]\nindex1 = (life_expectancy.index(min(life_expectancy,)))\nTypeError: '<' not supported between instances of 'NoneType' and 'int'\n\nindex1 = (life_expectancy.index(min(life_expectancy,key=int)))\nTypeError: int() argument must be a string, a bytes-like object or a real number, not 'NoneType'\n life_expectancy= [2,3,5,7,11,13, \"\", \"0\", \"\", \"3.14\", 1.414, \"\", 1.712, \"\", 1.618, 0]\nnew_list = [e for e in life_expectancy if e and type(e) != str]\nnew_list\n>>> [2, 3, 5, 7, 11, 13, 1.414, 1.712, 1.618]\n"
},
{
"answer_id": 74551669,
"author": "Dava",
"author_id": 16376445,
"author_profile": "https://Stackoverflow.com/users/16376445",
"pm_score": 0,
"selected": false,
"text": "df_temp = df.loc[df[\"column_name\"]!=\"\"]\n\ndf_temp = df_temp.loc[df_temp[\"column_name\"]>0]\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74549279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13062685/"
] |
74,549,322
|
<p>I'm using ms sql server.
I have a simple table with a parent child relationship, like
Parent, Child</p>
<p>Now I need a query which delivers every Element with itself, all its successors and successors of them an so on.
Example</p>
<pre><code>Parent Child
------ -----
A A1
A1 A11
A A2
A2 A21
A21 A211
</code></pre>
<p>Now the result should look like:</p>
<pre><code>Root Successor
------ ---------
A A
A A1
A A11
A A2
A A21
A A211
A1 A1
A1 A11
A11 A11
A2 A2
A2 A21
A2 A211
A21 A21
A21 A211
A211 A211
</code></pre>
<p>Any idea to do it recursivly on MS SQL Server with a sql query?</p>
<p>I searched for the internet and found some solutions, but not for my problem. I never got a list with the root and all its successor, only parent child for one level.</p>
|
[
{
"answer_id": 74549745,
"author": "Nenad Zivkovic",
"author_id": 612181,
"author_profile": "https://Stackoverflow.com/users/612181",
"pm_score": 2,
"selected": true,
"text": "WITH CTE_AllRoots AS \n(\n SELECT Parent as Root FROM Table1\n UNION \n SELECT Child FROM Table1\n)\n, RCTE AS \n(\n SELECT Root, Root AS Successor FROM CTE_AllRoots\n UNION ALL\n SELECT r.Root, t.Child\n FROM RCTE r\n INNER JOIN Table1 t ON t.Parent = r.Successor\n)\nSELECT * \nFROM RCTE\nORDER BY Root, Successor\n"
},
{
"answer_id": 74549913,
"author": "Jonas Metzler",
"author_id": 18794826,
"author_profile": "https://Stackoverflow.com/users/18794826",
"pm_score": 0,
"selected": false,
"text": "CROSS JOIN SELECT\ny1.parent AS Root, y2.child AS Successor\nFROM \nyourtable AS y1 \nCROSS JOIN \nyourtable AS y2\nWHERE y2.child LIKE y1.parent + '%'\nUNION\nSELECT parent, parent FROM yourtable\nUNION\nSELECT child, child FROM yourtable\nORDER BY Root, Successor;\n LIKE WHERE CTE"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74549322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10364464/"
] |
74,549,328
|
<p>Suppose I have an array with <code>302</code> elements. I want to split the array into <code>n = 6</code> groups (roughly equal size), such that it looks like the following. The following code works when <code>n = 6</code>. However, if <code>n</code> is <code>51</code> groups, then it failed and generated <code>60</code> groups. How can I get this right ?</p>
<pre class="lang-py prettyprint-override"><code>n = 6
group_num = np.arange(302) // (302 // n)
group_num[group_num == n] = n - 1
array([
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5],
dtype=int32
)
</code></pre>
|
[
{
"answer_id": 74549646,
"author": "Mauro Vanetti",
"author_id": 581285,
"author_profile": "https://Stackoverflow.com/users/581285",
"pm_score": 0,
"selected": false,
"text": "302 // n import numpy\n\nn = 51\ngroup_num = numpy.arange(302) // (302 / n)\ngroup_num[group_num == n] = n-1\nprint(group_num)\n"
},
{
"answer_id": 74549716,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 3,
"selected": true,
"text": "numpy.linspace n = 51\nnp.linspace(0, n, num=302, endpoint=False).astype(int)\n array([ 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2,\n 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5,\n 5, 5, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8,\n 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 11, 11,\n 11, 11, 11, 11, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 14, 14,\n 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 17,\n 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19,\n 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22,\n 22, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25,\n 25, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28,\n 28, 28, 29, 29, 29, 29, 29, 29, 30, 30, 30, 30, 30, 30, 31, 31, 31,\n 31, 31, 31, 32, 32, 32, 32, 32, 32, 33, 33, 33, 33, 33, 33, 34, 34,\n 34, 34, 34, 34, 35, 35, 35, 35, 35, 35, 36, 36, 36, 36, 36, 36, 37,\n 37, 37, 37, 37, 37, 38, 38, 38, 38, 38, 39, 39, 39, 39, 39, 39, 40,\n 40, 40, 40, 40, 40, 41, 41, 41, 41, 41, 41, 42, 42, 42, 42, 42, 42,\n 43, 43, 43, 43, 43, 43, 44, 44, 44, 44, 44, 44, 45, 45, 45, 45, 45,\n 45, 46, 46, 46, 46, 46, 46, 47, 47, 47, 47, 47, 47, 48, 48, 48, 48,\n 48, 48, 49, 49, 49, 49, 49, 49, 50, 50, 50, 50, 50])\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74549328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1769197/"
] |
74,549,345
|
<p>I've got some strings like:</p>
<pre><code>Cola12018
ColaKKK112018
Cola-22018
</code></pre>
<p>And I need retrieve just Cola from them and delete everything after in order to use further.</p>
<p>I tried</p>
<p>$cola = 'Cola.*'</p>
<p>What did I miss?</p>
<p>The main thing - I want to check that the word begins with "Cola"</p>
|
[
{
"answer_id": 74549646,
"author": "Mauro Vanetti",
"author_id": 581285,
"author_profile": "https://Stackoverflow.com/users/581285",
"pm_score": 0,
"selected": false,
"text": "302 // n import numpy\n\nn = 51\ngroup_num = numpy.arange(302) // (302 / n)\ngroup_num[group_num == n] = n-1\nprint(group_num)\n"
},
{
"answer_id": 74549716,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 3,
"selected": true,
"text": "numpy.linspace n = 51\nnp.linspace(0, n, num=302, endpoint=False).astype(int)\n array([ 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2,\n 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5,\n 5, 5, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8,\n 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 11, 11,\n 11, 11, 11, 11, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 14, 14,\n 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 17,\n 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19,\n 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22,\n 22, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25,\n 25, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28,\n 28, 28, 29, 29, 29, 29, 29, 29, 30, 30, 30, 30, 30, 30, 31, 31, 31,\n 31, 31, 31, 32, 32, 32, 32, 32, 32, 33, 33, 33, 33, 33, 33, 34, 34,\n 34, 34, 34, 34, 35, 35, 35, 35, 35, 35, 36, 36, 36, 36, 36, 36, 37,\n 37, 37, 37, 37, 37, 38, 38, 38, 38, 38, 39, 39, 39, 39, 39, 39, 40,\n 40, 40, 40, 40, 40, 41, 41, 41, 41, 41, 41, 42, 42, 42, 42, 42, 42,\n 43, 43, 43, 43, 43, 43, 44, 44, 44, 44, 44, 44, 45, 45, 45, 45, 45,\n 45, 46, 46, 46, 46, 46, 46, 47, 47, 47, 47, 47, 47, 48, 48, 48, 48,\n 48, 48, 49, 49, 49, 49, 49, 49, 50, 50, 50, 50, 50])\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74549345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18644650/"
] |
74,549,349
|
<p>Using invalid HTML I get the look I want, but using valid HTML I don't. Is there CSS that will allow me to configure the <FIGURE> or <FIGCAPTION> to emulate what the <SPAN> is doing?</p>
<p>The way I want it to look is on the left, the valid HTML is on the right.</p>
<p>Invalid HTML:</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 {
margin: auto;
padding: 0 5px 0 5px;
font-family: Tahoma, Verdana, sans-serif;
font-size: 12pt;
background-color: black;
color: white;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><UL>
<SPAN style="font-weight: bold; text-decoration: underline; color: lemonchiffon">Color Code Guide</SPAN>
<LI>
<SPAN style="color: DarkCyan">comment</SPAN>
</LI>
<LI>
<SPAN style="color: Coral">processor directive</SPAN>
</LI>
<LI>
<SPAN style="color: HotPink">#ifndef name</SPAN>
</LI>
<LI>
<SPAN style="color: PaleTurquoise">library include</SPAN>
</LI>
<LI>
<SPAN style="color: DarkSalmon">user-defined include</SPAN>
</LI>
<LI>
<SPAN style="color: Gold">library function</SPAN>
</LI>
<LI>
<SPAN style="color: DarkKhaki">initializer function</SPAN>
</LI>
<LI>user-defined function</LI>
<LI>
<SPAN style="color: DodgerBlue">keyword</SPAN>
</LI>
<LI>
<SPAN style="color: Red">important symbol</SPAN>
</LI>
</UL></code></pre>
</div>
</div>
</p>
<p>Valid HTML:</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 {
margin: auto;
padding: 0 5px 0 5px;
font-family: Tahoma, Verdana, sans-serif;
font-size: 12pt;
background-color: black;
color: white;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><FIGURE>
<FIGCAPTION>
<SPAN style="font-weight: bold; text-decoration: underline; color: lemonchiffon">Color Code Guide</SPAN>
</FIGCAPTION>
<UL>
<LI>
<SPAN style="color: DarkCyan">comment</SPAN>
</LI>
<LI>
<SPAN style="color: Coral">processor directive</SPAN>
</LI>
<LI>
<SPAN style="color: HotPink">#ifndef name</SPAN>
</LI>
<LI>
<SPAN style="color: PaleTurquoise">library include</SPAN>
</LI>
<LI>
<SPAN style="color: DarkSalmon">user-defined include</SPAN>
</LI>
<LI>
<SPAN style="color: Gold">library function</SPAN>
</LI>
<LI>
<SPAN style="color: DarkKhaki">initializer function</SPAN>
</LI>
<LI>user-defined function</LI>
<LI>
<SPAN style="color: DodgerBlue">keyword</SPAN>
</LI>
<LI>
<SPAN style="color: Red">important symbol</SPAN>
</LI>
</UL>
</FIGURE></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74549646,
"author": "Mauro Vanetti",
"author_id": 581285,
"author_profile": "https://Stackoverflow.com/users/581285",
"pm_score": 0,
"selected": false,
"text": "302 // n import numpy\n\nn = 51\ngroup_num = numpy.arange(302) // (302 / n)\ngroup_num[group_num == n] = n-1\nprint(group_num)\n"
},
{
"answer_id": 74549716,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 3,
"selected": true,
"text": "numpy.linspace n = 51\nnp.linspace(0, n, num=302, endpoint=False).astype(int)\n array([ 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2,\n 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5,\n 5, 5, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8,\n 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 11, 11,\n 11, 11, 11, 11, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 14, 14,\n 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 17,\n 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19,\n 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22,\n 22, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25,\n 25, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28,\n 28, 28, 29, 29, 29, 29, 29, 29, 30, 30, 30, 30, 30, 30, 31, 31, 31,\n 31, 31, 31, 32, 32, 32, 32, 32, 32, 33, 33, 33, 33, 33, 33, 34, 34,\n 34, 34, 34, 34, 35, 35, 35, 35, 35, 35, 36, 36, 36, 36, 36, 36, 37,\n 37, 37, 37, 37, 37, 38, 38, 38, 38, 38, 39, 39, 39, 39, 39, 39, 40,\n 40, 40, 40, 40, 40, 41, 41, 41, 41, 41, 41, 42, 42, 42, 42, 42, 42,\n 43, 43, 43, 43, 43, 43, 44, 44, 44, 44, 44, 44, 45, 45, 45, 45, 45,\n 45, 46, 46, 46, 46, 46, 46, 47, 47, 47, 47, 47, 47, 48, 48, 48, 48,\n 48, 48, 49, 49, 49, 49, 49, 49, 50, 50, 50, 50, 50])\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74549349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5332013/"
] |
74,549,356
|
<p>I am trying to share the Mongo connection with other modules in my Node.js project. I keep getting either <code>undefined</code> or <code>is not a function</code> when attempting to use the exported client. I also had a question around detecting if the connection is in fact open before performing operations on the database.</p>
<p>It seems like using the <code>app.locals</code> would be the proper way to share the connection but I could not get that working either. Below is what I have at the moment. I've tried this many ways. Most of what I can find online seems to export the Mongo Node driver's method, not the connection itself. The idea is to connect once and never disconnect until the app shuts down.</p>
<pre><code>const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
async function connect () {
app.locals.dbConnected = false;
try {
await client.connect();
app.locals.dbConnected = true;
module.exports = client;
} catch (e) {
console.error(e);
}
};
</code></pre>
<p>then in another module do something like:</p>
<pre><code>await client.db('syslogs').collection('production').insertOne(doc);
</code></pre>
<p>Is it possible to share the <em>connection</em>?</p>
|
[
{
"answer_id": 74550076,
"author": "thecodeparadox",
"author_id": 690854,
"author_profile": "https://Stackoverflow.com/users/690854",
"pm_score": 1,
"selected": false,
"text": "const client = new MongoClient(uri, {\n useNewUrlParser: true,\n useUnifiedTopology: true,\n});\n\nlet __inst = null;\n\nexport default new Promise((resolve, reject) => {\n if (__inst !== null) resolve(__inst);\n\n // the open event is the key here\n // like this we can handle error, close etc thru events as well\n client.open((err, mongoInst) => {\n if (err) reject(err);\n __inst = mongoInst;\n resolve(__inst);\n });\n});\n"
},
{
"answer_id": 74550673,
"author": "Ronnie Royston",
"author_id": 4797603,
"author_profile": "https://Stackoverflow.com/users/4797603",
"pm_score": 0,
"selected": false,
"text": "app.locals const { MongoClient } = require(\"mongodb\");\nconst client = new MongoClient(uri, {\n useNewUrlParser: true,\n useUnifiedTopology: true,\n});\n(async () => {\n app.locals.dbConnected = false;\n try {\n await client.connect();\n console.log(\"Connected to DB\");\n app.locals.client = client;\n app.listen(PORT, HOST, () => {\n console.log(`Running on http://${HOST}:${PORT}`);\n });\n } catch (e) {\n console.error(e);\n }\n})();\n async function index (req, res) {\n try {\n let db = req.app.locals.client.db(\"admin\");\n await db.command({ ping: 1 });\n console.log(\"pinged admin database\");\n }catch(err) {\n console.log(err);\n }\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74549356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4797603/"
] |
74,549,395
|
<p>I'm trying to create a simple flutter UI that is similar to the layout below. How would I create this without using any other libs/packages? All of the examples I've seen are using massive libraries. Looking for some small example of how to achieve this.</p>
<p>Example using a package: <a href="https://pub.dev/packages/timelines" rel="nofollow noreferrer">https://pub.dev/packages/timelines</a></p>
<p><a href="https://i.stack.imgur.com/popbJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/popbJ.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74549520,
"author": "Petro",
"author_id": 2163927,
"author_profile": "https://Stackoverflow.com/users/2163927",
"pm_score": 0,
"selected": false,
"text": " Timeline(children: [\n const RightChild(\n asset: 'assets/delivery/order_placed.png',\n title: 'Order Placed',\n message: 'We have received your order.',\n ),\n const RightChild(\n asset: 'assets/delivery/order_confirmed.png',\n title: 'Order Confirmed',\n message: 'Your order has been confirmed.',\n ),\n const RightChild(\n asset: 'assets/delivery/order_processed.png',\n title: 'Order Processed',\n message: 'We are preparing your order.',\n ),\n const RightChild(\n disabled: false,\n asset: 'assets/delivery/ready_to_pickup.png',\n title: 'Ready to Pickup',\n message: 'Your order is ready for pickup.',\n ),\n ],),\n\n\nclass RightChild extends StatelessWidget {\n const RightChild({\n Key? key,\n required this.asset,\n required this.title,\n required this.message,\n this.disabled = false,\n }) : super(key: key);\n\n final String asset;\n final String title;\n final String message;\n final bool disabled;\n\n @override\n Widget build(BuildContext context) {\n return Padding(\n padding: const EdgeInsets.all(16.0),\n child: Row(\n children: <Widget>[\n Opacity(\n child: Image.asset(asset, height: 50),\n opacity: disabled ? 0.5 : 1,\n ),\n const SizedBox(width: 16),\n Column(\n crossAxisAlignment: CrossAxisAlignment.start,\n mainAxisSize: MainAxisSize.min,\n children: <Widget>[\n Text(\n title,\n style: GoogleFonts.yantramanav(\n color: disabled\n ? const Color(0xFFBABABA)\n : const Color(0xFF636564),\n fontSize: 18,\n fontWeight: FontWeight.w500,\n ),\n ),\n const SizedBox(height: 6),\n Text(\n message,\n style: GoogleFonts.yantramanav(\n color: disabled\n ? const Color(0xFFD5D5D5)\n : const Color(0xFF636564),\n fontSize: 16,\n ),\n ),\n ],\n ),\n ],\n ),\n );\n }\n}\n"
},
{
"answer_id": 74549707,
"author": "BLKKKBVSIK",
"author_id": 11550065,
"author_profile": "https://Stackoverflow.com/users/11550065",
"pm_score": 2,
"selected": false,
"text": "Stepper Stepper(\n currentStep: _index,\n onStepCancel: () {\n if (_index > 0) {\n setState(() {\n _index -= 1;\n });\n }\n },\n onStepContinue: () {\n if (_index <= 0) {\n setState(() {\n _index += 1;\n });\n }\n },\n onStepTapped: (int index) {\n setState(() {\n _index = index;\n });\n },\n steps: <Step>[\n Step(\n title: const Text('Step 1 title'),\n content: Container(\n alignment: Alignment.centerLeft,\n child: const Text('Content for Step 1')),\n ),\n const Step(\n title: Text('Step 2 title'),\n content: Text('Content for Step 2'),\n ),\n ],\n );\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74549395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2163927/"
] |
74,549,414
|
<p>Trying to generate a BPMN diagram, even a basic one with start event, end event and some user tasks. Is there any Java libraries or API's available that would help me achieve this.
Have searched around a lot but could not find any suitable.
Any help would be appreciated</p>
|
[
{
"answer_id": 74567634,
"author": "rob2universe",
"author_id": 1491439,
"author_profile": "https://Stackoverflow.com/users/1491439",
"pm_score": 2,
"selected": true,
"text": " public static void main(String[] args) {\n\n BpmnModelInstance modelInst;\n try {\n // File file = new File(ModelModifier.class.getClassLoader().getResource(\"process1.bpmn\").toURI());\n File file = new File(\"./src/main/resources/process1.bpmn\");\n // modelInst = Bpmn.readModelFromFile(file);\n modelInst = Bpmn.createProcess()\n .name(\"Twitter QA\")\n .executable()\n .startEvent()\n .userTask().id(\"ApproveTweet\").name(\"Approve Tweet\")\n .exclusiveGateway().id(\"isApproved\").name(\"Approved?\")\n .condition(\"approved\", \"#{approved}\")\n .serviceTask().id(\"sendTweet\").name(\"Send tweet\")\n .endEvent().name(\"Tweet sent\")\n .moveToLastGateway()\n // done();\n // Gateway gateway = modelInst.getModelElementById(\"isApproved\");\n // gateway.builder()\n .condition(\"Not approved\", \"#{!approved}\")\n .serviceTask().name(\"Send Rejection\")\n .endEvent().name(\"Tweet rejected\").done();\n\n log.info(\"Flow Elements - Name : Id : Type Name\");\n modelInst.getModelElementsByType(UserTask.class).forEach(e -> log.info(\"{} : {} : {}\", e.getName(), e.getId(), e.getElementType().getTypeName()));\n\n Bpmn.writeModelToFile(file, modelInst);\n// file.createNewFile(\"/tmp/testDiagram2.bpmn\")\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74549414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14859042/"
] |
74,549,427
|
<p>When I render an array of objects and try to render component inside map function is gives me this error:
Uncaught TypeError: (intermediate value)(intermediate value)(intermediate value).map is not a function
The problem occurs here:</p>
<pre><code>{comments.map((obj, i) => (
<CommentsBlock
key={i}
items={{
user: {
fullName: obj?.user?.fullName,
avatarUrl: obj?.user?.avatarUrl,
},
text: obj?.text,
}}
isLoading={false}
id={obj._id}
isEditable={userData._id == obj.user._id}
><Index /></CommentsBlock>
))}
</code></pre>
<p>CommentBlock component:</p>
<pre><code>export const CommentsBlock = ({
id,
items,
children,
isLoading = true,
isEditable = false,
}) => {
const dispatch = useDispatch();
const onClickRemove = () => {
if (window.confirm("Вы действительно хотите удалить статью?")) {
//dispatch(fetchRemovePosts(id));
}
};
return (
<SideBlock title="Комментарии">
<List>
{(isLoading ? [...Array(5)] : items).map((obj, index) => (
<React.Fragment key={index}>
<ListItem alignItems="flex-start">
<ListItemAvatar>
{isLoading ? (
<Skeleton variant="circular" width={40} height={40} />
) : (
<Avatar alt={obj.user.fullName} src={obj.user.avatarUrl} />
)}
</ListItemAvatar>
{isLoading ? (
<div style={{ display: "flex", flexDirection: "column" }}>
<Skeleton variant="text" height={25} width={120} />
<Skeleton variant="text" height={18} width={230} />
</div>
) : (
<ListItemText
primary={
<Typography
style={{
display: "flex",
justifyContent: "space-between",
}}
>
{obj.user.fullName}
{isEditable ? (
<IconButton color="secondary" style={{ padding: 0 }}>
<DeleteIcon />
</IconButton>
) : (
""
)}
</Typography>
}
secondary={obj.text}
/>
)}
</ListItem>
<Divider variant="inset" component="li" />
</React.Fragment>
))}
</List>
{children}
</SideBlock>
);
};
</code></pre>
<p>array comment comes from here</p>
<pre><code>const comments = useSelector((state) => state.comment.data);
</code></pre>
<p><a href="https://i.stack.imgur.com/AOpFB.png" rel="nofollow noreferrer">that's how comments looks like</a></p>
<p>So i expect to render these elements</p>
|
[
{
"answer_id": 74549551,
"author": "Tigran Petrosyan",
"author_id": 10422933,
"author_profile": "https://Stackoverflow.com/users/10422933",
"pm_score": 1,
"selected": false,
"text": "(isLoading ? [...Array(5)] : items).map((obj, index) \n [undefined, undefined, undefined, undefined, undefined]\n"
},
{
"answer_id": 74549591,
"author": "thecodeparadox",
"author_id": 690854,
"author_profile": "https://Stackoverflow.com/users/690854",
"pm_score": 1,
"selected": true,
"text": "items CommentsBlock List {(isLoading ? [...Array(5)] : items).map((obj, index) => ( items [...Array(5)] undefined items"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74549427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20583316/"
] |
74,549,436
|
<p>I'm migrating a Java Spring application to Spring Boot. I've transferred the application-context.xml configuration inside Java beans. However, when I try to launch the Spring Boot app, I get the following error:</p>
<blockquote>
<p>java.lang.NoSuchMethodError:
com.zaxxer.hikari.HikariDataSource.getMetricsTrackerFactory()Lcom/zaxxer/hikari/metrics/MetricsTrackerFactory;</p>
</blockquote>
<p>It seems like there is something wrong with my configuration or the library version I'm using, but so far I've no clue. I'm using Spring Boot 2.5.6 and HikariCP 2.5.1.</p>
<p>Here is my data source configuration:</p>
<pre><code>@Primary
@Bean(destroyMethod = "close")
DataSource dataSource(DatasourceProperties datasourceProperties) {
return DataSourceBuilder.create()
.type(HikariDataSource.class)
.driverClassName(datasourceProperties.getDriverClassName())
.url(datasourceProperties.getUrl())
.username(datasourceProperties.getUsername())
.password(datasourceProperties.getPassword())
.build();
}
</code></pre>
<p>I can provide more configuration and info if needed.</p>
|
[
{
"answer_id": 74562162,
"author": "TCH",
"author_id": 5611906,
"author_profile": "https://Stackoverflow.com/users/5611906",
"pm_score": 1,
"selected": true,
"text": "<dependency>\n <groupId>org.quartz-scheduler</groupId>\n <artifactId>quartz</artifactId>\n <version>${quartz.version}</version>\n <exclusions>\n <exclusion>\n <groupId>com.zaxxer</groupId>\n <artifactId>HikariCP-java7</artifactId>\n </exclusion>\n </exclusions>\n</dependency>\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74549436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5611906/"
] |
74,549,450
|
<pre class="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">
<title>Add Multiple Choice Question</title>
<link rel="stylesheet" href="./multiple.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css">
<script src="./multiple.js"></script>
</head>
<body>
<script src="./multiple.js"></script>
<div class="multiple">
<div class="question">
<label id="question-label" for="question">Question</label>
<textarea name="question-area" id="qarea" cols="38" rows="5"></textarea>
</div>
<div class="answer">
<label class="answer-label" for="answer">Choice-1 </label>
<input class="answer-inp" type="text">
<i class="fa-solid fa-circle-plus fa-xl" id="icon-add" onclick="add_more_field()"></i>
</div>
<!-- <div class="icon"></div>-->
</div>
</body>
</html>
</code></pre>
<pre class="lang-js prettyprint-override"><code>function add_more_field(){
html = '<div class="answer">\
<label class="answer-label" for="answer">Choice-1 </label>\
<input class="answer-inp" type="text">\
<i class="fa-solid fa-circle-plus fa-xl" id="icon-add" onclick="add_more_field()"></i>\
</div>'
var add = document.getElementsByClassName("multiple");
add.appendChild(html);
}
</code></pre>
<p>I want to write a javascript code that creates the same answer div when the user presses the + icon again. This will be the answers to a multiple choice question and the number of answers needs to be increased dynamically. I wrote the function, but it does not create a new answer div when I click on the icon. How can I do that?</p>
|
[
{
"answer_id": 74549564,
"author": "jerry",
"author_id": 20493210,
"author_profile": "https://Stackoverflow.com/users/20493210",
"pm_score": 2,
"selected": true,
"text": " let html =\n '<div class=\"answer\">\\\n <label class=\"answer-label\" for=\"answer\">Choice-1 </label>\\\n <input class=\"answer-inp\" type=\"text\">\\\n <i class=\"fa-solid fa-circle-plus fa-xl\" id=\"icon-add\" onclick=\"add_more_field()\"></i>\\\n </div>';\n\n function add_more_field() {\n var add = document.querySelector(\".multiple\");\n add.innerHTML += html;\n } <!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>Add Multiple Choice Question</title>\n\n <link\n rel=\"stylesheet\"\n href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css\"\n />\n </head>\n <body>\n <div class=\"multiple\">\n <div class=\"question\">\n <label id=\"question-label\" for=\"question\">Question</label>\n <textarea name=\"question-area\" id=\"qarea\" cols=\"38\" rows=\"5\"></textarea>\n </div>\n <div class=\"answer\">\n <label class=\"answer-label\" for=\"answer\">Choice-1 </label>\n <input class=\"answer-inp\" type=\"text\" />\n <i\n class=\"fa-solid fa-circle-plus fa-xl\"\n id=\"icon-add\"\n onclick=\"add_more_field()\"\n ></i>\n </div>\n\n <!-- <div class=\"icon\"></div>-->\n </div>\n\n </body>\n</html>"
},
{
"answer_id": 74549608,
"author": "Diego D",
"author_id": 1221208,
"author_profile": "https://Stackoverflow.com/users/1221208",
"pm_score": 1,
"selected": false,
"text": "appendChild() innerHTML let choiceNumber = 1;\n\nfunction addNewField(passedLabel) {\n\n choiceNumber++;\n if(passedLabel === undefined)\n choiceLabel = `Choice-${choiceNumber}`;\n else\n choiceLabel = passedLabel;\n\n html = `\n <div class=\"answer\">\n <label class=\"answer-label\" for=\"answer\">${choiceLabel}</label>\n <input class=\"answer-inp\" type=\"text\">\\\n <i class=\"fa-solid fa-circle-plus fa-xl\" id=\"icon-add\" onclick=\"add_more_field()\"></i>\n </div>`;\n\n var add = document.getElementById(\"multiple\");\n add.innerHTML += html;\n} <body>\n\n <div id=\"multiple\">\n\n <div class=\"question\">\n <label id=\"question-label\" for=\"question\">Question</label>\n <textarea name=\"question-area\" id=\"qarea\" cols=\"38\" rows=\"5\"></textarea>\n </div>\n \n <div class=\"answer\">\n <label class=\"answer-label\" for=\"answer\">Choice-1</label>\n <input class=\"answer-inp\" type=\"text\">\n <i class=\"fa-solid fa-circle-plus fa-xl\" id=\"icon-add\" onclick=\"add_more_field()\"></i>\n </div>\n\n <!-- <div class=\"icon\"></div>-->\n </div>\n\n <button type=\"button\" onclick=\"addNewField();\">Add</button>\n\n</body>"
},
{
"answer_id": 74549988,
"author": "Andy",
"author_id": 1377002,
"author_profile": "https://Stackoverflow.com/users/1377002",
"pm_score": 0,
"selected": false,
"text": "undefined getElementsByClassName querySelector appendChild document.createElement insertAdjacentHTML add-answer // Cache the container element, and add a listener to it\n// This will catch the events from its children and handle them\n// appropriately\nconst container = document.querySelector('.multiple');\ncontainer.addEventListener('click', handleClick);\n\n// The buildHTML function accepts a count, and returns some HTML\n// using a template string. Note you can use `count` in the string,\n// and increment it.\nfunction buildHTML(count) {\n return `\n <div class=\"answer\">\n <label class=\"answer-label\" for=\"answer\">\n Choice-${count + 1}\n </label>\n <input class=\"answer-inp\" type=\"text\">\n <button type=\"button\" class=\"add-answer\">\n <i class=\"fa-solid fa-circle-plus fa-xl\"></i>\n </button>\n </div>\n `;\n}\n\n// `e` is the event the listener catches\nfunction handleClick(e) {\n \n // If the clicked element (`e.target`)\n // has an `add-answer` class (ie the button)...\n if (e.target.matches('.add-answer')) {\n \n // ...get the current number of answers by selecting\n // all the elements with the `answer` class, and getting its length\n const count = container.querySelectorAll('.answer').length;\n\n // Build some HTML passing in that count value\n const html = buildHTML(count);\n \n // Insert that HTML on to the end of the container\n container.insertAdjacentHTML('beforeend', html);\n }\n} <link href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css\" rel=\"stylesheet\"/>\n<div class=\"multiple\">\n <div class=\"question\">Question</div>\n <div class=\"answer\">\n <label class=\"answer-label\" for=\"answer\">\n Choice-1\n </label>\n <input class=\"answer-inp\" type=\"text\">\n <button type=\"button\" class=\"add-answer\">\n <i class=\"fa-solid fa-circle-plus fa-xl\"></i>\n </button>\n </div>\n</div>"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74549450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12314029/"
] |
74,549,487
|
<p>I am very new to Maven, and I am creating a Maven parent and child project. I want the child project to have a different version than the parent, but if I change the version, then I am getting the error <code>Cannot resolve</code> for some of the dependencies.</p>
<p>How can I have a have a parent version different than the child version?</p>
<p>Following are the current properties I have, which are working pretty fine:</p>
<pre><code><modelVersion>4.0.0</modelVersion>
<parent>
<groupId>io.parent-test</groupId>
<artifactId>io.parent-test</artifactId>
<version>0.9.1-SNAPSHOT</version>
<relativePath></relativePath>
</parent>
<artifactId>test-project-converter</artifactId>
<name>test-project</name>
<description>Test Project</description>
</code></pre>
<p>If I change the properties to include the different version for child then I get the error:</p>
<pre><code>
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>io.parent-test</groupId>
<artifactId>io.parent-test</artifactId>
<version>0.9.1-SNAPSHOT</version>
<relativePath></relativePath>
</parent>
<version>0.9.2-SNAPSHOT</version>
<artifactId>test-project-converter</artifactId>
<name>test-project</name>
<description>Test Project</description>
</code></pre>
<p>I have the following dependencies based on the version that is throwing the error:</p>
<pre><code><dependency>
<groupId>io.parent-dep</groupId>
<artifactId>parent-dev</artifactId>
<version>${project.version}</version>
</dependency>
</code></pre>
<p>I tried to look into some of the responses online and made modifications to my parent project to include the properties:</p>
<pre><code><properties>
<revision>0.9.2-SNAPSHOT</revision>
</properties>
</code></pre>
<p>and accordingly, change the child project to include the version <code><version>${revision}</version></code> but it's not working as expected.</p>
<p>Can someone please let me know how can I create a different snapshot version for my child project while keeping the parent project same?</p>
|
[
{
"answer_id": 74549564,
"author": "jerry",
"author_id": 20493210,
"author_profile": "https://Stackoverflow.com/users/20493210",
"pm_score": 2,
"selected": true,
"text": " let html =\n '<div class=\"answer\">\\\n <label class=\"answer-label\" for=\"answer\">Choice-1 </label>\\\n <input class=\"answer-inp\" type=\"text\">\\\n <i class=\"fa-solid fa-circle-plus fa-xl\" id=\"icon-add\" onclick=\"add_more_field()\"></i>\\\n </div>';\n\n function add_more_field() {\n var add = document.querySelector(\".multiple\");\n add.innerHTML += html;\n } <!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>Add Multiple Choice Question</title>\n\n <link\n rel=\"stylesheet\"\n href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css\"\n />\n </head>\n <body>\n <div class=\"multiple\">\n <div class=\"question\">\n <label id=\"question-label\" for=\"question\">Question</label>\n <textarea name=\"question-area\" id=\"qarea\" cols=\"38\" rows=\"5\"></textarea>\n </div>\n <div class=\"answer\">\n <label class=\"answer-label\" for=\"answer\">Choice-1 </label>\n <input class=\"answer-inp\" type=\"text\" />\n <i\n class=\"fa-solid fa-circle-plus fa-xl\"\n id=\"icon-add\"\n onclick=\"add_more_field()\"\n ></i>\n </div>\n\n <!-- <div class=\"icon\"></div>-->\n </div>\n\n </body>\n</html>"
},
{
"answer_id": 74549608,
"author": "Diego D",
"author_id": 1221208,
"author_profile": "https://Stackoverflow.com/users/1221208",
"pm_score": 1,
"selected": false,
"text": "appendChild() innerHTML let choiceNumber = 1;\n\nfunction addNewField(passedLabel) {\n\n choiceNumber++;\n if(passedLabel === undefined)\n choiceLabel = `Choice-${choiceNumber}`;\n else\n choiceLabel = passedLabel;\n\n html = `\n <div class=\"answer\">\n <label class=\"answer-label\" for=\"answer\">${choiceLabel}</label>\n <input class=\"answer-inp\" type=\"text\">\\\n <i class=\"fa-solid fa-circle-plus fa-xl\" id=\"icon-add\" onclick=\"add_more_field()\"></i>\n </div>`;\n\n var add = document.getElementById(\"multiple\");\n add.innerHTML += html;\n} <body>\n\n <div id=\"multiple\">\n\n <div class=\"question\">\n <label id=\"question-label\" for=\"question\">Question</label>\n <textarea name=\"question-area\" id=\"qarea\" cols=\"38\" rows=\"5\"></textarea>\n </div>\n \n <div class=\"answer\">\n <label class=\"answer-label\" for=\"answer\">Choice-1</label>\n <input class=\"answer-inp\" type=\"text\">\n <i class=\"fa-solid fa-circle-plus fa-xl\" id=\"icon-add\" onclick=\"add_more_field()\"></i>\n </div>\n\n <!-- <div class=\"icon\"></div>-->\n </div>\n\n <button type=\"button\" onclick=\"addNewField();\">Add</button>\n\n</body>"
},
{
"answer_id": 74549988,
"author": "Andy",
"author_id": 1377002,
"author_profile": "https://Stackoverflow.com/users/1377002",
"pm_score": 0,
"selected": false,
"text": "undefined getElementsByClassName querySelector appendChild document.createElement insertAdjacentHTML add-answer // Cache the container element, and add a listener to it\n// This will catch the events from its children and handle them\n// appropriately\nconst container = document.querySelector('.multiple');\ncontainer.addEventListener('click', handleClick);\n\n// The buildHTML function accepts a count, and returns some HTML\n// using a template string. Note you can use `count` in the string,\n// and increment it.\nfunction buildHTML(count) {\n return `\n <div class=\"answer\">\n <label class=\"answer-label\" for=\"answer\">\n Choice-${count + 1}\n </label>\n <input class=\"answer-inp\" type=\"text\">\n <button type=\"button\" class=\"add-answer\">\n <i class=\"fa-solid fa-circle-plus fa-xl\"></i>\n </button>\n </div>\n `;\n}\n\n// `e` is the event the listener catches\nfunction handleClick(e) {\n \n // If the clicked element (`e.target`)\n // has an `add-answer` class (ie the button)...\n if (e.target.matches('.add-answer')) {\n \n // ...get the current number of answers by selecting\n // all the elements with the `answer` class, and getting its length\n const count = container.querySelectorAll('.answer').length;\n\n // Build some HTML passing in that count value\n const html = buildHTML(count);\n \n // Insert that HTML on to the end of the container\n container.insertAdjacentHTML('beforeend', html);\n }\n} <link href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css\" rel=\"stylesheet\"/>\n<div class=\"multiple\">\n <div class=\"question\">Question</div>\n <div class=\"answer\">\n <label class=\"answer-label\" for=\"answer\">\n Choice-1\n </label>\n <input class=\"answer-inp\" type=\"text\">\n <button type=\"button\" class=\"add-answer\">\n <i class=\"fa-solid fa-circle-plus fa-xl\"></i>\n </button>\n </div>\n</div>"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74549487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7584240/"
] |
74,549,492
|
<p>I have 2 pandas dataframes:</p>
<p>df1</p>
<pre><code> Home Place
a MS Z2
c KM Z3
d RR R2
</code></pre>
<p>df2</p>
<pre><code> Place1
a A2
c A66
z F32
x K41
t E90
</code></pre>
<p>I want to replace values of df2['Place1'] with df1['Place'] when indexes are matching and leave it the same when indexes are not matching.</p>
<p>Desired result:</p>
<pre><code> Place1
a Z2
c Z3
z F32
x K41
t E90
</code></pre>
<p>I tried to use pd.replace but it returns NAs</p>
|
[
{
"answer_id": 74549556,
"author": "BENY",
"author_id": 7964527,
"author_profile": "https://Stackoverflow.com/users/7964527",
"pm_score": 1,
"selected": false,
"text": "update df2['Place1'].update(df1['Place'])\ndf2\nOut[75]: \n Place1\na Z2\nc Z3\nz F32\nx K41\nt E90\n"
},
{
"answer_id": 74549604,
"author": "steflbert",
"author_id": 20572791,
"author_profile": "https://Stackoverflow.com/users/20572791",
"pm_score": 0,
"selected": false,
"text": "df2['Place1'] = df2['Place1'].update(df1['Place'])\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74549492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20583361/"
] |
74,549,542
|
<p>can somebody help me?
I have problem with position in css. I would like to move first div to the right and second div move under it (first picture).When I use <strong>float: right</strong> for first <strong>div</strong> it looks like that these components are next to each other (second picture).</p>
<pre><code><div>
<div>
<button> Button 1 </button>
<button> Button 2 </button>
</div>
<div>
<image></image>
</div>
</div>
</code></pre>
<p>Can somebody help me how css file sjhould looklike</p>
<p><a href="https://i.stack.imgur.com/aVOXA.png" rel="nofollow noreferrer">how it should look like</a>
<a href="https://i.stack.imgur.com/51MaT.png" rel="nofollow noreferrer">how it is now</a></p>
|
[
{
"answer_id": 74549556,
"author": "BENY",
"author_id": 7964527,
"author_profile": "https://Stackoverflow.com/users/7964527",
"pm_score": 1,
"selected": false,
"text": "update df2['Place1'].update(df1['Place'])\ndf2\nOut[75]: \n Place1\na Z2\nc Z3\nz F32\nx K41\nt E90\n"
},
{
"answer_id": 74549604,
"author": "steflbert",
"author_id": 20572791,
"author_profile": "https://Stackoverflow.com/users/20572791",
"pm_score": 0,
"selected": false,
"text": "df2['Place1'] = df2['Place1'].update(df1['Place'])\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74549542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14182697/"
] |
74,549,567
|
<p>I'm trying to practice for a techniqual test where I have to count the number of characters in a DNA sequence, but no matter what I do the counter won't update, this is really frustrating as I learnt code with ruby and it would update, but Java seems to have an issue. I know there's something wrong with my syntaxt but for the life of me I can't figure it out.</p>
<pre><code>public class DNA {
public static void main(String[] args) {
String dna1 = "ATGCGATACGCTTGA";
String dna2 = "ATGCGATACGTGA";
String dna3 = "ATTAATATGTACTGA";
String dna = dna1;
int aCount = 0;
int cCount = 0;
int tCount = 0;
for (int i = 0; i <= dna.length(); i++) {
if (dna.substring(i) == "A") {
aCount+= 1;
}
else if (dna.substring(i) == "C") {
cCount++;
}
else if (dna.substring(i) == "T") {
tCount++;
}
System.out.println(aCount);
}
}
}
</code></pre>
<p>It just keeps returning zero instead of adding one to it if the conditions are meet and reassigning the value.</p>
|
[
{
"answer_id": 74549671,
"author": "Edward Peters",
"author_id": 6016064,
"author_profile": "https://Stackoverflow.com/users/6016064",
"pm_score": 2,
"selected": false,
"text": "substring System.out.println(dna.substring(i)); ATGCGATACGCTTGA\nTGCGATACGCTTGA\nGCGATACGCTTGA\nCGATACGCTTGA\nGATACGCTTGA\nATACGCTTGA\nTACGCTTGA\nACGCTTGA\nCGCTTGA\nGCTTGA\nCTTGA\nTTGA\nTGA\nGA\nA\n substring == string1.equals(string2)"
},
{
"answer_id": 74549884,
"author": "Philippe Fery",
"author_id": 10675247,
"author_profile": "https://Stackoverflow.com/users/10675247",
"pm_score": 0,
"selected": false,
"text": "substring equals String a = \"first string\";\nString b = \"second string\";\nboolean result = a.equals(b));\n charAt(int) char a = '6';\nchar b = 't';\nboolean result = (a==b);\n public class DNA {\n \n public static void main(String[] args) {\n String dna1 = \"ATGCGATACGCTTGA\";\n String dna2 = \"ATGCGATACGTGA\";\n String dna3 = \"ATTAATATGTACTGA\";\n String dna = dna1;\n int aCount = 0;\n int cCount = 0;\n int tCount = 0;\n \n for (int i = 0; i < dna.length(); i++) {\n if (dna.charAt(i) == 'A') {\n aCount += 1;\n } else if (dna.charAt(i) == 'C') {\n cCount++;\n } else if (dna.charAt(i) == 'T') {\n tCount++;\n }\n System.out.println(aCount);\n }\n }\n }\n"
},
{
"answer_id": 74550827,
"author": "WJS",
"author_id": 1552534,
"author_profile": "https://Stackoverflow.com/users/1552534",
"pm_score": 0,
"selected": false,
"text": "public class DNA {\n\n public static void main(String[] args) {\n String dna1 = \"ATGCGATACGCTTGA\";\n String dna2 = \"ATGCGATACGTGA\";\n String dna3 = \"ATTAATATGTACTGA\";\n\n String[] dnaStrings =\n {dna1,dna2,dna3};\n int aCount = 0;\n int cCount = 0;\n int tCount = 0;\n int gCount = 0;\n for (String dnaString : dnaStrings) {\n for (char c : dnaString.toCharArray()) {\n switch (c) {\n case 'A' -> aCount++;\n case 'T' -> tCount++;\n case 'C' -> cCount++;\n case 'G' -> gCount++;\n }\n }\n }\n System.out.println(\"A's = \" + aCount);\n System.out.println(\"T's = \" + tCount);\n System.out.println(\"C's = \" + cCount);\n System.out.println(\"G's = \" + gCount);\n}\n A's = 14\nT's = 13\nC's = 6\nG's = 10\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74549567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20583533/"
] |
74,549,568
|
<p>I am working on a project to build a portal inside SharePoint online. Now i got this requirement:-</p>
<ul>
<li>To build a quick links web part in React SPFx (similar to the built-in modern Quick Links)</li>
<li>But this quick links can contain links to internal applications that can only be accessed using VPN.</li>
<li>So if the user access the SharePoint online home page without VPN >> the quick links should hide all the links which the user does not have access to.</li>
<li>Also if the user access the SharePoint using VPN and the user does not have permission to the internal system (the user will get http 401 or will be prompted with a dialog to enter username and password) to hide the links as well.</li>
</ul>
<p>So in other words, the SPFx web part need to send a request to the link url, and if it get http code other than "2xx success" to hide the link.</p>
<p>Can anyone advice how to build such a web part please?</p>
<p>Now i tried to benefit from this SPFx web part @ <a href="https://github.com/clarktozer/spfx-quicklinks" rel="nofollow noreferrer">https://github.com/clarktozer/spfx-quicklinks</a> . where this is the <code>QuickLinksWebPart.ts</code>:-</p>
<pre><code>import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
PropertyPaneDropdown,
PropertyPaneCheckbox} from '@microsoft/sp-webpart-base';
import * as strings from 'QuickLinksWebPartStrings';
import QuickLinks from './components/QuickLinks';
import { IQuickLinksProps } from './components/IQuickLinksProps';
import { PropertyPaneLinksList } from '../../controls/PropertyPaneLinksList/PropertyPaneLinksList';
import { PropertyFieldColorPicker, PropertyFieldColorPickerStyle } from '@pnp/spfx-property-controls/lib/PropertyFieldColorPicker';
import { Link } from '../../controls/PropertyPaneLinksList/components/ILinksListState';
export interface IQuickLinksWebPartProps {
title: string;
type: LinkType;
iconColor: string;
openInNewTab?: boolean;
fontColor: string;
initLinks: string[];
links: Link[];
}
export enum LinkType {
LINK = "Link",
FILE = "File"
}
export default class QuickLinksWebPart extends BaseClientSideWebPart<IQuickLinksWebPartProps> {
public render(): void {
const element: React.ReactElement<IQuickLinksProps> = React.createElement(
QuickLinks,
{
title: this.properties.title,
type: this.properties.type,
iconColor: this.properties.iconColor,
fontColor: this.properties.fontColor,
openInNewTab: this.properties.openInNewTab,
links: this.properties.links != null ? this.properties.links : [],
displayMode: this.displayMode,
updateProperty: (value: string) => {
this.properties.title = value;
}
}
);
ReactDom.render(element, this.domElement);
}
protected onDispose(): void {
ReactDom.unmountComponentAtNode(this.domElement);
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.BasicGroupName,
groupFields: [
PropertyPaneDropdown('type', {
label: strings.LinkType,
options: Object.keys(LinkType).map((e) => {
return {
key: LinkType[e], text: LinkType[e]
};
}),
selectedKey: 'link'
}),
PropertyPaneCheckbox('openInNewTab', {
text: strings.OpenInNewTab
})
]
},
{
groupName: strings.StylingGroup,
groupFields: [
PropertyFieldColorPicker('iconColor', {
label: strings.IconColor,
selectedColor: this.properties.iconColor,
onPropertyChange: this.onPropertyPaneFieldChanged.bind(this),
properties: this.properties,
disabled: false,
alphaSliderHidden: false,
style: PropertyFieldColorPickerStyle.Inline,
key: 'iconColor'
}),
PropertyFieldColorPicker('fontColor', {
label: strings.FontColor,
selectedColor: this.properties.fontColor,
onPropertyChange: this.onPropertyPaneFieldChanged.bind(this),
properties: this.properties,
disabled: false,
alphaSliderHidden: false,
style: PropertyFieldColorPickerStyle.Inline,
key: 'fontColor'
})
]
},
{
groupName: strings.LinksGroup,
groupFields: [
new PropertyPaneLinksList("links", {
key: "links",
links: this.properties.links
})
]
}
]
}
]
};
}
}
</code></pre>
<p>and this is the <code>QuikcLinks.tsx</code> :-</p>
<pre><code>import * as React from 'react';
import styles from './QuickLinks.module.scss';
import { IQuickLinksProps } from './IQuickLinksProps';
import { autobind } from '@uifabric/utilities';
import { LinkType } from '../QuickLinksWebPart';
import { WebPartTitle } from "@pnp/spfx-controls-react/lib/WebPartTitle";
import Radium from 'radium';
import * as tinycolor from 'tinycolor2';
@Radium
export default class QuickLinks extends React.Component<IQuickLinksProps, {}> {
private inlineStyles: any;
constructor(props: IQuickLinksProps) {
super(props);
}
@autobind
private createLinkStyle(hoverColor) {
return {
color: this.props.fontColor,
':hover': {
color: tinycolor(hoverColor).darken(25).toString()
}
};
}
@autobind
public getIcon() {
let icon = "";
switch (this.props.type) {
case LinkType.FILE:
icon = "OpenFile";
break;
default:
icon = "Link";
}
return icon;
}
public render(): React.ReactElement<IQuickLinksProps> {
this.inlineStyles = {
link: this.createLinkStyle(this.props.fontColor)
};
return (
<div className={"ms-Grid " + styles.quickLinks}>
<div>
<div className="ms-Grid-row">
<div className="ms-Grid-col ms-sm12">
<WebPartTitle displayMode={this.props.displayMode}
title={this.props.title}
updateProperty={this.props.updateProperty} />
{
this.props.links.map((e, i) => {
let linkProps = {
key: e.key,
href: e.value
};
if (this.props.openInNewTab) {
linkProps["target"] = "_blank";
}
return <div className={styles.linkRow} key={this.props.type + "-link-" + i}>
<i style={{ color: this.props.iconColor }} className={styles.quickLinkIcon + " ms-Icon ms-Icon--" + this.getIcon()} aria-hidden="true"></i>
<a className={styles.link} {...linkProps} style={this.inlineStyles.link}>{e.label}</a>
</div>;
})
}
</div>
</div>
</div>
</div>
);
}
}
</code></pre>
<p>So where i need to do the call to the URL and check the response so i can render the link or hide it accordingly??
Thanks</p>
|
[
{
"answer_id": 74549671,
"author": "Edward Peters",
"author_id": 6016064,
"author_profile": "https://Stackoverflow.com/users/6016064",
"pm_score": 2,
"selected": false,
"text": "substring System.out.println(dna.substring(i)); ATGCGATACGCTTGA\nTGCGATACGCTTGA\nGCGATACGCTTGA\nCGATACGCTTGA\nGATACGCTTGA\nATACGCTTGA\nTACGCTTGA\nACGCTTGA\nCGCTTGA\nGCTTGA\nCTTGA\nTTGA\nTGA\nGA\nA\n substring == string1.equals(string2)"
},
{
"answer_id": 74549884,
"author": "Philippe Fery",
"author_id": 10675247,
"author_profile": "https://Stackoverflow.com/users/10675247",
"pm_score": 0,
"selected": false,
"text": "substring equals String a = \"first string\";\nString b = \"second string\";\nboolean result = a.equals(b));\n charAt(int) char a = '6';\nchar b = 't';\nboolean result = (a==b);\n public class DNA {\n \n public static void main(String[] args) {\n String dna1 = \"ATGCGATACGCTTGA\";\n String dna2 = \"ATGCGATACGTGA\";\n String dna3 = \"ATTAATATGTACTGA\";\n String dna = dna1;\n int aCount = 0;\n int cCount = 0;\n int tCount = 0;\n \n for (int i = 0; i < dna.length(); i++) {\n if (dna.charAt(i) == 'A') {\n aCount += 1;\n } else if (dna.charAt(i) == 'C') {\n cCount++;\n } else if (dna.charAt(i) == 'T') {\n tCount++;\n }\n System.out.println(aCount);\n }\n }\n }\n"
},
{
"answer_id": 74550827,
"author": "WJS",
"author_id": 1552534,
"author_profile": "https://Stackoverflow.com/users/1552534",
"pm_score": 0,
"selected": false,
"text": "public class DNA {\n\n public static void main(String[] args) {\n String dna1 = \"ATGCGATACGCTTGA\";\n String dna2 = \"ATGCGATACGTGA\";\n String dna3 = \"ATTAATATGTACTGA\";\n\n String[] dnaStrings =\n {dna1,dna2,dna3};\n int aCount = 0;\n int cCount = 0;\n int tCount = 0;\n int gCount = 0;\n for (String dnaString : dnaStrings) {\n for (char c : dnaString.toCharArray()) {\n switch (c) {\n case 'A' -> aCount++;\n case 'T' -> tCount++;\n case 'C' -> cCount++;\n case 'G' -> gCount++;\n }\n }\n }\n System.out.println(\"A's = \" + aCount);\n System.out.println(\"T's = \" + tCount);\n System.out.println(\"C's = \" + cCount);\n System.out.println(\"G's = \" + gCount);\n}\n A's = 14\nT's = 13\nC's = 6\nG's = 10\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74549568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1146775/"
] |
74,549,582
|
<p>I'm currently building a minimalist app following this CMake architecture:</p>
<p>-root</p>
<p>--QmlModule</p>
<p>---Component1.qml</p>
<p>---Component2.qml</p>
<p>--App1</p>
<p>---main.cpp</p>
<p>---main.qml</p>
<p>--App2</p>
<p>---main.cpp</p>
<p>---main.qml</p>
<p>I use "qt6_add_qml_module" to create a QML module at "QmlModule" level as a STATIC library.</p>
<pre><code>qt_add_library(myComponentTarget STATIC)
qt6_add_qml_module(myComponentTarget
URI QmlModule
VERSION 1.0
QML_FILES
Component1.qml
Component2.qml
RESOURCES
logo.png)
</code></pre>
<p>Then, at App1 (and App2) level, a link to the module is done using "target_link_libraries". "qt6_add_qml_module" does some work behind the scenes in order to expose the module trough an automatically generated plugin named "your_component_URIplugin". More details about this <a href="https://doc.qt.io/qt-6.2/qtqml-writing-a-module.html" rel="nofollow noreferrer">here</a>.</p>
<pre><code>add_executable(App1Exe
main.cpp)
qt6_add_qml_module(App1Exe
URI App1
VERSION 1.0
QML_FILES
main.qml)
target_link_libraries(App1Exe
PRIVATE
myComponentURIplugin)
</code></pre>
<p>At Root level, I overload QML_IMPORT_PATH in order to link to the build folder and add all subdirectories.</p>
<pre><code>set(QML_IMPORT_PATH ${CMAKE_CURRENT_SOURCE_DIR}/qmlModule)
add_subdirectory(QmlModule)
add_subdirectory(App1)
add_subdirectory(App2)
</code></pre>
<p>I run CMake without any errors, and open App1/main.qml file.
On my <code>import QmlModule</code>, the module can't be found:</p>
<blockquote>
<p>module "lupinComponentsplugin" is not installed</p>
</blockquote>
<p>How to make my module visible from my Apps ?
What step am I missing ?</p>
|
[
{
"answer_id": 74602211,
"author": "Greg",
"author_id": 4373753,
"author_profile": "https://Stackoverflow.com/users/4373753",
"pm_score": 1,
"selected": true,
"text": "QQmlApplicationEngine engine;\nengine.addImportPath(\":/\");\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74549582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4373753/"
] |
74,549,589
|
<p>i need a guide to establish a connection to a public web service, send request to it and get response back. for example this web service:</p>
<pre><code>http://webservices.oorsprong.org/websamples.countryinfo/CountryInfoService.wso?WSDL
</code></pre>
<p>i've tried to test this API with SoapUI application. this API has a bunch of methods such as sending you a country's capital by getting it's ISO name (send IR as request and get Tehran as respond). now somehow i want to do this through Python. i want to have access to all it's methods and send requests. only by connecting to API's address or any other way (maybe by loading each method's XML code and running it in Python? idk). is it possible? any guide?</p>
|
[
{
"answer_id": 74602211,
"author": "Greg",
"author_id": 4373753,
"author_profile": "https://Stackoverflow.com/users/4373753",
"pm_score": 1,
"selected": true,
"text": "QQmlApplicationEngine engine;\nengine.addImportPath(\":/\");\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74549589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8150028/"
] |
74,549,597
|
<p>I'm trying to create an Java Swing (with Ant) application to send an email to a desired address(My first time).The application builds successfully but when I click the button to send the email I get a lot of different error messages, with the first being a java.lang.NoClassDefFoundError: javax/activation/DataSource .The sender email is new and I did not assosciate it with a phone number(I was told it might lead to issues). I've also have already added the mail.jar to the project library. The catch JOptionPane did not print any errors as well so I'm having a hard time figuring this out. I've attached the code as well as a <a href="https://i.stack.imgur.com/MpxLL.png" rel="nofollow noreferrer">screenshot</a> of the error.</p>
<blockquote>
<pre><code>private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String toEmail= "email1";//Changed emails for securityPurposes
String fromEmail = "email2";
String fromEmailPassword="Password";
String subject="This is the subject";
Properties properties = new Properties();
properties.put("mail.smtp.auth","true");
properties.put("mail.smtp.starttls.enable","true");
properties.put("mail.smtp.host","smtp.gmail.com");
properties.put("mail.smtp.port","587");
Session session=Session.getDefaultInstance(properties,new >javax.mail.Authenticator(){
@Override
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(fromEmail,fromEmailPassword);
}
});
try{
MimeMessage message=new MimeMessage(session);
message.setFrom(new InternetAddress(fromEmail));
message.addRecipient(Message.RecipientType.TO,new >InternetAddress(toEmail));
message.setSubject(subject);
message.setText("Hello");
Transport.send(message);
}
catch(Exception ex){
JOptionPane.showMessageDialog(null, ex);
}
}
</code></pre>
</blockquote>
<p>I've looked but haven't found any similar cases or solutions.</p>
|
[
{
"answer_id": 74602211,
"author": "Greg",
"author_id": 4373753,
"author_profile": "https://Stackoverflow.com/users/4373753",
"pm_score": 1,
"selected": true,
"text": "QQmlApplicationEngine engine;\nengine.addImportPath(\":/\");\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74549597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20325375/"
] |
74,549,610
|
<p>Valid URL fails requests.get</p>
<p><a href="https://finance.yahoo.com/quote/AAPL/analysis?p=AAPL" rel="nofollow noreferrer">https://finance.yahoo.com/quote/AAPL/analysis?p=AAPL</a> is a valid URL as is not redirects</p>
<p>DOES NOT WORK</p>
<pre><code>import requests
url6 = 'https://finance.yahoo.com/quote/AAPL/analysis?p=AAPL'
r = requests.get(url6)
</code></pre>
<p>returns</p>
<p>False</p>
<p>404</p>
<p>[]</p>
<p>or more simply</p>
<pre><code>requests.get('https://finance.yahoo.com/quote/AAPL/analysis?p=AAPL')
</code></pre>
<p><Response [404]></p>
<p>WORKS
this for example (different page on same source)</p>
<pre><code>requests.get('https://finance.yahoo.com/quote/AMG?p=AMG')
</code></pre>
<p>returns
True
200</p>
|
[
{
"answer_id": 74602211,
"author": "Greg",
"author_id": 4373753,
"author_profile": "https://Stackoverflow.com/users/4373753",
"pm_score": 1,
"selected": true,
"text": "QQmlApplicationEngine engine;\nengine.addImportPath(\":/\");\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74549610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20574706/"
] |
74,549,630
|
<p>I test my script just printing return value of .split:</p>
<pre><code>for f in os.listdir():
f_name, f_ext = os.path.splitext(f)
print(f_name.split('-'))
</code></pre>
<p>and it shows me what I'd like to see - lists with 3 strings in each.</p>
<pre><code>['Earth ', ' Our Solar System ', ' #4']
['Saturn ', ' Our Solar System ', ' #7']
['The Sun ', ' Our Solar System ', ' #1']
</code></pre>
<p>However, when I'm trying to store it in 3 different variables:</p>
<pre><code>for f in os.listdir():
f_name, f_ext = os.path.splitext(f)
f_title, f_course, f_num = f_name.split(' - ')
</code></pre>
<p>it gives me an error:</p>
<pre><code>f_title, f_course, f_num = f_name.split('-')
^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: not enough values to unpack (expected 3, got 1)
</code></pre>
<p>I'd appreciate any help on this! Thanks!</p>
<hr />
|
[
{
"answer_id": 74602211,
"author": "Greg",
"author_id": 4373753,
"author_profile": "https://Stackoverflow.com/users/4373753",
"pm_score": 1,
"selected": true,
"text": "QQmlApplicationEngine engine;\nengine.addImportPath(\":/\");\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74549630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20562348/"
] |
74,549,658
|
<p>When I run <code>Invoke-Sqlcmd</code> with a <code>-Query</code> that contains a password retrieved via <code>Read-Host</code> with the <code>-AsSecureString</code> parameter, and the value entered is <a href="https://learn.microsoft.com/en-us/previous-versions/azure/jj943764(v=azure.100)" rel="nofollow noreferrer">too simple</a>, it will fail <strong>without</strong> returning an exception.</p>
<p>When I run <code>Invoke-Sqlcmd</code> with a <code>-Query</code> that contains a password retrieved via <code>Read-Host</code> <strong>without</strong> the <code>-AsSecureString</code> parameter, and the value entered is too simple, it will return an exception, as expected:</p>
<blockquote>
<p>Password validation failed. The password does not meet policy requirements because it is not complex enough.</p>
<p>Msg 40632, Level 16, State 1, Procedure , Line 1.</p>
</blockquote>
<p><strong>Examples</strong></p>
<p>This code returns the "Msg 40632" exception when I enter <code>01234567</code> as a password, and will successfully execute when I enter <code>012345A!</code> as a password:</p>
<pre><code>$local:password = Read-Host ("Enter the new password for {0} on {1}" -f $local:login, $local:serverDomain)
$local:updatePasswordQuery = ("ALTER LOGIN {0} WITH PASSWORD = '{1}'" -f $local:login, $local:password)
Invoke-Sqlcmd `
-ServerInstance ("{0}.database.windows.net" -f $local:server.name) `
-Database "master" `
-AccessToken $local:access_token `
-ErrorAction Stop `
-Query "$local:updatePasswordQuery"
</code></pre>
<p>This code will <strong>fail silently</strong> when I enter <code>01234567</code> as a password, and will also successfully execute when I enter <code>012345A!</code> as a password:</p>
<pre><code>$local:securePassword = Read-Host ("Enter the new password for {0} on {1}" -f $local:login, $local:serverDomain) `
-AsSecureString
$local:updatePasswordQuery = ("ALTER LOGIN {0} WITH PASSWORD = '{1}'" -f $local:login, $local:securePassword)
Invoke-Sqlcmd `
-ServerInstance ("{0}.database.windows.net" -f $local:server.name) `
-Database "master" `
-AccessToken $local:access_token `
-ErrorAction Stop `
-Query "$local:updatePasswordQuery"
</code></pre>
<p><strong>So my question is: how can I get Invoke-Sqlcmd to return an exception when I pass a secure string with a password that is not complex enough?</strong> Or is this simply impossible due to the nature of <a href="https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.security/convertto-securestring?view=powershell-7.3" rel="nofollow noreferrer">secure strings</a>?</p>
<pre><code>> $PSVersionTable
Name Value
---- -----
PSVersion 7.3.0
PSEdition Core
GitCommitId 7.3.0
OS Microsoft Windows 10.0.22000
Platform Win32NT
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
WSManStackVersion 3.0
Imported Modules:
Az.Accounts 2.10.3
SqlServer 21.1.18256
</code></pre>
|
[
{
"answer_id": 74602211,
"author": "Greg",
"author_id": 4373753,
"author_profile": "https://Stackoverflow.com/users/4373753",
"pm_score": 1,
"selected": true,
"text": "QQmlApplicationEngine engine;\nengine.addImportPath(\":/\");\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74549658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/533460/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.