qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,506,237
|
<p><img src="https://i.stack.imgur.com/b77um.png" alt="I am trying to retrieve these two Timestamp fields." /></p>
<p>I have the starts and ends fields in my model as Timestamp, but I am getting this error. I don't get it when I define start and end as var in my Model.</p>
<pre><code>Unhandled Exception: type 'Null' is not a subtype of type 'Timestamp'
</code></pre>
<p>Model:</p>
<pre><code> import 'package:cloud_firestore/cloud_firestore.dart';
class Event {
String eid;
String title;
String location;
Timestamp start;
Timestamp end;
String instructor;
String image;
String description;
Event({
required this.eid,
required this.title,
required this.location,
required this.start,
required this.end,
required this.instructor,
required this.image,
required this.description
});
factory Event.fromMap(Map<String, dynamic>? map) {
return Event(
eid: map?['eid'] ?? 'undefined',
title: map?['title'] ?? 'undefined',
location: map?['location'] ?? 'undefined',
start: map?['starts'],
end: map?['ends'],
instructor: map?['instructor'] ?? 'undefined',
image: map?['image'] ?? 'undefined',
description: map?['description'] ?? 'undefined'
);
}
</code></pre>
|
[
{
"answer_id": 74506218,
"author": "Niaho",
"author_id": 15283583,
"author_profile": "https://Stackoverflow.com/users/15283583",
"pm_score": 2,
"selected": true,
"text": "onsubmit=\"return validateEmail(this)\"\n"
},
{
"answer_id": 74506251,
"author": "Niaho",
"author_id": 15283583,
"author_profile": "https://Stackoverflow.com/users/15283583",
"pm_score": -1,
"selected": false,
"text": "var validRegex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\\.[a-zA-Z0-9_-]{2,3}){1,2})$/;\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20373971/"
] |
74,506,245
|
<p>Using Lambda function to Get and post request. While testing it gives error
{"errorMessage": "'httpMethod'", "errorType": "KeyError", "requestId": "435e6811-acc5-4bc7-b009-377bc6178bb8", "stackTrace": [" File "/var/task/lambda_function.py", line 11, in lambda_handler\n if event['httpMethod'] == 'GET':\n"]} :</p>
<pre><code>dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('ApigatewayDynamo')
def lambda_handler(event, context):
print("event", event)
if event['httpMethod'] == 'GET':
name = event['queryStringParameters']['name']
response = table.get_item(Key={'name': name})
print(response)
print(response['Item'])
return {
'statusCode': 200,
'body': json.dumps(response['Item'])
}
if event['httpMethod'] == 'POST':
body = json.loads(event['body'])
print('body', body)
name = body.get('name')
print('Name is ', name)
if name is None:
return {
'statusCode': 400,
'body': json.dumps("Check the payload/ method")
}
table.put_item(Item=body)
return {
'statusCode': 200,
'body': json.dumps("Name added successfully")
}
return {
'statusCode': 400,
'body': json.dumps("Check the payload/ method/ Lambda function")
}
</code></pre>
<p>The Dynamo db table has name as primary key and the json testing data is</p>
<pre><code>{
"name": "Kaira",
"Phone Number": 98777
}
</code></pre>
<p>What is to be done to resolve this?</p>
<p>I am trying to insert the data from post method and get the data from Get method.</p>
|
[
{
"answer_id": 74507310,
"author": "Lee Hannigan",
"author_id": 7909676,
"author_profile": "https://Stackoverflow.com/users/7909676",
"pm_score": 1,
"selected": false,
"text": "event event event"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13971824/"
] |
74,506,247
|
<p>I have an array like this:</p>
<pre><code>[
{
"function_1": {
"element": {
"error": "0",
"msg": "test"
}
}
},
{
"function_1": {
"element_2": {
"error": "0",
"msg": "test"
}
}
},
{
"function_2": {
"element": {
"error": "0",
"msg": "test"
}
}
},
{
"function_2": {
"element_2": {
"error": "0",
"msg": "test"
}
}
}
]
</code></pre>
<p>I want output like this:</p>
<pre><code>[
{
"function_1": {
"element": {
"error": "0",
"msg": "test"
},
"element_2": {
"error": "0",
"msg": "test"
}
}
},
{
"function_2": {
"element": {
"error": "0",
"msg": "test"
},
"element_2": {
"error": "0",
"msg": "test"
}
}
}
]
</code></pre>
<p>The answers that I found offered to search by name("function_1", "function_2"). But this does not suit me, the function will not always pass an array. I need exactly the "depth" or any other reasonable way.
Thank you!</p>
|
[
{
"answer_id": 74506408,
"author": "albertdiones",
"author_id": 2665533,
"author_profile": "https://Stackoverflow.com/users/2665533",
"pm_score": 0,
"selected": false,
"text": "function combineElementsPerfunction($functions) {\n\n $result = [];\n\n $uniqueFunctions = [];\n foreach ($functions as $function) {\n $functionName = array_keys($function)[0];\n $uniqueFunctions[] = $functionName;\n }\n $uniqueFunctions = array_unique($uniqueFunctions);\n foreach ($uniqueFunctions as $uniqueFunction) {\n $functionObjects = array_filter(\n $functions,\n function($function) use ($uniqueFunction) {\n $functionName = array_keys($function)[0];\n return $functionName === $uniqueFunction;\n }\n );\n \n $elements = [];\n foreach ($functionObjects as $functionObject) {\n $function = array_shift($functionObject);\n $elements = array_merge($elements, $function);\n }\n \n $result[] = [\n $uniqueFunction => $elements\n ];\n }\n return $result;\n}\n"
},
{
"answer_id": 74506679,
"author": "Niaho",
"author_id": 15283583,
"author_profile": "https://Stackoverflow.com/users/15283583",
"pm_score": 0,
"selected": false,
"text": "function changeArr($data){\n $box = $new = [];\n foreach ($data as $v){\n $key = array_key_first($v);\n $i = count($box);\n if(in_array($key, $box)){\n $keys = array_flip($box);\n $i = $keys[$key];\n }else{\n $box[] = $key;\n }\n $new[$i][$key] = isset($new[$i][$key]) ? array_merge($new[$i][$key], $v[$key]) : $v[$key];\n }\n return $new;\n}\n"
},
{
"answer_id": 74511979,
"author": "mickmackusa",
"author_id": 2943403,
"author_profile": "https://Stackoverflow.com/users/2943403",
"pm_score": 1,
"selected": false,
"text": "$array = json_decode($json, true);\n$merged = array_merge_recursive(...$array);\n\n$result = [];\nforeach ($merged as $key => $data) {\n $result[] = [$key => $data];\n}\nvar_export($result);\n array_merge_recursive() var_export(\n array_merge_recursive(\n ...json_decode($json, true)\n )\n);\n array (\n 'function_1' => \n array (\n 'element' => \n array (\n 'error' => '0',\n 'msg' => 'test',\n ),\n 'element_2' => \n array (\n 'error' => '0',\n 'msg' => 'test',\n ),\n ),\n 'function_2' => \n array (\n 'element' => \n array (\n 'error' => '0',\n 'msg' => 'test',\n ),\n 'element_2' => \n array (\n 'error' => '0',\n 'msg' => 'test',\n ),\n ),\n)\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20469430/"
] |
74,506,276
|
<p>I have an array of object and one array with integer ids.</p>
<p>I want to only have those entries in array of object whose ids are matched with array with has those ids in react jsx.</p>
<p>Ex:</p>
<pre><code>A = [(0)-> id:'123', name:'john', city:'Newyork']
[(1)-> id:'345', name:'martin', city:'Tokyo']
[(2)-> id:'456', name:'lee', city:'Malbonre']
[(3)-> id:'567', name:'roman', city:'Delhi']
[(4)-> id:'789', name:'julie', city:'US']
B = [123, 456,567]
</code></pre>
<p>I want the result in such a way that array A should have only</p>
<pre><code> A = [(0)-> id:'123', name:'john', city:'Newyork']
[(1)-> id:'456', name:'lee', city:'Malbonre']
[(2)-> id:'567', name:'roman', city:'Delhi']
</code></pre>
|
[
{
"answer_id": 74506408,
"author": "albertdiones",
"author_id": 2665533,
"author_profile": "https://Stackoverflow.com/users/2665533",
"pm_score": 0,
"selected": false,
"text": "function combineElementsPerfunction($functions) {\n\n $result = [];\n\n $uniqueFunctions = [];\n foreach ($functions as $function) {\n $functionName = array_keys($function)[0];\n $uniqueFunctions[] = $functionName;\n }\n $uniqueFunctions = array_unique($uniqueFunctions);\n foreach ($uniqueFunctions as $uniqueFunction) {\n $functionObjects = array_filter(\n $functions,\n function($function) use ($uniqueFunction) {\n $functionName = array_keys($function)[0];\n return $functionName === $uniqueFunction;\n }\n );\n \n $elements = [];\n foreach ($functionObjects as $functionObject) {\n $function = array_shift($functionObject);\n $elements = array_merge($elements, $function);\n }\n \n $result[] = [\n $uniqueFunction => $elements\n ];\n }\n return $result;\n}\n"
},
{
"answer_id": 74506679,
"author": "Niaho",
"author_id": 15283583,
"author_profile": "https://Stackoverflow.com/users/15283583",
"pm_score": 0,
"selected": false,
"text": "function changeArr($data){\n $box = $new = [];\n foreach ($data as $v){\n $key = array_key_first($v);\n $i = count($box);\n if(in_array($key, $box)){\n $keys = array_flip($box);\n $i = $keys[$key];\n }else{\n $box[] = $key;\n }\n $new[$i][$key] = isset($new[$i][$key]) ? array_merge($new[$i][$key], $v[$key]) : $v[$key];\n }\n return $new;\n}\n"
},
{
"answer_id": 74511979,
"author": "mickmackusa",
"author_id": 2943403,
"author_profile": "https://Stackoverflow.com/users/2943403",
"pm_score": 1,
"selected": false,
"text": "$array = json_decode($json, true);\n$merged = array_merge_recursive(...$array);\n\n$result = [];\nforeach ($merged as $key => $data) {\n $result[] = [$key => $data];\n}\nvar_export($result);\n array_merge_recursive() var_export(\n array_merge_recursive(\n ...json_decode($json, true)\n )\n);\n array (\n 'function_1' => \n array (\n 'element' => \n array (\n 'error' => '0',\n 'msg' => 'test',\n ),\n 'element_2' => \n array (\n 'error' => '0',\n 'msg' => 'test',\n ),\n ),\n 'function_2' => \n array (\n 'element' => \n array (\n 'error' => '0',\n 'msg' => 'test',\n ),\n 'element_2' => \n array (\n 'error' => '0',\n 'msg' => 'test',\n ),\n ),\n)\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3241554/"
] |
74,506,281
|
<p>The <a href="https://doc.rust-lang.org/reference/attributes/testing.html" rel="nofollow noreferrer">Rust docs</a> mention that the <code>#[test]</code> directive is for marking a function which is only compiled and executed in test mode. What is the reason for having the <code>#[cfg(test)]</code> directive then?</p>
|
[
{
"answer_id": 74506469,
"author": "Chayim Friedman",
"author_id": 7884305,
"author_profile": "https://Stackoverflow.com/users/7884305",
"pm_score": 3,
"selected": true,
"text": "#[cfg(test)] #[cfg] #[test] #[cfg(test)]"
},
{
"answer_id": 74506481,
"author": "Nikolay Zakirov",
"author_id": 9023490,
"author_profile": "https://Stackoverflow.com/users/9023490",
"pm_score": 2,
"selected": false,
"text": "#[cfg(test)] #[test] test_helper mod tests cargo test"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7932229/"
] |
74,506,302
|
<p>I'm attempting to determine the number of consecutive wins and losses. I get the number with my current code, but when I test its reliability with the total number of wins and losses, it doesn't match the total number of wins and losses shown by the strategy tester, so I'm not sure if it's giving me the right answer. `</p>
<pre><code>print(string txt1, string txt2,string txt) =>
var table t = table.new(position.middle_right, 1, 3)
table.cell(t, 0, 0, txt1, bgcolor = color.rgb(0, 254, 21))
table.cell(t, 0, 1, txt2, bgcolor = color.rgb(0, 254, 21))
table.cell(t, 0, 2, txt, bgcolor = color.rgb(0, 254, 21))
print2(string txt) =>
var table t = table.new(position.top_right, 1, 1)
table.cell(t, 0, 0, txt, bgcolor = color.rgb(246, 4, 4))
newLoss = (strategy.losstrades > strategy.losstrades[1]) and (strategy.wintrades == strategy.wintrades[1]) and (strategy.eventrades == strategy.eventrades[1])
var streakLenloss = 0
var lossnum = 0
if (newLoss)
streakLenloss := streakLenloss + 1
else
if (strategy.wintrades > strategy.wintrades[1])
streakLenloss := 0
else
streakLenloss := streakLenloss
if ( streakLenloss>= 1)// or streakLenloss == 4 or streakLenloss == 8......
lossnum := lossnum+1
b = lossnum
print2(str.tostring(b))
</code></pre>
<p>`</p>
<p>Previously, I used the conditions below to calculate the total number of two consecutive losses, but when I tested the reliability of the last if statement with the above condition, it generated more losses than the total number of trades.</p>
<p><code>if ( streakLenloss== 2 or streakLenloss == 4 or streakLenloss == 6 or streakLenloss == 8 or streakLenloss == 10)</code></p>
|
[
{
"answer_id": 74506469,
"author": "Chayim Friedman",
"author_id": 7884305,
"author_profile": "https://Stackoverflow.com/users/7884305",
"pm_score": 3,
"selected": true,
"text": "#[cfg(test)] #[cfg] #[test] #[cfg(test)]"
},
{
"answer_id": 74506481,
"author": "Nikolay Zakirov",
"author_id": 9023490,
"author_profile": "https://Stackoverflow.com/users/9023490",
"pm_score": 2,
"selected": false,
"text": "#[cfg(test)] #[test] test_helper mod tests cargo test"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18070351/"
] |
74,506,325
|
<p>I'm currently facing the problem of not being able to print the last longest string.
Strings example:</p>
<pre><code>banica
pizza
kiufte
</code></pre>
<p>The first and the third are same length, but I want the last longest string.</p>
<pre><code>def longest(list1):
longest_list = max(len(elem) for elem in list1)
return longest_list
somelist=[]
while True:
s = input()
if s == "END":
break
somelist.append(s)
longest_string = max(somelist, key=len)
print(longest_string)
</code></pre>
|
[
{
"answer_id": 74506348,
"author": "Ni3dzwi3dz",
"author_id": 12768056,
"author_profile": "https://Stackoverflow.com/users/12768056",
"pm_score": 3,
"selected": false,
"text": "longest_string = max(somelist, key=len)\n longest_string = max(somelist[::-1], key=len)\n"
},
{
"answer_id": 74506415,
"author": "Jaydip Bhadane",
"author_id": 20552979,
"author_profile": "https://Stackoverflow.com/users/20552979",
"pm_score": 0,
"selected": false,
"text": " def longest(list1):\n longest_list = max(len(elem) for elem in list1)\n return longest_list\nsomelist=[]\nwhile True:\n\n s = input()\n\n if s == \"END\":\n break\n somelist.append(s)\nlongest_string = max(somelist[::-1], key=len)\nprint(longest_string)\n"
},
{
"answer_id": 74506431,
"author": "MarianD",
"author_id": 7023590,
"author_profile": "https://Stackoverflow.com/users/7023590",
"pm_score": 0,
"selected": false,
"text": "longest() longest_length = longest(somelist)\nlongest_string = [s for s in somelist if len(s) == longest_length][-1]\n [-1]"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20439276/"
] |
74,506,360
|
<p>Using Angular, I'm trying to get data from an API. The GET request seems to be successful because, when I display the GET result in the console view, I can see that I'm getting an array of the right size and with the correct values. The issue is that, when I try to read a single data from an array element, it is undefined.</p>
<pre><code>export class Achat {
constructor(
public IDAchat_PK: number,
public Date: Date,
public Fournisseur: string,
public FraisLivraison: string,
public status: number
) {}
}
</code></pre>
<pre><code>export class DbService {
/* Back end URL */
public Back_End_Url = "https://localhost:7198/pokegong/";
constructor(private httpClient: HttpClient) { }
public GetAchats(): Observable<Achat> {
return this.httpClient.get<Achat>(this.Back_End_Url + "Achat");
}
}
</code></pre>
<pre><code>export class StockComponent implements OnInit {
achats: Achat[] = [];
constructor(private dbService: DbService) {
}
ngOnInit(): void {
console.log("app-stock is initializing");
this.GetAchats();
}
GetAchats() {
/* Get stock items from Back End and fill _stock_items*/
return this.dbService.GetAchats().subscribe((data: {}) => {
this.achats = data;
console.log(this.achats[3])
console.log(this.achats[3].Fournisseur)
});
}
}
</code></pre>
<p>Upon execution of console.log(this.achats[3]), I can see in the console the text
{idAchat_PK: 4, date: '2022-10-05T00:00:00', fournisseur: 'VISTAPRINT', fraisLivraison: 6.19, status: 2}</p>
<p>However, upon execution of console.log(this.achats[3].Fournisseur), I get the 'undefined' value.</p>
<p>All my workaround was not successful. I really don't understand how I can be able to read a full JSON record, but not a single element within this record.</p>
<p>Many thanks for your help.</p>
|
[
{
"answer_id": 74506659,
"author": "Flo",
"author_id": 4472932,
"author_profile": "https://Stackoverflow.com/users/4472932",
"pm_score": 0,
"selected": false,
"text": "console.log(this.achats[3].fournisseur) const convertedResult = this.achats.map((data) => {return new Achat(.....);})"
},
{
"answer_id": 74506745,
"author": "Avraham Weinstein",
"author_id": 8938503,
"author_profile": "https://Stackoverflow.com/users/8938503",
"pm_score": 2,
"selected": false,
"text": "Fournisseur fournisseur"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13362005/"
] |
74,506,413
|
<p>I have been following <a href="https://stackoverflow.com/questions/69899955/problem-in-redirecting-programmatically-to-a-route-in-react-router-v6">this answer</a> to get redirection functionality added to a <code>React</code> project I have been working on.</p>
<p>I have a class that is currently extended by several other classes; this parent class currently extends <code>React.Component</code>:</p>
<pre class="lang-javascript prettyprint-override"><code>class LoginForm extends Form {
...
}
export default LoginForm;
</code></pre>
<pre class="lang-javascript prettyprint-override"><code>class Form extends React.Component {
...
...
}
export default withRouter(Form);
</code></pre>
<p>This was working fine until I added this <code>withRouter</code> functionality on the component. I am now presented with the following error when the page loads:</p>
<pre class="lang-shellsession prettyprint-override"><code>Login.js:8 Uncaught TypeError: Class extends value props => {
_s();
const params = (0,react_router_dom__WEBPACK_IMPORTED_MODULE_2__.useParams)();
cons...<omitted>... } is not a constructor or null
at ./src/pages/Forms/Auth/Login.js (Login.js:8:1)
</code></pre>
<p>The code for wrapping the class export is:</p>
<pre class="lang-javascript prettyprint-override"><code>const withRouter = Wrapper => props => {
const params = useParams();
const navigate = useNavigate();
return (
<Wrapper
{...props}
navigate={navigate}
params={params}
/>
)
}
export default withRouter;
</code></pre>
<p>What do I need to do to be able to inherit this class? I do not want to refactor the whole site to use functional components, but we are using Router V6 - and I understand that using the hook is necessary. Is there a way to inject the property higher up to make this work?</p>
|
[
{
"answer_id": 74506659,
"author": "Flo",
"author_id": 4472932,
"author_profile": "https://Stackoverflow.com/users/4472932",
"pm_score": 0,
"selected": false,
"text": "console.log(this.achats[3].fournisseur) const convertedResult = this.achats.map((data) => {return new Achat(.....);})"
},
{
"answer_id": 74506745,
"author": "Avraham Weinstein",
"author_id": 8938503,
"author_profile": "https://Stackoverflow.com/users/8938503",
"pm_score": 2,
"selected": false,
"text": "Fournisseur fournisseur"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/655667/"
] |
74,506,454
|
<p>I build a scraper where the scraped data gets compared with already existing data to avoid duplicates, create new entries and update old entries. I'm doing this with a for loop, which loops over a findOne function where are two awaits in. The problem is that my for loop is ignoring (because it's sync?) my awaits and goes over to a part, where it is important that all of these awaits are done.</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>async function comparedata(length) {
console.log("Starting comparing entries in data");
for (let x = 0; x < length; x++) {
const model = new dataModel({
link: dataLinks[x],
name: dataGames[x].replace('Download', ' '),
logo: dataLogos[x],
provider: 'data',
});
model.collection.findOne({ "link": dataLinks[x] }, async function (err, found) {
if (err) throw err;
if (found == null) {
await model.save().then((result) => {
console.log(result) // Is not happening because the for loop goes through to the next function and closes the server
}).catch((err) => { console.log(err) });
}
else if (found != null) {
if (dataGames[x] != found.name) {
await model.collection.findOneAndUpdate({ link: dataLinks[x] }, { $set: { name: dataGames[x] } });
}
}
})
}
closeServer()//Closes the server is happening before new entries or updates are made.
}</code></pre>
</div>
</div>
</p>
<p>My idea was to work with promises, but even if I tried to, it was just getting resolved too fast and closes the server again.</p>
|
[
{
"answer_id": 74506592,
"author": "Jordan Wright",
"author_id": 17097798,
"author_profile": "https://Stackoverflow.com/users/17097798",
"pm_score": 1,
"selected": false,
"text": "const found = await new Promise((resolve, reject) => {\n model.collection.findOne({ \"link\": dataLinks[x] }, function (err, found) {\n if (err) {\n reject(err);\n return;\n };\n resolve(found);\n }\n});\n"
},
{
"answer_id": 74506695,
"author": "lpizzinidev",
"author_id": 13211263,
"author_profile": "https://Stackoverflow.com/users/13211263",
"pm_score": 2,
"selected": false,
"text": "async function comparedata(length) {\n console.log('Starting comparing entries in data');\n try {\n for (let x = 0; x < length; x++) {\n let found = await dataModel.findOne({ link: dataLinks[x] });\n if (!found) {\n found = await dataModel.create({\n link: dataLinks[x],\n name: dataGames[x].replace('Download', ' '),\n logo: dataLogos[x],\n provider: 'data',\n });\n } else if (found.name !== dataGames[x]) {\n found.name = dataGames[x];\n await found.save();\n }\n console.log(found);\n }\n } catch (e) {\n console.log(e);\n }\n \n closeServer(); \n}\n"
},
{
"answer_id": 74506775,
"author": "Soorya J",
"author_id": 18576371,
"author_profile": "https://Stackoverflow.com/users/18576371",
"pm_score": 2,
"selected": true,
"text": "async function comparedata(length) {\n console.log(\"Starting comparing entries in data\");\n for (let x = 0; x < length; x++) {\n const model = new dataModel({\n link: dataLinks[x],\n name: dataGames[x].replace('Download', ' '),\n logo: dataLogos[x],\n provider: 'data',\n\n });\n // using .exec() at the end allows us to go with the promise way of dealing things rather than callbacks\n // assuming that 'dataModel' is the Schema, so I directly called findOne on it\n const found = await dataModel.findOne({ \"link\": dataLinks[x] }).exec();\n\n if (found == null) {\n // wrap the await in try...catch for catching errors while saving\n try{\n await model.save();\n console.log(\"Document Saved Successfully !\");\n }catch(err) {\n console.log(`ERROR while saving the document. DETAILS: ${model} & ERROR: ${err}`) \n }\n } else if (found != null) {\n if (dataGames[x] != found.name) {\n await model.collection.findOneAndUpdate({ link: dataLinks[x] }, { $set: { name: dataGames[x] } });\n }\n }\n\n if (x > length)\n sendErrorMail();\n }\n closeServer()//Closes the server is happening before new entries or updates are made. \n}\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20136915/"
] |
74,506,455
|
<p>The update is working fine, but stock value when is purchased I want to show messagebox, and stop the purchase when the value is zero in the stock update code.</p>
<p>I tried this code, but he only reduces value if the quantity is zero showing minus in the stock value when to stop when the value is equal to zero.</p>
<pre><code>private void updateQty()
{
try
{
int newqty = stock - Convert.ToInt32(txtnumberofunit.Text);
con.Open();
SqlCommand cmd = new SqlCommand("Update medic Set quantity=@q where id=@Xkey ", con);
//stock=Convert.ToInt32(dr)
cmd.Parameters.AddWithValue("@q", newqty);
cmd.Parameters.AddWithValue("@Xkey", key);
cmd.ExecuteNonQuery();
MessageBox.Show("Medicine updated!!");
con.Close();
//showExpenses();
//Reset();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
</code></pre>
|
[
{
"answer_id": 74506592,
"author": "Jordan Wright",
"author_id": 17097798,
"author_profile": "https://Stackoverflow.com/users/17097798",
"pm_score": 1,
"selected": false,
"text": "const found = await new Promise((resolve, reject) => {\n model.collection.findOne({ \"link\": dataLinks[x] }, function (err, found) {\n if (err) {\n reject(err);\n return;\n };\n resolve(found);\n }\n});\n"
},
{
"answer_id": 74506695,
"author": "lpizzinidev",
"author_id": 13211263,
"author_profile": "https://Stackoverflow.com/users/13211263",
"pm_score": 2,
"selected": false,
"text": "async function comparedata(length) {\n console.log('Starting comparing entries in data');\n try {\n for (let x = 0; x < length; x++) {\n let found = await dataModel.findOne({ link: dataLinks[x] });\n if (!found) {\n found = await dataModel.create({\n link: dataLinks[x],\n name: dataGames[x].replace('Download', ' '),\n logo: dataLogos[x],\n provider: 'data',\n });\n } else if (found.name !== dataGames[x]) {\n found.name = dataGames[x];\n await found.save();\n }\n console.log(found);\n }\n } catch (e) {\n console.log(e);\n }\n \n closeServer(); \n}\n"
},
{
"answer_id": 74506775,
"author": "Soorya J",
"author_id": 18576371,
"author_profile": "https://Stackoverflow.com/users/18576371",
"pm_score": 2,
"selected": true,
"text": "async function comparedata(length) {\n console.log(\"Starting comparing entries in data\");\n for (let x = 0; x < length; x++) {\n const model = new dataModel({\n link: dataLinks[x],\n name: dataGames[x].replace('Download', ' '),\n logo: dataLogos[x],\n provider: 'data',\n\n });\n // using .exec() at the end allows us to go with the promise way of dealing things rather than callbacks\n // assuming that 'dataModel' is the Schema, so I directly called findOne on it\n const found = await dataModel.findOne({ \"link\": dataLinks[x] }).exec();\n\n if (found == null) {\n // wrap the await in try...catch for catching errors while saving\n try{\n await model.save();\n console.log(\"Document Saved Successfully !\");\n }catch(err) {\n console.log(`ERROR while saving the document. DETAILS: ${model} & ERROR: ${err}`) \n }\n } else if (found != null) {\n if (dataGames[x] != found.name) {\n await model.collection.findOneAndUpdate({ link: dataLinks[x] }, { $set: { name: dataGames[x] } });\n }\n }\n\n if (x > length)\n sendErrorMail();\n }\n closeServer()//Closes the server is happening before new entries or updates are made. \n}\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20552904/"
] |
74,506,485
|
<p><a href="https://practice-project-html-css.vercel.app/#project" rel="nofollow noreferrer">https://practice-project-html-css.vercel.app/#project</a></p>
<p>I'm talking about "PROJECTS".</p>
<p>When you hover there, it shows some text. How do I make it?</p>
<p>Like this: <a href="https://imgur.com/a/N86uRpP" rel="nofollow noreferrer">https://imgur.com/a/N86uRpP</a></p>
<p>HTML:</p>
<pre><code><div class="grid-container">
<div class="one"><img src="project1.png" alt="" /></div>
<div class="two"><img src="Project2.png" alt="" /></div>
<div class="three"><img src="project3.png" alt="" /></div>
<div class="four"><img src="project4.png" alt="" /></div>
<div class="five"><img src="project5.png" alt="" /></div>
<div class="six"><img src="project6.png" alt="" /></div>
<div class="seven"><img src="project7.png" alt="" /></div>
<div class="eight"><img src="project8.png" alt="" /></div>
<div class="nine"><img src="project9.png" alt="" /></div>
</div>
</code></pre>
<p>CSS:</p>
<pre><code>.grid-container{
display:grid;
grid-template-columns:1fr 1fr 1fr;
gap:40px;
}
</code></pre>
|
[
{
"answer_id": 74506572,
"author": "Cihan Kalmaz",
"author_id": 4430438,
"author_profile": "https://Stackoverflow.com/users/4430438",
"pm_score": 0,
"selected": false,
"text": "https://codepen.io/francisco-kataldo/pen/LBBryV https://ordinarycoders.com/blog/article/codepen-bootstrap-card-hovers\n"
},
{
"answer_id": 74506622,
"author": "Rokit",
"author_id": 996314,
"author_profile": "https://Stackoverflow.com/users/996314",
"pm_score": 2,
"selected": true,
"text": "overflow position overflow-y: hidden; bottom position: absolute; transition .image-container {\n position: relative;\n color: white;\n background-color: #888;\n height: 100px;\n padding: 10px;\n overflow-y: hidden;\n}\n\n.image-container:hover .container-text {\n bottom: 0px;\n}\n\n.container-text {\n position: absolute;\n bottom: -60px;\n left: 0;\n transition: bottom 200ms;\n text-align: center;\n padding: 10px;\n background-color: #444;\n width: 100%;\n box-sizing: border-box;\n} <div class=\"image-container\">\n Hover me\n <div class=\"container-text\">Message</div>\n</div>"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19901123/"
] |
74,506,504
|
<p>Basically I want to destruct this object to get this result but in the console I see <code>u is not defined</code></p>
<p>The object:</p>
<pre><code>const game =
releases: {
"Oath In Felghana": ["USA", "Japan"],
};`
</code></pre>
<p>My code:</p>
<pre><code>const {
releases: {
"Oath In Felghana": o = [u, j],
} = game;
console.log(`My Best Release Is ${o} It Released in ${u} & ${j}`);
</code></pre>
<p>What I want to see</p>
<blockquote>
<p>My Best Release Is Oath In Felghana It Released in USA & Japan</p>
</blockquote>
<p>what I get</p>
<blockquote>
<p>Uncaught ReferenceError: u is not defined</p>
</blockquote>
<p>So the problem is that it shows me that you is undefined even though I used array destructuring to destruct it</p>
<p>It's mentioned in the task that you need to use key and values, so I tried to put this between the object and my destructuring</p>
<pre><code>game.releases["Oath In Felghana"] = Object.keys(game.releases["Oath In Felghana"]);
</code></pre>
<p>but still doesn't work.</p>
|
[
{
"answer_id": 74506572,
"author": "Cihan Kalmaz",
"author_id": 4430438,
"author_profile": "https://Stackoverflow.com/users/4430438",
"pm_score": 0,
"selected": false,
"text": "https://codepen.io/francisco-kataldo/pen/LBBryV https://ordinarycoders.com/blog/article/codepen-bootstrap-card-hovers\n"
},
{
"answer_id": 74506622,
"author": "Rokit",
"author_id": 996314,
"author_profile": "https://Stackoverflow.com/users/996314",
"pm_score": 2,
"selected": true,
"text": "overflow position overflow-y: hidden; bottom position: absolute; transition .image-container {\n position: relative;\n color: white;\n background-color: #888;\n height: 100px;\n padding: 10px;\n overflow-y: hidden;\n}\n\n.image-container:hover .container-text {\n bottom: 0px;\n}\n\n.container-text {\n position: absolute;\n bottom: -60px;\n left: 0;\n transition: bottom 200ms;\n text-align: center;\n padding: 10px;\n background-color: #444;\n width: 100%;\n box-sizing: border-box;\n} <div class=\"image-container\">\n Hover me\n <div class=\"container-text\">Message</div>\n</div>"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19850116/"
] |
74,506,505
|
<p>I want a select query that fills the null values in column 2 [Tags.1] with the distinct value from column 1 [ResourcesUD]</p>
<pre><code>The given table:
ReourceID [Tags.1]
1x ws
2x NULL
1x ws
3x qs
2x sg
4x ee
3x NULL
4x NULL
2x sg
</code></pre>
<p>The expected result:</p>
<pre><code>ReourceID [Tags.1]
1x ws
2x sg
1x ws
3x qs
2x sg
4x ee
3x qs
4x ee
2x sg
</code></pre>
|
[
{
"answer_id": 74506553,
"author": "Iynga Iyngaran Iyathurai",
"author_id": 9348637,
"author_profile": "https://Stackoverflow.com/users/9348637",
"pm_score": 0,
"selected": false,
"text": "SELECT DISTINCT ResourceID, Tags.1 FROM table WHERE Tags.1 IS NULL\n"
},
{
"answer_id": 74506613,
"author": "masoud rafiee",
"author_id": 4256602,
"author_profile": "https://Stackoverflow.com/users/4256602",
"pm_score": 2,
"selected": true,
"text": " SELECT ResourceID, isnull(Tags.1, select top 1 b.ResourceID from\n table b where b.ResourceID=a.ResourceID) FROM table a\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1264054/"
] |
74,506,516
|
<p>When I add a product to my cart(for the first time), <code>action.payload.count = 1;</code> works fine in my slice.
But when I clear my cart(added item is removed), and again add that(the same product), I get this error in the console and item doesn't add to the cart:</p>
<p><code>Uncaught TypeError: "count" is read-only addToCart CartSlice.js:13</code></p>
<p>It doesn't have any error when I add a new product(it's not removed before).</p>
<p>Why are products added correctly the first time, but not added again after deletion?</p>
<p><code>cartSlice.js</code></p>
<pre><code>export const CartSlice = createSlice({
name: "cart",
initialState: [],
reducers: {
addToCart(state, action){
const existIndex = state.findIndex(item => item.shortName === action.payload.shortName);
if(existIndex !== -1){
state[existIndex].count += 1;
}
else{
action.payload.count = 1;
state.push(action.payload);
}
},
clearCart(state, action){
return state=[];
}
}
})
</code></pre>
<p><code>card.js</code></p>
<pre><code>export const Card = ({product, showProductSlide}) => {
const dispatch = useDispatch();
const addToCart = () => {
dispatch({type: "cart/addToCart", payload: product})
}
return(
<div className="card item border-0 overflow-hidden">
<div className="img-box">
<img src={product.pic} className="card-img-top" alt="..." />
<div className="triangle"></div>
</div>
<div className="card-body d-flex flex-column justify-content-between bg-secondary text-white">
<p className="card-text">{product.shortName}</p>
<p className="card-text text-end fw-bold">{product.price}</p>
<div className="d-flex justify-content-between">
<button className="btn btn-sm bg-transparent text-white" onClick={showProductSlide}><span className="q-mark me-1">?</span>Quick-view</button>
<button className="btn btn-sm bg-transparent btn-cart text-nowrap" onClick={addToCart}>Add to cart<div><span>+</span></div></button>
</div>
</div>
</div>
)
}
</code></pre>
<p><code>cartList.js</code></p>
<pre><code>export const CartList = ({showCart, cartProducts}) => {
const dispatch = useDispatch();
const totalPrices = () => {
let total = 0;
cartProducts.forEach(function (value){
total += Number(value.price.replace(/[$]/, "")) * value.count;
})
return total.toFixed(2);
}
const clearCart = () => {
dispatch({type: "cart/clearCart", payload: ""})
}
return(
<div className={showCart ? "open-list" : "close-list"}>
{cartProducts.length === 0 ?
<span className="align-self-center">empty</span> :
<>
<ul>
{cartProducts.map((item, index) => {
return(
<li className="d-flex justify-content-between" key={index}>
<span>{item.shortName}</span><span>{item.count}</span>
</li>
)
}
)}
</ul>
<p className="total-price">Total Amounts: {totalPrices()}</p>
<button onClick={clearCart}>Cancel order</button>
</>
}
</div>
)
}
</code></pre>
<p>Link to output: <a href="https://eloquent-kashata-a64506.netlify.app/" rel="nofollow noreferrer">https://eloquent-kashata-a64506.netlify.app/</a></p>
<p>Please do these: Click <code>add to cart</code>, then clear cart, and again add the same product.</p>
|
[
{
"answer_id": 74506553,
"author": "Iynga Iyngaran Iyathurai",
"author_id": 9348637,
"author_profile": "https://Stackoverflow.com/users/9348637",
"pm_score": 0,
"selected": false,
"text": "SELECT DISTINCT ResourceID, Tags.1 FROM table WHERE Tags.1 IS NULL\n"
},
{
"answer_id": 74506613,
"author": "masoud rafiee",
"author_id": 4256602,
"author_profile": "https://Stackoverflow.com/users/4256602",
"pm_score": 2,
"selected": true,
"text": " SELECT ResourceID, isnull(Tags.1, select top 1 b.ResourceID from\n table b where b.ResourceID=a.ResourceID) FROM table a\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17007184/"
] |
74,506,559
|
<p>I have two components - Contacts and ContactItem. In Contacts There is a div in which contacts are displayed and the "Add" button. In ContactItem there is a select with a choice of social network, textarea where you enter your number or nickname in the social network, the delete button. I need to implement the ability to remove and add new items</p>
<p>Now the problem is that I have an infinite number of renders when I click on the add button. How can it be fixed?
<a href="https://i.stack.imgur.com/uQ4vy.png" rel="nofollow noreferrer">enter image description here</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const Contacts = () => {
const [contactItems, setContactItems] = useState([
{
index: 0,
key: 0,
id: 0,
},
]);
const addItemHandler = (event) => {
event.preventDefault();
const id = uuidv4();
setContactItems(() => [
...contactItems,
{
index: contactItems.length,
key: id,
id,
},
]);
};
const removeItemHandler = (id) => {
setContactItems((contactItems) =>
contactItems.filter((el) => el.id !== id)
);
};
return (
<>
<div className={stylesCenter.channels}>
{contactItems.map((item) => (
<ContactItem
index={item.index}
key={item.key}
id={item.id}
removeItem={removeItemHandler}
/>
))}
</div>
<div>
<button
onClick={addItemHandler}
>
<img src="plus.svg" alt="plus logo" />
</button>
</div>
</>
);
};</code></pre>
</div>
</div>
</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 ContactItem = ({ index, removeItem }) => {
console.log("child render", index);
return (
<div className={stylescenter.fullChannelControll}>
<select className={stylescenter.selecterOptions} name="optionSelected">
{options.map((el) => (
<option key={el.value} value={el.value}>
{el.label}
</option>
))}
</select>
<div className={stylescenter.detailsAndInputAndDelete}>
<textarea
maxLength="100"
rows="2"
/>
<div className={stylescenter.removeButtons}>
{index !== 0 && (
<span>
<IconButton onClick={removeItem(index)}>
<img src="bin.svg" alt="bin logo" />
</IconButton>
</span>
)}
</div>
</div>
</div>
);
};</code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74506553,
"author": "Iynga Iyngaran Iyathurai",
"author_id": 9348637,
"author_profile": "https://Stackoverflow.com/users/9348637",
"pm_score": 0,
"selected": false,
"text": "SELECT DISTINCT ResourceID, Tags.1 FROM table WHERE Tags.1 IS NULL\n"
},
{
"answer_id": 74506613,
"author": "masoud rafiee",
"author_id": 4256602,
"author_profile": "https://Stackoverflow.com/users/4256602",
"pm_score": 2,
"selected": true,
"text": " SELECT ResourceID, isnull(Tags.1, select top 1 b.ResourceID from\n table b where b.ResourceID=a.ResourceID) FROM table a\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20553149/"
] |
74,506,568
|
<p>John is in a big city and he sees an area of buildings. make a program that will print the number of buildings that are visible by John if he is seeing from the west. The building(s) are only visible if it's not blocked by another buildings that are higher on the same height.</p>
<p>Format Input:</p>
<p>First line, input N which is the size of the area. Afterwards the user will input N x N the heights of the buildings.</p>
<p>Output:</p>
<p>The output will be the number of buildings that are visible.</p>
<p>Sample Input(1):</p>
<p>3</p>
<p>1 2 3</p>
<p>2 1 3</p>
<p>3 1 2</p>
<p>Sample Output(1):</p>
<p>3 | 1 2 3</p>
<p>2 | 2 1 3</p>
<p>1 | 3 1 2</p>
<p>Sample Input(2):</p>
<p>5</p>
<p>8 4 3 2 1</p>
<p>1 1 1 1 1</p>
<p>4 1 3 2 5</p>
<p>2 1 2 5 3</p>
<p>1 1 2 4 2</p>
<p>Sample Output(2):</p>
<p>1 | 8 4 3 2 1</p>
<p>1 | 1 1 1 1 1</p>
<p>2 | 4 1 3 2 5</p>
<p>2 | 2 1 2 5 3</p>
<p>3 | 1 1 2 4 2</p>
<p>This is my current code, it's unfinished</p>
<pre><code>#include <stdio.h>
int main()
{
int n;
scanf("%d", &n);
int building[n][n];
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
scanf("%d", &building[i][j]);
}
}
int max = 0;
int count = 0;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
if(building[i][j] > max)
{
count++;
max = building[i][j];
}
}
}
for(int i = 0; i < n; i++)
{
printf("%d |", count);
for(int j = 0; j < n; j++)
{
printf(" %d", building[i][j]);
}
puts("");
}
return 0;
}
</code></pre>
<p>What should I do next? or is the whole code wrong?</p>
|
[
{
"answer_id": 74506553,
"author": "Iynga Iyngaran Iyathurai",
"author_id": 9348637,
"author_profile": "https://Stackoverflow.com/users/9348637",
"pm_score": 0,
"selected": false,
"text": "SELECT DISTINCT ResourceID, Tags.1 FROM table WHERE Tags.1 IS NULL\n"
},
{
"answer_id": 74506613,
"author": "masoud rafiee",
"author_id": 4256602,
"author_profile": "https://Stackoverflow.com/users/4256602",
"pm_score": 2,
"selected": true,
"text": " SELECT ResourceID, isnull(Tags.1, select top 1 b.ResourceID from\n table b where b.ResourceID=a.ResourceID) FROM table a\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20196675/"
] |
74,506,569
|
<pre><code>ProductName | display | final value
Lewis No
Lewis No
Lewis No
Sood No
Henny Yes
Henny No
Henny No
</code></pre>
<p>1.Looking for a formula in excel where if product have display value as yes with same product name then final value should come as yes and other should come as variant.
2.else if the product have display value no for all products with same name then it should come as not displayed.</p>
<p>Final output should be</p>
<pre><code>ProductName | display | final value
Lewis No. Not display
Lewis No. Not display
Lewis No. Not display
Sood No. Not display
Henny Yes. Yes
Henny No. Variant
Henny No. Variant
</code></pre>
<p>Tried with if and count if but not able to find not displayed logic</p>
|
[
{
"answer_id": 74506637,
"author": "Harun24hr",
"author_id": 5514747,
"author_profile": "https://Stackoverflow.com/users/5514747",
"pm_score": 2,
"selected": true,
"text": "=LET(x,CONCAT(UNIQUE(FILTER($B$2:$B2,$A$2:$A2=A2))),IF(x=\"No\",\"Not Display\",IF(x=\"Yes\",\"Yes\",\"Variant\")))\n"
},
{
"answer_id": 74506880,
"author": "P.b",
"author_id": 12634230,
"author_profile": "https://Stackoverflow.com/users/12634230",
"pm_score": 0,
"selected": false,
"text": "=LET(range,A1:B8,\n r,ROWS(range),\n name,TAKE(range,1-r,1),\n display,TAKE(range,1-r,-1),\nDROP(REDUCE(0, SEQUENCE(r-1,),\n LAMBDA(x, y, \n VSTACK(x,\n IF( \n ISNUMBER(XMATCH(INDEX(name,y)&\"Yes\",name&display)), \n IF(INDEX(display,y)=\"Yes\",\n \"Yes\",\n \"Variant\"),\n \"No display\")))),\n 1))\n =IF(COUNTIFS($A$2:$A$8,A2,$B$2:$B$8,\"Yes\"),IF(B2=\"Yes\",\"Yes\",\"Variant\"),\"Not display\") Yes Not display Yes Yes Variant"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20552995/"
] |
74,506,590
|
<p>I was interviewed for a position and was asked this question. Obviously, I did not have an answer hence seeking help from you guys.</p>
<p>What I was asked:</p>
<blockquote>
<p>Create a generic loader screen that mimics form structure of the child component, so that instead of showing a spinner, we show an animated skeleton of the content to be loaded.</p>
</blockquote>
<p>My idea was to clone the structure manually and animate it. This works fine but this will only work for 1 form. So question is, how can we do this?</p>
<p><strong>Ideas I thought might work:</strong></p>
<ol>
<li>We can maybe mimic props to have a blank render and use it as a loader. Then we only need to animate the form, which we might be able to do using css. Issues with this approach would be,
<ul>
<li>We do not know what elements are there to animate</li>
<li>If we use redux and use <code>useSelector</code>, it will break</li>
</ul>
</li>
<li>We can look into HOC. This way we know what component will be rendered. However, same issues apply here.</li>
<li>Maybe we can look into inheritance or react portals or string manipulation for some hacky way but this is half cooked idea.</li>
</ol>
<p>Here is the sample <a href="https://jsfiddle.net/exayo5hd/" rel="nofollow noreferrer">JSFiddle</a> to show animation.</p>
<p>The place I'm stuck is, how to get the markup of the component? Most real components will use props and might break if not available.</p>
|
[
{
"answer_id": 74523599,
"author": "RubenSmn",
"author_id": 20088324,
"author_profile": "https://Stackoverflow.com/users/20088324",
"pm_score": 1,
"selected": false,
"text": "SkeletonWrapper isLoading Skeleton const SkeletonWrapper = ({ children, isLoading }) => {\n if (!children) return null;\n if (!isLoading) return <>{children}</>;\n\n // if the components are wrapped in a Fragment replace children with the children from the Fragment\n if (children.type === React.Fragment) children = children.props.children;\n\n return children.map((child, idx) => <Skeleton key={idx}>{child}</Skeleton>);\n};\n Skeleton clone children visibilty: \"hidden\" spacing margin Skeleton br Skeleton const Skeleton = ({ children }) => {\n if (children.type === \"br\") return null;\n\n const clone = React.cloneElement(children, {\n style: { ...children.props.style, visibility: \"hidden\", margin: 0 },\n });\n\n return (\n <div\n style={{\n background:\n \"linear-gradient(90deg, lightgray 45%, #ddd 55%, lightgray 100%)\",\n backgroundSize: \"200% 200%\",\n animation: \"pulse 1.5s ease-in-out 0.5s infinite\",\n borderRadius: \"12px\",\n margin: children.props.style?.margin ?? \"0\",\n width: \"fit-content\",\n }}\n >\n {clone}\n </div>\n );\n};\n Skeleton fit-content flex"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3783478/"
] |
74,506,602
|
<p>Here is my code example, stripped a majority of the URLs and code inside them to make it easier to read <a href="https://pastebin.com/DBQrjJ8F" rel="nofollow noreferrer">https://pastebin.com/DBQrjJ8F</a></p>
<p>Is there a better way to handle the routing of the URLs, to trigger the respective functions for each URL?</p>
<p>I've tried the code example above and Splitting the Absolute URL by / but I was not sure where to go from there. Any code examples or explanations etc would be greatly appreciated</p>
<p>I don't write c# a lot so please forgive me if I'm missing something obvious</p>
<pre><code>if((inputRequest.HttpMethod == "POST") && (inputRequest.Url.AbsolutePath == "/API/Auth"))
{
Auth();
}
else if((inputRequest.HttpMethod == "GET") && (inputRequest.Url.AbsolutePath == "/API/Shutdown"))
{
Shutdown();
}
else if((inputRequest.HttpMethod == "POST") && (inputRequest.Url.AbsolutePath == "/API/Script/Exec"))
{
ScriptExec();
}
else
{
SendBackUnknownURLMessage();
}
</code></pre>
|
[
{
"answer_id": 74523599,
"author": "RubenSmn",
"author_id": 20088324,
"author_profile": "https://Stackoverflow.com/users/20088324",
"pm_score": 1,
"selected": false,
"text": "SkeletonWrapper isLoading Skeleton const SkeletonWrapper = ({ children, isLoading }) => {\n if (!children) return null;\n if (!isLoading) return <>{children}</>;\n\n // if the components are wrapped in a Fragment replace children with the children from the Fragment\n if (children.type === React.Fragment) children = children.props.children;\n\n return children.map((child, idx) => <Skeleton key={idx}>{child}</Skeleton>);\n};\n Skeleton clone children visibilty: \"hidden\" spacing margin Skeleton br Skeleton const Skeleton = ({ children }) => {\n if (children.type === \"br\") return null;\n\n const clone = React.cloneElement(children, {\n style: { ...children.props.style, visibility: \"hidden\", margin: 0 },\n });\n\n return (\n <div\n style={{\n background:\n \"linear-gradient(90deg, lightgray 45%, #ddd 55%, lightgray 100%)\",\n backgroundSize: \"200% 200%\",\n animation: \"pulse 1.5s ease-in-out 0.5s infinite\",\n borderRadius: \"12px\",\n margin: children.props.style?.margin ?? \"0\",\n width: \"fit-content\",\n }}\n >\n {clone}\n </div>\n );\n};\n Skeleton fit-content flex"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3579834/"
] |
74,506,630
|
<p>If someone can help me before I go crazy.
I have a User Control who contains a ListBox
I would like to add a property for the SelectedItem to the UserControl, so the parent can get it.
So I used a DependencyProperty</p>
<p>UserControl (VersionList.xaml):</p>
<pre><code><UserControl
x:Class="PcVueLauncher.Controls.VersionsList"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:converters="clr-namespace:PcVueLauncher.Converters"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:PcVueLauncher.Controls"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
d:Background="white"
d:DesignHeight="450"
d:DesignWidth="800"
mc:Ignorable="d">
<FrameworkElement.Resources>
<ResourceDictionary>
<converters:BoolToVisibilityConverter x:Key="BoolToVisibilityConverter" />
</ResourceDictionary>
</FrameworkElement.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock
Grid.Row="0"
Padding="10"
Text="Versions" />
<ListBox
Grid.Row="1"
d:ItemsSource="{d:SampleData ItemCount=5}"
ItemsSource="{Binding Versions}"
SelectedItem="{Binding SelectedVersion}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="auto" />
</Grid.ColumnDefinitions>
<TextBlock
Grid.Column="0"
Margin="5,5,10,5"
Text="{Binding VersionName}" />
<Button
Grid.Column="1"
Padding="5"
Command="{Binding RemoveVersionCommand}"
Content="Remove"
Visibility="{Binding CanBeRemoved, Converter={StaticResource BoolToVisibilityConverter}}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</UserControl>
</code></pre>
<p>UserControl Associated ViewModel (VersionListViewModel)</p>
<pre><code>namespace PcVueLauncher.ViewModels.Controls
{
public class VersionsListViewModel : ViewModelBase
{
private List<VersionPcVue> _versions;
public List<VersionPcVue> Versions
{
get
{
return _versions;
}
set
{
_versions = value;
OnPropertyChanged(nameof(Versions));
}
}
private VersionPcVue _selectedVersion;
public VersionPcVue SelectedVersion
{
get
{
return _selectedVersion;
}
set
{
_selectedVersion = value;
OnPropertyChanged(nameof(SelectedVersion));
}
}
public ICommand RemoveVersionCommand { get; }
public VersionsListViewModel()
{
List<VersionPcVue> versionPcVues = new()
{
new VersionPcVue{VersionName="V15"},
new VersionPcVue{VersionName="V12"}
};
Versions = versionPcVues;
}
}
}
</code></pre>
<p>UserControl code behind (VersionList.cs):</p>
<pre><code>public partial class VersionsList : UserControl
{
public VersionsList()
{
InitializeComponent();
}
public VersionPcVue SelectedVersion
{
get { return (VersionPcVue)GetValue(SelectedVersionProperty); }
set { SetValue(SelectedVersionProperty, value); }
}
//Using a DependencyProperty as the backing store for SelectedVersion.This enables animation, styling, binding, etc...
public static readonly DependencyProperty SelectedVersionProperty =
DependencyProperty.Register("SelectedVersion",
typeof(VersionPcVue),
typeof(VersionsList),
new FrameworkPropertyMetadata(
defaultValue: null,
flags: FrameworkPropertyMetadataOptions.AffectsMeasure,
propertyChangedCallback: new PropertyChangedCallback(OnSelectionChanged)));
private static void OnSelectionChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
d.CoerceValue(SelectedVersionProperty);
}
}
// Register a dependency property with the specified property name,
// property type, owner type, property metadata, and callbacks.
public static readonly DependencyProperty SelectedVersionProperty = DependencyProperty.Register(
name: "SelectedVersion",
propertyType: typeof(VersionPcVue),
ownerType: typeof(VersionsList),
typeMetadata: new FrameworkPropertyMetadata(
defaultValue: null,
flags: FrameworkPropertyMetadataOptions.AffectsMeasure,
propertyChangedCallback: new PropertyChangedCallback(OnSelectionChanged)
));
private static void OnSelectionChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs e)
{
depObj.CoerceValue(SelectedVersionProperty);
}
</code></pre>
<p>In the HomeView which contains the UserControl, I have this :</p>
<pre><code><UserControl
x:Class="PcVueLauncher.Views.HomeView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Controls="clr-namespace:PcVueLauncher.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:PcVueLauncher.Views"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:system="clr-namespace:System;assembly=netstandard"
xmlns:viewmodels="clr-namespace:PcVueLauncher.ViewModels"
d:Background="White"
d:DataContext="{d:DesignInstance Type=viewmodels:HomeViewModel}"
d:DesignHeight="450"
d:DesignWidth="800"
mc:Ignorable="d">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="2*" />
</Grid.ColumnDefinitions>
<Controls:VersionsList
x:Name="test"
Grid.Column="0"
DataContext="{Binding VersionsListViewModel}"
SelectedVersion="{Binding DataContext.SelectedVersion, RelativeSource={RelativeSource FindAncestor, AncestorLevel=1, AncestorType={x:Type UserControl}}, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</Grid>
</UserControl>
</code></pre>
<p>And in the associated ViewModel (HomeViewModel)</p>
<pre><code> public class HomeViewModel : ViewModelBase
{
private IProjectService _projectService;
private VersionPcVue _selectedVersion;
public VersionPcVue SelectedVersion
{
get
{
return _selectedVersion;
}
set
{
_selectedVersion = value;
OnPropertyChanged(nameof(SelectedVersion));
}
}
private VersionPcVue _test1;
public VersionPcVue Test1
{
get
{
return _test1;
}
set
{
_test1 = value;
OnPropertyChanged(nameof(Test1));
}
}
private string _test;
public string Test
{
get
{
return _test;
}
set
{
_test = value;
OnPropertyChanged(nameof(Test));
}
}
private VersionsListViewModel versionsListViewModel;
public VersionsListViewModel VersionsListViewModel
{
get
{
return versionsListViewModel;
}
set
{
versionsListViewModel = value;
OnPropertyChanged(nameof(VersionsListViewModel));
}
}
public HomeViewModel(IProjectService projectService)
{
_projectService = projectService;
VersionsListViewModel = new();
}
}
</code></pre>
<p>When I change the selected item from my user control, nothing happens in the HomeViewModel.
I thought about a binding error, but to try, I changed this</p>
<pre><code> SelectedVersion="{Binding DataContext.SelectedVersionnnnnnn, RelativeSource={RelativeSource FindAncestor, AncestorLevel=1, AncestorType={x:Type Grid}}, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</code></pre>
<p>And Visual Studio tells me that the SelectedVersionnnnn does not exist in HomeViewModel.</p>
<p>Why can't I get back the Selected Item back to the SelectedVersion property of my HomeViewModel.</p>
<p>Thanks a lot for your help</p>
|
[
{
"answer_id": 74506767,
"author": "vernou",
"author_id": 2703673,
"author_profile": "https://Stackoverflow.com/users/2703673",
"pm_score": 1,
"selected": true,
"text": "VersionList.xaml <ListBox SelectedItem=\"{Binding SelectedVersion}\" ...\n ListBox.SelectedItem {DataContext}.SelectedVersion VersionList.SelectedVersion VersionsList.cs SelectedVersionProperty SelectedVersion VersionList.xaml <UserControl x:Class=\"PcVueLauncher.Controls.VersionsList\" />\n...\n <ListBox\n ...\n ItemsSource=\"{Binding Versions}\"\n SelectedItem=\"{Binding SelectedVersion}\">\n...\n</UserControl>\n ListBox.SelectedItem ListBox.DataContext.SelectedVersion ListBox.DataContext VersionsListViewModel ListBox.SelectedItem VersionsListViewModel.SelectedVersion HomeView VersionsListViewModel VersionList.DataContext <UserControl x:Class=\"PcVueLauncher.Views.HomeView\"\n...\n <Controls:VersionsList DataContext=\"{Binding VersionsListViewModel}\" />\n...\n</UserControl>\n HomeView.VersionsList.ListBox.SelectedItem HomeView.DataContext.VersionsListViewModel.SelectedVersion HomeView.DataContext HomeViewModel HomeView.VersionsList.ListBox.SelectedItem HomeViewModel.VersionsListViewModel.SelectedVersion HomeViewModel.SelectedVersion HomeViewModel.VersionsListViewModel.SelectedVersion HomeViewModel.SelectedVersion HomeViewModel.SelectedVersion HomeViewModel.VersionsListViewModel.SelectedVersion HomeViewModel.cs public class HomeViewModel : ViewModelBase\n{\n private VersionsListViewModel versionsListViewModel;\n public VersionsListViewModel VersionsListViewModel\n {\n get\n {\n return versionsListViewModel;\n }\n set\n {\n if(versionsListViewModel != null)\n versionsListViewModel.PropertyChanged -= VersionsListViewModel_PropertyChanged;\n versionsListViewModel = value;\n if(versionsListViewModel != null)\n versionsListViewModel.PropertyChanged += VersionsListViewModel_PropertyChanged;\n OnPropertyChanged(nameof(VersionsListViewModel));\n }\n }\n\n public VersionPcVue SelectedVersion\n {\n get\n {\n return versionsListViewModel.SelectedVersion;\n } \n set\n {\n versionsListViewModel.SelectedVersion = value;\n OnPropertyChanged(nameof(SelectedVersion));\n }\n }\n\n void VersionsListViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)\n {\n //Propagate the property changed SelectedVersion\n if(string.IsNullOrEmpty(e.PropertyName) || e.PropertyName == nameof(VersionsListViewModel.SelectedVersion))\n OnPropertyChanged(nameof(SelectedVersion));\n }\n}\n HomeViewModel.VersionsListViewModel.SelectedVersion HomeViewModel.SelectedVersion VersionsList.SelectedVersion ListBox.SelectedItem VersionsList.SelectedVersion SelectedVersion VersionList.cs public partial class VersionsList : UserControl\n{\n public VersionsList()\n {\n InitializeComponent();\n }\n\n public VersionPcVue SelectedVersion\n {\n get { return (VersionPcVue)GetValue(SelectedVersionProperty); }\n set { SetValue(SelectedVersionProperty, value); }\n }\n\n public static readonly DependencyProperty SelectedVersionProperty =\n DependencyProperty.Register(\n \"SelectedVersion\",\n typeof(VersionPcVue),\n typeof(VersionsList),\n new FrameworkPropertyMetadata(\n defaultValue: null,\n flags: FrameworkPropertyMetadataOptions.AffectsMeasure\n )\n );\n\n public List<VersionPcVue> Versions\n {\n get { return (List<VersionPcVue>)GetValue(VersionsProperty); }\n set { SetValue(VersionsProperty, value); }\n }\n \n public static readonly DependencyProperty VersionsProperty =\n DependencyProperty.Register(\n \"Versions\",\n typeof(List<VersionPcVue>),\n typeof(VersionsList),\n new FrameworkPropertyMetadata(\n defaultValue: null,\n flags: FrameworkPropertyMetadataOptions.AffectsMeasure\n )\n );\n}\n VersionList.xaml <UserControl x:Class=\"PcVueLauncher.Controls.VersionsList\" />\n...\n <ListBox\n ...\n ItemsSource=\"{Binding Versions}, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}\"\n SelectedItem=\"{Binding SelectedVersion, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}\">\n...\n</UserControl>\n {RelativeSource TemplatedParent} VersionsList <UserControl x:Class=\"PcVueLauncher.Views.HomeView\"\n...\n <Controls:VersionsList\n Versions=\"{Binding VersionsListViewModel.Versions}\" \n SelectedVersion=\"{Binding SelectedVersion}\"/>\n...\n</UserControl>\n VersionsListViewModel.SelectedVersion"
},
{
"answer_id": 74507608,
"author": "BionicCode",
"author_id": 3141792,
"author_profile": "https://Stackoverflow.com/users/3141792",
"pm_score": 2,
"selected": false,
"text": "DependencyObject.CoerceValue FrameworkPropertyMetadataOptions.AffectsMeasure ListBox.SelectedItem FrameworkPropertyMetadataOptions.BindsTwoWayByDefault Control DataContext DataContext DataContext DataContext ListBox.ItemsSource VersionsListViewModel.Versions VersionsItemsSource HomeView DataContext Binding DataContext UserControl FrameworkElement Binding.RelativeSource DataContext DataContext public partial class VersionsList : UserControl\n{\n public VersionPcVue SelectedVersionItem\n {\n get => (VersionPcVue)GetValue(SelectedVersionItemProperty); \n set => SetValue(SelectedVersionItemProperty, value); \n }\n \n public static readonly DependencyProperty SelectedVersionItemProperty = DependencyProperty.Register(\n \"SelectedVersionItem\",\n typeof(VersionPcVue),\n typeof(VersionsList),\n new FrameworkPropertyMetadata(default(VersionPcVue), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnSelectedVersionChanged));\n\n public IList VersionsItemsSource\n {\n get => (IList)GetValue(VersionsItemsSourceProperty); \n set => SetValue(VersionsItemsSourceProperty, value); \n }\n \n public static readonly DependencyProperty VersionsItemsSourceProperty = DependencyProperty.Register(\n \"VersionsItemsSource\",\n typeof(IList),\n typeof(VersionsList),\n new PropertyMetadata(default));\n\n public VersionsList()\n {\n InitializeComponent();\n }\n\n private static void OnSelectedVersionChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n { \n }\n}\n Control DataContext <UserControl>\n <FrameworkElement.Resources>\n <ResourceDictionary>\n <converters:BoolToVisibilityConverter x:Key=\"BoolToVisibilityConverter\" />\n </ResourceDictionary>\n </FrameworkElement.Resources>\n\n <Grid>\n <Grid.RowDefinitions>\n <RowDefinition Height=\"Auto\" />\n <RowDefinition Height=\"*\" />\n <RowDefinition Height=\"Auto\" />\n </Grid.RowDefinitions>\n <TextBlock\n Grid.Row=\"0\"\n Padding=\"10\"\n Text=\"Versions\" />\n <ListBox Grid.Row=\"1\"\n d:ItemsSource=\"{d:SampleData ItemCount=5}\"\n ItemsSource=\"{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=VersionsItemsSource}\"\n SelectedItem=\"{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=SelectedVersionItem}\">\n <ListBox.ItemTemplate>\n <DataTemplate>\n <Grid>\n <Grid.ColumnDefinitions>\n <ColumnDefinition Width=\"*\" />\n <ColumnDefinition Width=\"auto\" />\n </Grid.ColumnDefinitions>\n <TextBlock\n Grid.Column=\"0\"\n Margin=\"5,5,10,5\"\n Text=\"{Binding VersionName}\" />\n <Button\n Grid.Column=\"1\"\n Padding=\"5\"\n Command=\"{Binding RemoveVersionCommand}\"\n Content=\"Remove\"\n Visibility=\"{Binding CanBeRemoved, Converter={StaticResource BoolToVisibilityConverter}}\" />\n </Grid>\n </DataTemplate>\n </ListBox.ItemTemplate>\n </ListBox>\n </Grid>\n</UserControl>\n DataContext VersionsList VersionsListViewModel <UserControl>\n <Grid>\n <Grid.ColumnDefinitions>\n <ColumnDefinition Width=\"*\" />\n <ColumnDefinition Width=\"*\" />\n <ColumnDefinition Width=\"2*\" />\n </Grid.ColumnDefinitions>\n\n <Controls:VersionsList x:Name=\"test\"\n Grid.Column=\"0\"\n DataContext=\"{Binding VersionsListViewModel}\"\n VersionsItemsSource=\"{Binding Versions}\"\n SelectedVersionItem=\"{Binding SelectedVersion}\" />\n </Grid>\n</UserControl>\n VersionsList VersionsListViewModel.SelectedVersion HomeViewModel VersionsListViewModel.SelectedVersion VersionsListViewModel HomeViewModel.SelectedVersion"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5199737/"
] |
74,506,646
|
<p>I am trying to run a loop that requires the bash command --
<code>!python3 -m runner.player_1 </code></p>
<p>but when I make it into loop:</p>
<pre><code>for player1 in range(0, 100, 1):
!python3 -m "runner.player_" + str(player1)
</code></pre>
<p>it doesn't work and returns the error:</p>
<pre><code>/bin/bash: -c: line 0: syntax error near unexpected token `('
/bin/bash: -c: line 0: `python3 -m "runner.player_" + str(player1)'
</code></pre>
<p>how can i fix this? thank you</p>
|
[
{
"answer_id": 74506676,
"author": "Ahmed AEK",
"author_id": 15649230,
"author_profile": "https://Stackoverflow.com/users/15649230",
"pm_score": 0,
"selected": false,
"text": "os.system import os\nfor player1 in range(0, 100, 1):\n os.system(\"python3 -m runner.player_\" + str(player1))\n"
},
{
"answer_id": 74506696,
"author": "tripleee",
"author_id": 874188,
"author_profile": "https://Stackoverflow.com/users/874188",
"pm_score": 2,
"selected": true,
"text": "for i in {0..99}; do python3 -m runner.player_$i; done\n do"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18104989/"
] |
74,506,670
|
<p>I am a new in jetpack compose and I really wanted to know how I can dismiss a composable dialog. Is there any function like dismiss() for dialog in jetpack compose?</p>
<p>By using below code, I cannot dismiss the dialog either touching outside or pressing back button. The dialog just still is visible on the top of view hierarchy.
`</p>
<pre><code>@Composable
fun InfoDialog() {
val shouldDismiss = remember {
mutableStateOf(false)
}
Dialog(onDismissRequest = {
shouldDismiss.value = false
}, properties = DialogProperties(
dismissOnBackPress = true,
dismissOnClickOutside = true
)) {
Card(
shape = RoundedCornerShape(8.dp),
modifier = Modifier.padding(16.dp,8.dp,16.dp,8.dp),
elevation = 8.dp
) {
Column(
Modifier.background(c282534)) {
Column(modifier = Modifier.padding(16.dp)) {
Text(
text = "Notice",
textAlign = TextAlign.Center,
modifier = Modifier
.padding(top = 8.dp)
.fillMaxWidth(),
style = TextStyle(fontWeight = FontWeight.Bold, color = Color.White, fontSize = 24.sp),
maxLines = 2,
overflow = TextOverflow.Ellipsis
)
Text(
text = "Allow Permission to send you notifications when important update added.",
textAlign = TextAlign.Center,
modifier = Modifier
.padding(top = 8.dp, start = 24.dp, end = 24.dp)
.fillMaxWidth(),
style = TextStyle(color = Color.White, fontSize = 16.sp)
)
}
Row(
Modifier
.fillMaxWidth()
.padding(top = 8.dp),
horizontalArrangement = Arrangement.SpaceAround) {
TextButton(onClick = {
shouldDismiss.value = true
}, modifier = Modifier.weight(1f)) {
Text(
"Close",
fontWeight = FontWeight.Normal,
color = Color.White,
modifier = Modifier.padding(top = 8.dp, bottom = 8.dp)
)
}
TextButton(
onClick = {
shouldDismiss.value = true
},
modifier = Modifier.weight(1f)
) {
Text(
"Allow",
fontWeight = FontWeight.ExtraBold,
color = Color.White,
modifier = Modifier.padding(top = 8.dp, bottom = 8.dp)
)
}
}
}
}
}
}
</code></pre>
<p>`</p>
|
[
{
"answer_id": 74506711,
"author": "Evgeny",
"author_id": 7309962,
"author_profile": "https://Stackoverflow.com/users/7309962",
"pm_score": 1,
"selected": false,
"text": "onDismissRequest shouldDismiss.value = true shouldDismiss Dialog {... if (shouldDismiss.value) return @Composable\nfun InfoDialog() {\n val shouldDismiss = remember {\n mutableStateOf(false)\n }\n\n if (shouldDismiss.value) return\n \n Dialog(onDismissRequest = {\n shouldDismiss.value = true\n }, properties = DialogProperties(\n dismissOnBackPress = true,\n dismissOnClickOutside = true\n )) {\n Card(\n shape = RoundedCornerShape(8.dp),\n modifier = Modifier.padding(16.dp,8.dp,16.dp,8.dp),\n elevation = 8.dp\n ) {\n Column(\n Modifier.background(c282534)) {\n Column(modifier = Modifier.padding(16.dp)) {\n Text(\n text = \"Notice\",\n textAlign = TextAlign.Center,\n modifier = Modifier\n .padding(top = 8.dp)\n .fillMaxWidth(),\n style = TextStyle(fontWeight = FontWeight.Bold, color = Color.White, fontSize = 24.sp),\n maxLines = 2,\n overflow = TextOverflow.Ellipsis\n )\n Text(\n text = \"Allow Permission to send you notifications when important update added.\",\n textAlign = TextAlign.Center,\n modifier = Modifier\n .padding(top = 8.dp, start = 24.dp, end = 24.dp)\n .fillMaxWidth(),\n style = TextStyle(color = Color.White, fontSize = 16.sp)\n )\n }\n Row(\n Modifier\n .fillMaxWidth()\n .padding(top = 8.dp),\n horizontalArrangement = Arrangement.SpaceAround) {\n\n TextButton(onClick = {\n shouldDismiss.value = true\n }, modifier = Modifier.weight(1f)) {\n\n Text(\n \"Close\",\n fontWeight = FontWeight.Normal,\n color = Color.White,\n modifier = Modifier.padding(top = 8.dp, bottom = 8.dp)\n )\n }\n TextButton(\n onClick = {\n shouldDismiss.value = true\n },\n modifier = Modifier.weight(1f)\n ) {\n Text(\n \"Allow\",\n fontWeight = FontWeight.ExtraBold,\n color = Color.White,\n modifier = Modifier.padding(top = 8.dp, bottom = 8.dp)\n )\n }\n }\n }\n }\n }\n}\n\n"
},
{
"answer_id": 74506835,
"author": "Gabriele Mariotti",
"author_id": 2016562,
"author_profile": "https://Stackoverflow.com/users/2016562",
"pm_score": 3,
"selected": true,
"text": "val shouldShowDialog = remember { mutableStateOf(true) }\n\nif (shouldShowDialog.value) {\n\n Dialog(onDismissRequest = { shouldShowDialog.value = false }) { \n Button(onClick = {shouldShowDialog.value = false}){\n Text(\"Close\")\n }\n }\n}\n shouldShowDialog false Dialog shouldShowDialog true Button(onClick = {shouldShowDialog.value = true}){\n Text(\"Open\")\n}\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12697321/"
] |
74,506,692
|
<p>I'm using nft.storage for storing my data on ipfs using storeBlob as I want to store only data.</p>
<pre><code>index.js:13
Uncaught (in promise) TypeError: source is not async iterable
at last (index.js:13:1)
at pack (index.js:14:1)
at packCar (lib.js:757:1)
at NFTStorage.encodeBlob (lib.js:472:1)
at NFTStorage.storeBlob (lib.js:151:1)
at NFTStorage.storeBlob (lib.js:542:1)
at storeAsset (Results.jsx:36:1)
at encryptingData (Results.jsx:63:1)
</code></pre>
<p>I used this function to get cid.</p>
<p>Here my metadata is encrypted string</p>
<pre><code>const client = new NFTStorage({ token: NFT_STORAGE_KEY })
async function storeAsset(metadata) {
const cid = await client.storeBlob(metadata);
console.log("Metadata stored on Filecoin and IPFS with cid:", cid)
}
</code></pre>
|
[
{
"answer_id": 74506711,
"author": "Evgeny",
"author_id": 7309962,
"author_profile": "https://Stackoverflow.com/users/7309962",
"pm_score": 1,
"selected": false,
"text": "onDismissRequest shouldDismiss.value = true shouldDismiss Dialog {... if (shouldDismiss.value) return @Composable\nfun InfoDialog() {\n val shouldDismiss = remember {\n mutableStateOf(false)\n }\n\n if (shouldDismiss.value) return\n \n Dialog(onDismissRequest = {\n shouldDismiss.value = true\n }, properties = DialogProperties(\n dismissOnBackPress = true,\n dismissOnClickOutside = true\n )) {\n Card(\n shape = RoundedCornerShape(8.dp),\n modifier = Modifier.padding(16.dp,8.dp,16.dp,8.dp),\n elevation = 8.dp\n ) {\n Column(\n Modifier.background(c282534)) {\n Column(modifier = Modifier.padding(16.dp)) {\n Text(\n text = \"Notice\",\n textAlign = TextAlign.Center,\n modifier = Modifier\n .padding(top = 8.dp)\n .fillMaxWidth(),\n style = TextStyle(fontWeight = FontWeight.Bold, color = Color.White, fontSize = 24.sp),\n maxLines = 2,\n overflow = TextOverflow.Ellipsis\n )\n Text(\n text = \"Allow Permission to send you notifications when important update added.\",\n textAlign = TextAlign.Center,\n modifier = Modifier\n .padding(top = 8.dp, start = 24.dp, end = 24.dp)\n .fillMaxWidth(),\n style = TextStyle(color = Color.White, fontSize = 16.sp)\n )\n }\n Row(\n Modifier\n .fillMaxWidth()\n .padding(top = 8.dp),\n horizontalArrangement = Arrangement.SpaceAround) {\n\n TextButton(onClick = {\n shouldDismiss.value = true\n }, modifier = Modifier.weight(1f)) {\n\n Text(\n \"Close\",\n fontWeight = FontWeight.Normal,\n color = Color.White,\n modifier = Modifier.padding(top = 8.dp, bottom = 8.dp)\n )\n }\n TextButton(\n onClick = {\n shouldDismiss.value = true\n },\n modifier = Modifier.weight(1f)\n ) {\n Text(\n \"Allow\",\n fontWeight = FontWeight.ExtraBold,\n color = Color.White,\n modifier = Modifier.padding(top = 8.dp, bottom = 8.dp)\n )\n }\n }\n }\n }\n }\n}\n\n"
},
{
"answer_id": 74506835,
"author": "Gabriele Mariotti",
"author_id": 2016562,
"author_profile": "https://Stackoverflow.com/users/2016562",
"pm_score": 3,
"selected": true,
"text": "val shouldShowDialog = remember { mutableStateOf(true) }\n\nif (shouldShowDialog.value) {\n\n Dialog(onDismissRequest = { shouldShowDialog.value = false }) { \n Button(onClick = {shouldShowDialog.value = false}){\n Text(\"Close\")\n }\n }\n}\n shouldShowDialog false Dialog shouldShowDialog true Button(onClick = {shouldShowDialog.value = true}){\n Text(\"Open\")\n}\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20553264/"
] |
74,506,716
|
<p>This question is in relation to Dr Angela Yu's 11th day of Python tutorials. I am not able to execute the code I typed in. The code is typed in replit. Where am I making mistakes? This code is supposed to play the game of Blackjack.</p>
<pre><code>import random
from replit import clear
from art import logo
def draw_card():
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
return random.choice(cards)
def calculate_score(cards):
if sum(cards) == 21 and len(cards) == 2:
return 0
if sum(cards) > 21 and 11 in cards:
cards.remove(11)
cards.append(1)
return sum(cards)
def compare(user_score, computer_score):
if user_score > 21 and computer_score > 21:
print("You went over 21. You lost")
elif computer_score == 0:
print("You lost. Computer has blackjack")
elif user_score == 0:
print("You won with a blackjack.")
elif user_score == computer_score:
print("Draw")
elif user_score > 21:
print("You lost")
elif computer_score > 21:
print("you won")
elif user_score > computer_score:
print("You won.")
else:
print("Computer won")
def play_game():
print (logo)
user_cards = []
computer_cards = []
for number in range(2):
user_cards.append(draw_card())
computer_cards.append(draw_card())
game_end = False
while not game_end:
user_score = calculate_score(user_cards)
computer_score = calculate_score(computer_cards)
print(f" Your cards: {user_cards}, your score: {user_score}.")
print(f" Computer's first card: {computer_cards[0]}")
get_card = input("Type 'y' to get another card, type 'n' to pass: ")
if get_card == "y".lower():
user_cards.append(draw_card())
else:
game_end = True
while computer_score < 17:
computer_cards.append(draw_card)
print(f" Your final hand: {user_cards}, final score: {user_score}")
print(f" Computer's final hand: {computer_cards}, final score: {computer_score}")
print(compare(user_score, computer_score))
play = input("Do you want to play a game of blackjack. Type y or n: ").lower()
while play == "y":
clear()
play_game()
</code></pre>
<p>I am not able to debug this code in thonny due to some functions I can only find in replit.</p>
|
[
{
"answer_id": 74506962,
"author": "UNK30WN",
"author_id": 18025253,
"author_profile": "https://Stackoverflow.com/users/18025253",
"pm_score": -1,
"selected": false,
"text": "\n#The main bug is that the program gets stuck at while loop in around lineNO 62 where it says \"while computer_score < 17:\"\n#I could solve it for you but i don't know the game, so do something there.\n#My suggestion: use if statement instead of while loop.\n"
},
{
"answer_id": 74510392,
"author": "Sören",
"author_id": 1707427,
"author_profile": "https://Stackoverflow.com/users/1707427",
"pm_score": 0,
"selected": false,
"text": "computer_score computer_score < 17 True"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20517675/"
] |
74,506,719
|
<p>I have two methods: <code>funca()</code> and <code>funcb()</code> which return a value of type <code>X</code> or a <code>List<X></code> respectively like shown below:</p>
<pre><code>X funca(Event e) { ... }
List<X> funcb(Event e) { ... }
</code></pre>
<p>I want to use them in the Stream and collect the result into a list.</p>
<p>These method methods should be called under different conditions, like shown below in pseudocode:</p>
<pre><code>List<Event> input = // initializing the input
List<X> resultList = input.values().stream()
.(event -> event.status=="active" ? funca(event) : funcb(event))
.collect(Collectors.toList());
</code></pre>
<p>Can someone please tell me how I can achieve this so that whether the function returns a list of values or values?</p>
|
[
{
"answer_id": 74507161,
"author": "Jean-Baptiste Yunès",
"author_id": 719263,
"author_profile": "https://Stackoverflow.com/users/719263",
"pm_score": 1,
"selected": false,
"text": "funcA flatMap List<X> result = input.stream()\n .flatMap(e -> e.status.equals(\"active\") ? List.of(funcA(e)) : funcB(e))\n .collect(Collectors.toList());\n"
},
{
"answer_id": 74507962,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
"author_profile": "https://Stackoverflow.com/users/17949945",
"pm_score": 3,
"selected": true,
"text": "flatMap() mapMulti() flatMap() Stream funca() Stream.of() List flatMap() List<X> = input.values().stream()\n .flatMap(event -> \"active\".equals(event.getStatus()) ? \n Stream.of(funca(event)) : funcb(event).stream()\n )\n .toList(); // for Java 16+ or collect(Collectors.toList())\n mapMulti() flatMap() flatMap BiConsumer Consumer Consumer mapMulti() funcb() flatMap() List<X> = input.values().stream()\n .<X>mapMulti((event, consumer) -> {\n if (\"active\".equals(event.getStatus())) consumer.accept(funca(event));\n else funcb(event).forEach(consumer);\n })\n .toList(); // for Java 16+ or collect(Collectors.toList())\n == String equals()"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16526999/"
] |
74,506,729
|
<p>I have a tree, and I want find the correct node and insert data into the object.</p>
<pre><code>const resultTree = {
grand_parent: {
parent: {
child: {},
},
sibling: {
cousin: {},
},
},
};
</code></pre>
<p>for example, insert grand_child into child.</p>
<p>so the result will look like this:</p>
<pre><code>const resultTree = {
grand_parent: {
parent: {
child: {
grand_child: {}, // inserted grand_child here
},
},
sibling: {
cousin: {},
},
},
};
</code></pre>
<p>and I can insert more as needed, i.e. insert sibling into child</p>
<pre><code>const resultTree = {
grand_parent: {
parent: {
child: {
grand_child: {},
sibling: {} // inserted sibling here
},
},
sibling: {
cousin: {},
},
},
};
</code></pre>
<p>This is what I have now, but it's not working</p>
<pre><code>const findAndInsert = (node: string, tree: Tree, parentNode: string) => {
if (!!tree[parentNode]) {
tree[parentNode][node] = {};
} else {
Object.keys(tree[parentNode]).forEach((n) => {
findAndInsert(node, tree[n], parentNode);
});
}
};
</code></pre>
|
[
{
"answer_id": 74507161,
"author": "Jean-Baptiste Yunès",
"author_id": 719263,
"author_profile": "https://Stackoverflow.com/users/719263",
"pm_score": 1,
"selected": false,
"text": "funcA flatMap List<X> result = input.stream()\n .flatMap(e -> e.status.equals(\"active\") ? List.of(funcA(e)) : funcB(e))\n .collect(Collectors.toList());\n"
},
{
"answer_id": 74507962,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
"author_profile": "https://Stackoverflow.com/users/17949945",
"pm_score": 3,
"selected": true,
"text": "flatMap() mapMulti() flatMap() Stream funca() Stream.of() List flatMap() List<X> = input.values().stream()\n .flatMap(event -> \"active\".equals(event.getStatus()) ? \n Stream.of(funca(event)) : funcb(event).stream()\n )\n .toList(); // for Java 16+ or collect(Collectors.toList())\n mapMulti() flatMap() flatMap BiConsumer Consumer Consumer mapMulti() funcb() flatMap() List<X> = input.values().stream()\n .<X>mapMulti((event, consumer) -> {\n if (\"active\".equals(event.getStatus())) consumer.accept(funca(event));\n else funcb(event).forEach(consumer);\n })\n .toList(); // for Java 16+ or collect(Collectors.toList())\n == String equals()"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13097920/"
] |
74,506,744
|
<p>I have a MySQL table of users as follows:</p>
<pre><code>CREATE TABLE `users` (
`ID` INT NOT NULL, -- NOTE: in practice, I'm using BINARY(16) and
-- the UUID()-function to create user IDs.
-- 'INT' is only a simplification for this
-- stackoverflow question.
`FirstName` NVARCHAR(100) NOT NULL,
`LastName` NVARCHAR(100) NOT NULL,
-- ...
PRIMARY KEY (`ID`)
);
INSERT INTO `users` (`ID`, `FirstName`, `LastName`)
VALUES (0, 'Albus', 'Dumbledore'),
(1, 'Lord', 'Voldemort'),
(2, 'Harry', 'Potter'),
(3, 'Hermione', 'Granger');
</code></pre>
<p>I'd like to create a user-defined function which returns the <code>ID</code> of the row matching a <code>FirstName</code> and <code>LastName</code> combination if (and only if) the results are unique (i.e. only one row matches the query):</p>
<pre><code>CREATE FUNCTION `FindUser`(`first_name` NVARCHAR(100), `last_name` NVARCHAR(100)
RETURNS INT
BEGIN
RETURN (SELECT `ID`
FROM `users`
WHERE ((first_name is NULL) OR (`FirstName` LIKE CONCAT('%', first_name, '%')))
AND ((last_name Is NULL) OR (`LastName` LIKE CONCAT('%', last_name, '%')))
LIMIT 1);
END
</code></pre>
<p>This works as expected on the following examples:</p>
<pre><code>SELECT `FindUser`(NULL, 'potter');
-- | ID |
-- |----|
-- | 2 |
SELECT `FindUser`('obama', NULL);
-- | ID |
-- |----|
</code></pre>
<p>However, this does not work on <code>SELECT FindUser(NULL, 'or');</code>, as the token <code>'or'</code> could match <code>0 | Albus | Dumbledore</code> and <code>1 | Lord | Voldemort</code>.</p>
<hr />
<p>I tried the following:</p>
<pre><code>SET @cnt = 0;
SET @id = NULL;
SELECT @id = u.id, @cnt = COUNT(id)
FROM users u
WHERE ...; -- same conditions as before
RETURN IF(@cnt = 1, @id, NULL);
</code></pre>
<p>However, that does not work, as <code>@id</code> and <code>@cnt</code> will always be overwritten by the last line.
The alternative would be to perform two queries, but that is inefficient.</p>
<p><strong>How could I solve the problem most efficiently?</strong></p>
|
[
{
"answer_id": 74507045,
"author": "Stu",
"author_id": 15332650,
"author_profile": "https://Stackoverflow.com/users/15332650",
"pm_score": 3,
"selected": true,
"text": "RETURN (\n SELECT CASE WHEN count(*) over() = 1 then ID ELSE null END\n FROM users\n WHERE (first_name is NULL OR FirstName LIKE CONCAT('%', first_name, '%'))\n AND (last_name Is NULL OR LastName LIKE CONCAT('%', last_name, '%'))\n LIMIT 1\n);\n"
},
{
"answer_id": 74507059,
"author": "forpas",
"author_id": 10498828,
"author_profile": "https://Stackoverflow.com/users/10498828",
"pm_score": 1,
"selected": false,
"text": "HAVING CREATE FUNCTION FindUser(first_name NVARCHAR(100), last_name NVARCHAR(100))\nRETURNS INT\nBEGIN\n RETURN (\n SELECT MAX(ID) \n FROM users\n WHERE (first_name IS NULL OR FirstName LIKE CONCAT('%', first_name, '%'))\n AND (last_name IS NULL OR LastName LIKE CONCAT('%', last_name, '%'))\n GROUP BY NULL -- you can omit this clause \n HAVING COUNT(*) = 1\n );\nEND;\n null ID WHERE null WHERE (first_name IS NOT NULL OR last_name IS NOT NULL)\n AND (first_name IS NULL OR FirstName LIKE CONCAT('%', first_name, '%'))\n AND (last_name IS NULL OR LastName LIKE CONCAT('%', last_name, '%'))\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3902603/"
] |
74,506,746
|
<p>In our project, we use this regular expression to validate emails:</p>
<p><code>"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,7}|[0-9]{1,3})(\]?)$"</code></p>
<p>But it allows non English characters.</p>
<p>For example:</p>
<p>"مستخدم@mail.com"</p>
<p>"userمحمد@mail.com"</p>
<p>"userName@خادم.com"</p>
<p>are valid emails.</p>
<p>How to add another rule to this expression to limit inputs to English letters only?</p>
|
[
{
"answer_id": 74506993,
"author": "Pradeep Kumar",
"author_id": 18704952,
"author_profile": "https://Stackoverflow.com/users/18704952",
"pm_score": 0,
"selected": false,
"text": " string[] StrInputNumber = { \"pradeep1234@yahoo.in\", \"مستخدم@mail.com'\", \"userمحمد@mail.com\", \"userName@خادم.com\" };\n Regex ASCIILettersOnly = new Regex(@\"^[\\P{L}A-Za-z]*$\");\n foreach (String item in StrInputNumber) {\n if (ASCIILettersOnly.IsMatch(item)) {\n Console.WriteLine(item + \" ==> valid\");\n }\n else {\n Console.WriteLine(item + \" ==>not valid\");\n }\n }\n"
},
{
"answer_id": 74507028,
"author": "Rachel",
"author_id": 20530549,
"author_profile": "https://Stackoverflow.com/users/20530549",
"pm_score": 0,
"selected": false,
"text": "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$.\n"
},
{
"answer_id": 74507947,
"author": "The fourth bird",
"author_id": 5424988,
"author_profile": "https://Stackoverflow.com/users/5424988",
"pm_score": 2,
"selected": true,
"text": "| \\]? [\\w-\\.] \\w [A-Za-z0-9] ^[A-Za-z0-9]+(?:[.-][A-Za-z0-9]+)*@[A-Za-z0-9]+(?:[.-][A-Za-z0-9]+)*\\.[a-z]{2,}$\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1541152/"
] |
74,506,755
|
<p>So, I wanted to claculate age from user birthdate to current date in Google sheet in my expected format. I tried few formula's from some sources, but it is just not happening.</p>
<p>Can anyone please guide me?</p>
<p>For reference and test purpose, I'm attaching one Google sheet public link. No worries if email address will be shown in Googe sheet.</p>
<p>Link: <a href="https://docs.google.com/spreadsheets/d/1jRlr6A3YRJIo1Ah1TSlRsDcLEDV_2BJ8YaBRS3YVC6Q/edit#gid=0" rel="nofollow noreferrer">https://docs.google.com/spreadsheets/d/1jRlr6A3YRJIo1Ah1TSlRsDcLEDV_2BJ8YaBRS3YVC6Q/edit#gid=0</a></p>
|
[
{
"answer_id": 74506993,
"author": "Pradeep Kumar",
"author_id": 18704952,
"author_profile": "https://Stackoverflow.com/users/18704952",
"pm_score": 0,
"selected": false,
"text": " string[] StrInputNumber = { \"pradeep1234@yahoo.in\", \"مستخدم@mail.com'\", \"userمحمد@mail.com\", \"userName@خادم.com\" };\n Regex ASCIILettersOnly = new Regex(@\"^[\\P{L}A-Za-z]*$\");\n foreach (String item in StrInputNumber) {\n if (ASCIILettersOnly.IsMatch(item)) {\n Console.WriteLine(item + \" ==> valid\");\n }\n else {\n Console.WriteLine(item + \" ==>not valid\");\n }\n }\n"
},
{
"answer_id": 74507028,
"author": "Rachel",
"author_id": 20530549,
"author_profile": "https://Stackoverflow.com/users/20530549",
"pm_score": 0,
"selected": false,
"text": "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$.\n"
},
{
"answer_id": 74507947,
"author": "The fourth bird",
"author_id": 5424988,
"author_profile": "https://Stackoverflow.com/users/5424988",
"pm_score": 2,
"selected": true,
"text": "| \\]? [\\w-\\.] \\w [A-Za-z0-9] ^[A-Za-z0-9]+(?:[.-][A-Za-z0-9]+)*@[A-Za-z0-9]+(?:[.-][A-Za-z0-9]+)*\\.[a-z]{2,}$\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19428652/"
] |
74,506,765
|
<p>I working on an ASP.NET Core 2.2 web application. I have some issues when upgrade my application to .NET 6.</p>
<p>My issue is that there's no <code>startup</code> class in .NET 6.0 and I found <code>program.cs</code> file only.</p>
<p>I add startup class on my web application but I don't know how to use it inside <code>Program.cs</code>.</p>
<p>How to add or use <code>startup</code> class inside my <code>program.cs</code>?</p>
<p>This is the <code>startup.cs</code> file in .NET Core 2.2:</p>
<pre><code>public class Startup
{
private readonly IConfigurationRoot configRoot;
private AppSettings AppSettings { get; set; }
public Startup(IConfiguration configuration)
{
Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
Configuration = configuration;
IConfigurationBuilder builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
configRoot = builder.Build();
AppSettings = new AppSettings();
Configuration.Bind(AppSettings);
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddController();
services.AddDbContext(Configuration, configRoot);
services.AddIdentityService(Configuration);
services.AddAutoMapper();
services.AddScopedServices();
services.AddTransientServices();
services.AddSwaggerOpenAPI();
services.AddMailSetting(Configuration);
services.AddServiceLayer();
services.AddVersion();
services.AddHealthCheck(AppSettings, Configuration);
services.AddFeatureManagement();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory log)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors(options =>
options.WithOrigins("http://localhost:3000")
.AllowAnyHeader()
.AllowAnyMethod());
app.ConfigureCustomExceptionMiddleware();
log.AddSerilog();
//app.ConfigureHealthCheck();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.ConfigureSwagger();
app.UseHealthChecks("/healthz", new HealthCheckOptions
{
Predicate = _ => true,
ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse,
ResultStatusCodes =
{
[HealthStatus.Healthy] = StatusCodes.Status200OK,
[HealthStatus.Degraded] = StatusCodes.Status500InternalServerError,
[HealthStatus.Unhealthy] = StatusCodes.Status503ServiceUnavailable,
},
}).UseHealthChecksUI(setup =>
{
setup.ApiPath = "/healthcheck";
setup.UIPath = "/healthcheck-ui";
//setup.AddCustomStylesheet("Customization/custom.css");
});
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
</code></pre>
<p>And this is my .NET 6 <code>program.cs</code>:</p>
<pre><code>var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.Run();
</code></pre>
<p>How to use the <code>startup</code> class inside <code>program.cs</code> class ?</p>
<p><strong>Updated Post</strong>
every thing is working but configure service not working
because i don't know how to implement <code>ILoggerFactory</code>
on <code>startup</code></p>
<pre><code> public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory log)
{
}
</code></pre>
<p>on program.cs</p>
<pre><code>startup.Configure(app, app.Environment,???);
</code></pre>
<p>How to add logger factory as third paramter on <code>program.cs</code>
<code>ILoggerFactory</code> is buit in class
<strong>Updated</strong> it solved using</p>
<pre><code>var app = builder.Build();
startup.Configure(
app,
builder.Environment,
app.Services.GetRequiredService<FooService>(),
app.Services.GetRequiredService<ILoggerFactory>()
);
</code></pre>
<p>can you please tell me how to apply swagger ui to check my api</p>
|
[
{
"answer_id": 74506909,
"author": "vernou",
"author_id": 2703673,
"author_profile": "https://Stackoverflow.com/users/2703673",
"pm_score": 3,
"selected": true,
"text": "Startup ConfigureServices Configure var builder = WebApplication.CreateBuilder(args);\n\nvar startup = new Startup(builder.Configuration);\nstartup.ConfigureServices(builder.Services);\n\nvar app = builder.Build();\nstartup.Configure(app, builder.Environment);\n Startup.Configure public class Startup\n{\n public void ConfigureServices(IServiceCollection services)\n {\n ...\n services.AddSingleton<IFooService, FooService>();\n }\n\n public void Configure(WebApplication app, IWebHostEnvironment env, IFooService fooService, ILoggerFactory loggerFactory)\n {\n\n fooService.Init();\n ...\n }\n}\n var app = builder.Build();\nstartup.Configure(\n app,\n builder.Environment,\n app.Services.GetRequiredService<FooService>(),\n app.Services.GetRequiredService<ILoggerFactory>()\n);\n Startup"
},
{
"answer_id": 74512655,
"author": "Guru Stron",
"author_id": 2501279,
"author_profile": "https://Stackoverflow.com/users/2501279",
"pm_score": 1,
"selected": false,
"text": "WebHost Main Program.cs Program Program.cs await CreateHostBuilder(args)\n .Build()\n .RunAsync();\n\n// do not forget to copy the rest of the setup if any\nstatic IHostBuilder CreateHostBuilder(string[] args) =>\n Host.CreateDefaultBuilder(args)\n .ConfigureWebHostDefaults(webBuilder =>\n {\n webBuilder.UseStartup<Startup>();\n });\n Startup"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12573767/"
] |
74,506,772
|
<p>I'm teaching myself Python and I have been stuck on this issue for a few days now.</p>
<p>The idea is to ask a user to input a sentence and then ask them for 5 characters that they would like to remove from the sentence.</p>
<p>For example the sentence input by the user is:
user_string = "The quick brown fox jumps over the lazy dog"</p>
<p>The characters they want to remove is:
lst = ["a", "b", "c", "d", "e"]</p>
<p>I have reached the point where I have the user string and the user list that needs to be removed, what I'm stuck on is figuring out how to loop through the list and check if each character is present in the string and then to strip it from the string.</p>
<p>I have tried to use a for loop but I'm not yet proficient in loops so I might be going about it the wrong way, this is my for loop so far:</p>
<pre><code>for char in user_string[:]:
if char[0] in user_string:
removed_string = user_string.strip(char)
print(removed_string)
</code></pre>
|
[
{
"answer_id": 74506789,
"author": "azro",
"author_id": 7212686,
"author_profile": "https://Stackoverflow.com/users/7212686",
"pm_score": 2,
"selected": false,
"text": "user_string.strip(char) char user_string = \"The quick brown fox jumps over the lazy dog\"\nlst = [\"a\", \"b\", \"c\", \"d\", \"e\"]\n\n# either collect valid chars\nresult = \"\"\nfor c in user_string:\n if c not in lst:\n result += c\nprint(result)\n\n# either remove invalid chars\nresult = user_string[:]\nfor to_remove in lst:\n result = result.replace(to_remove, \"\")\nprint(result)\n"
},
{
"answer_id": 74506790,
"author": "Geeky Quentin",
"author_id": 17235431,
"author_profile": "https://Stackoverflow.com/users/17235431",
"pm_score": 0,
"selected": false,
"text": "\"\" user_string = \"the quick brown fox jumps over the lazy dog\"\n\nchars_to_remove = [\"a\", \"b\", \"c\", \"d\", \"e\"]\n\nfor char in chars_to_remove:\n user_string = user_string.replace(char, \"\")\n\nprint(user_string)\n th quik rown fox jumps ovr th lzy of\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20553321/"
] |
74,506,796
|
<p>so I have a gridview which is displaying a db table I have.
I dont create the table manually obviously as this is what <%#Eval("text")%>' and Bind() do.
I created a unique table with my sql query to add two rows of sum in the bottom of the table, ( 2 last records), my question is:
is there a way in which I can access those rows to style them?
I think its not possible but still Im asking maybe Ill find out that theres a way.
thanks</p>
|
[
{
"answer_id": 74506789,
"author": "azro",
"author_id": 7212686,
"author_profile": "https://Stackoverflow.com/users/7212686",
"pm_score": 2,
"selected": false,
"text": "user_string.strip(char) char user_string = \"The quick brown fox jumps over the lazy dog\"\nlst = [\"a\", \"b\", \"c\", \"d\", \"e\"]\n\n# either collect valid chars\nresult = \"\"\nfor c in user_string:\n if c not in lst:\n result += c\nprint(result)\n\n# either remove invalid chars\nresult = user_string[:]\nfor to_remove in lst:\n result = result.replace(to_remove, \"\")\nprint(result)\n"
},
{
"answer_id": 74506790,
"author": "Geeky Quentin",
"author_id": 17235431,
"author_profile": "https://Stackoverflow.com/users/17235431",
"pm_score": 0,
"selected": false,
"text": "\"\" user_string = \"the quick brown fox jumps over the lazy dog\"\n\nchars_to_remove = [\"a\", \"b\", \"c\", \"d\", \"e\"]\n\nfor char in chars_to_remove:\n user_string = user_string.replace(char, \"\")\n\nprint(user_string)\n th quik rown fox jumps ovr th lzy of\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19198699/"
] |
74,506,807
|
<p>everyone</p>
<p>I started programming in python yesterday to create a project. This consists of taking data from an API using the "Requests" library</p>
<p>So far I had no trouble getting familiar with the library, but I can't get results for what I'm specifically looking for.</p>
<p>My idea is just to get the name of the account.</p>
<p>Here the code</p>
<pre><code>import requests
user = 'example'
payload = {'data': 'username'}
r = requests.get('https://api.imvu.com/user/user-'+user, params=payload)
json = r.json()
print(json)
</code></pre>
<p>My idea is that, within all the data that can be obtained, only obtain the name of the account. just the name</p>
<p>The code works perfectly, but it throws me all the account data.</p>
<p>For example:</p>
<pre class="lang-json prettyprint-override"><code>{
"https://api.imvu.com/user/user-x?data=created": {
"data": {
"created": "2020-11-30T17:56:31Z",
"registered": "x",
"gender": "f",
"display_name": " ",
"age": "None",
"country": "None",
"state": "None",
"avatar_image": "x",
"avatar_portrait_image": "https://......",
"is_vip": false,
"is_ap": true,
"is_creator": false,
"is_adult": true,
"is_ageverified": true,
"is_staff": false,
"is_greeter": false,
"greeter_score": 0,
"badge_level": 0,
"username": "=== ONLY THIS I NEED ==="
}
}
}
</code></pre>
<p>As you can see, I only need one thing from all that data.</p>
<p>Sorry for bothering and I hope I can learn from your answers. Thanks so much for reading</p>
|
[
{
"answer_id": 74506876,
"author": "Saurabh Verma",
"author_id": 12817895,
"author_profile": "https://Stackoverflow.com/users/12817895",
"pm_score": 1,
"selected": true,
"text": "r = requests.get('https://api.imvu.com/user/user-'+user, params=payload)\n\njson = r.json()\n\nusername = json[\"https://api.imvu.com/user/user-x?data=created\"][\"data\"][\"username\"]\n\nprint(username)\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20553314/"
] |
74,506,809
|
<p>I am using tippy js library to handle tooltips in my app. Now I want to test whether the components shows a tooltip content when hover over an element. The tippy js library says that the tooltip is triggered by either <code>mouseEnter</code> or <code>focus</code> event.</p>
<p>When testing it, I use <code>fireEvent.mouseEnter()</code> event to trigger tooltip. That works fine enough to pass. But when I use <code>userEvent.hover()</code>, it didn't work. <strong>Doesn't <code>userEvent.hover()</code> support <code>mouserEnter</code> event?</strong> Or help me to understand why doesn't it works here.</p>
<p>Note: <code>fireEvent.mouseOver()</code> doesn't work here.</p>
<p>I know the tippy js lib is already been tested. I am just curious why it is not working with <code>userEvent.hover()</code>.</p>
<p>The following is contrived/reproducible code. <a href="https://codesandbox.io/s/polished-wood-dssc0e?file=/src/App.js:23-225" rel="nofollow noreferrer">CodeSandbox</a></p>
<pre class="lang-js prettyprint-override"><code>import React from "react";
import Tippy from "@tippyjs/react";
const App = () => (
<Tippy content={<span>Tooltip</span>}>
<button>My button</button>
</Tippy>
);
export default App;
</code></pre>
<pre class="lang-js prettyprint-override"><code>import React from "react";
import { fireEvent, render, screen } from "@testing-library/react";
import "@testing-library/jest-dom";
import user from "@testing-library/user-event";
import App from "./App";
test("first", async () => {
render(<App />);
const button = screen.getByRole("button", { name: /my button/i });
expect(button).toBeInTheDocument();
user.hover(button);
expect(await screen.findByText(/tooltip/i)).toBeInTheDocument();
screen.debug();
});
test("second", async () => {
render(<App />);
const button = screen.getByRole("button", { name: /my button/i });
expect(button).toBeInTheDocument();
fireEvent.mouseEnter(button);
expect(screen.getByText(/tooltip/i)).toBeInTheDocument();
screen.debug();
});
</code></pre>
|
[
{
"answer_id": 74648075,
"author": "Jablonski Shargoid",
"author_id": 20660247,
"author_profile": "https://Stackoverflow.com/users/20660247",
"pm_score": 2,
"selected": false,
"text": "const App = () => (\n <Tippy content={<span>Tooltip</span>} trigger=\"focus\">\n <button>My button</button>\n </Tippy>\n);\n"
},
{
"answer_id": 74669674,
"author": "palash gupta",
"author_id": 12719634,
"author_profile": "https://Stackoverflow.com/users/12719634",
"pm_score": 1,
"selected": false,
"text": "test(\"second\", async () => {\n render(<App />);\n\n const button = screen.getByRole(\"button\", { name: /my button/i });\n\n expect(button).toBeInTheDocument();\n\n fireEvent.mouseEnter(button);\n expect(screen.getByText(/tooltip/i)).toBeInTheDocument();\n screen.debug();\n});\n"
},
{
"answer_id": 74670192,
"author": "Akshay",
"author_id": 3881787,
"author_profile": "https://Stackoverflow.com/users/3881787",
"pm_score": 2,
"selected": true,
"text": "<Tippy content={<span>Tooltip</span>} trigger={['mouseEnter', 'focus']}>\n <button>My button</button>\n</Tippy>\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13847690/"
] |
74,506,838
|
<p>I need some help on a simple strategy code I have written. This is my 1st code on it.
I have an issue with mon code written on PineScript.</p>
<p>PineScript doesnt calculate my SL, TP and quantity size properly and I cannot figure out why.</p>
<p>My strategy is :
when there are 4 green candles in a row after 1 red candle, to enter a long position on the 5th candle (no matters if it is red or green).</p>
<p>the SL price = (the close price of the 4th green candle from the red candle + the open price of the 2nd green candle from the red candle)/2</p>
<p>Diff = Difference between entry price - SL price.
This value in price will be used to calculate the TP price</p>
<p>the TP price = entry price + (2*Diff)
The "2" means I have a risk reward of 2, I risk 1 to win 2.</p>
<p>Also I want to risk 1% on each trade of my account balance.
For example if my account balance is 200 000$, I want to risk 2000$
So if the Diff (Difference between entry price - SL price) is 2$, I want to buy 1000 units of the share for ETH as 2000$/2$.
Based on my risk reward, all my lossing trades should always be 1% of my account balance and all my winning trades should always be 2%. But when I look at the trades, the percentages dont follow anything.</p>
<p>But PineScript doesnt do it properly.
It does detect the pattern that I want to trade and goes in in the 5th candle but the exit point doesnt work properly either the SL or TP and quantity.</p>
<p>I dont know if my instructions of the SL is wrong or whatever.
Do you have any idea ?</p>
<p>This is my current code and see below some picture of the trades :</p>
<pre><code>// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
strategy("4 Green Candle Strategy", overlay=true,shorttitle = "4GCS")
// 1. User Input //
i_rewardmulti = input.float(2.0, "Risk Reward", minval = 1.0, step = 0.5, group = "4 Green Candle Strategy Settings")
i_risk = input.float(1.0, "Percentage to risk per trade", minval = 0.1, step = 0.05, group = "4 Green Candle Strategy Settings")
ibtstarttime = input.time(title="Start Backtest", defval=timestamp("01 Jan 2022 00:00 +0000"), group="Backtest Period")
ibtendtime = input.time(title="End Backtest", defval=timestamp("01 Jan 2099"), group="Backtest Period")
// ---------------------------------------------------- Strategy Settings -----------------------------------------------//
// 2. Conditions of a valid setup //
ValidSetup = close[4] < open[4] and close[3] > close[4] and close[2] > close[3] and close[1] > close[2] and close > close[1] and barstate.isconfirmed
// 3. Confirmation of a valid setup //
ValidLong = ValidSetup and strategy.position_size==0 and barstate.isconfirmed
// 4. Calculation of TP, SL, balance risked and position size risked //
EntryPrice = close
long_SLprice = (close + open[2])*0.5
long_diff_EntryPrice_and_StopLossExitPrice = close - long_SLprice
long_TPprice = EntryPrice + (i_rewardmulti * long_diff_EntryPrice_and_StopLossExitPrice)
balance = (strategy.initial_capital + strategy.netprofit)
balance_limited = (balance > 0 ? balance : 0)
balance_risked = (i_risk/100) * balance
position_size_risked = (balance_risked/long_diff_EntryPrice_and_StopLossExitPrice)
// 5. Save of SL, TP and position size if a valid setup is detected //
var trade_entry = 0.0
var trade_SL = 0.0
var trade_TP = 0.0
var trade_direction = 0
// 6. Detection of a valid long and trigger alerts //
trade_entry := EntryPrice
trade_SL := long_SLprice
trade_TP := long_TPprice
trade_direction := 1
// 7. Enter a trade whenever a valid setup is detected //
if ValidLong
strategy.entry("Long", strategy.long, qty=position_size_risked)
// 8. Exit a trade whenever a TP or SL is hit //
if strategy.position_size > 0
strategy.exit("Long Exit", from_entry = "Long", limit= trade_TP, stop = trade_SL)
// 9. Draw trade data and Price action setup arrow //
plot (series = strategy.position_size !=0 and ValidLong ? trade_SL : na, title = "Trade Stop Price", color=color.red, style = plot.style_linebr)
plot (series = strategy.position_size !=0 and ValidLong ? trade_TP : na, title = "Trade TP Price", color=color.green, style = plot.style_linebr)
plotshape(series = ValidLong ? 1 : na, style =shape.triangleup, location = location.belowbar, color=color.green, title = "Bullish Setup")
// ------------------------------------------------------ End of Code -------------------------------------------------//
</code></pre>
<p><a href="https://i.stack.imgur.com/7Vncd.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>Normally on the trade which started at 22.00 (10pm) after it detected 4 green candles after 1 red candle, based on my TP strategy, it should have exit at 1212.84$ after the TP value was 1.84$ but it exit at a higher price that it was supposed to do.
And the profit in percentage is 1.57% when it should always be 2% and you can see below on a lossing trade, the percentage lost is 0.12% when it should always be 1%.</p>
<p>Do you have any idea on why it does work properly ?
Is there a mistake in my code ?</p>
<p>Thanks,
Ulrich</p>
<p>I tried to change number the reference of the candle eg candle [2] to candle [1], the detection went wrong.</p>
|
[
{
"answer_id": 74508434,
"author": "mr_statler",
"author_id": 17978157,
"author_profile": "https://Stackoverflow.com/users/17978157",
"pm_score": 2,
"selected": true,
"text": "strategy.exit() strategy.position_size 0 close open[2] //@version=5\nstrategy(\"My strategy\", overlay=true, margin_long=100, margin_short=100)\n\ntp_price = close * 1.1\nsl_price = close * 0.9\n\nlongCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28))\nif (longCondition)\n strategy.entry(\"Long\", strategy.long)\n\n strategy.exit(\"Exit Long\", \"Long\", limit = tp_price, stop = sl_price)\n close strategy.exit() strategy.position_size 0 //@version=5\nstrategy(\"My strategy\", overlay=true, margin_long=100, margin_short=100)\n\ntp_price = close * 1.1\nsl_price = close * 0.9\n\nlongCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28))\nif (longCondition)\n strategy.entry(\"Long\", strategy.long)\n\nif strategy.position_size > 0\n strategy.exit(\"Exit Long\", \"Long\", limit = tp_price, stop = sl_price)\n close strategy.position_size 0 strategy.exit() strategy.entry() if ValidLong\n strategy.entry(\"Long\", strategy.long, qty=position_size_risked)\n strategy.exit(\"Long Exit\", from_entry = \"Long\", limit= trade_TP, stop = trade_SL)\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20550735/"
] |
74,506,840
|
<p>I am not sure whether this is the correct place to post this question.</p>
<p>I recently installed iTerm 2 together with shell integration.
However, I am getting a constant error/warning on the start up:</p>
<pre><code>> /Users/usr/.iterm2_shell_integration.zsh:32: bad floating point constant
</code></pre>
<p>The <code>.iterm2_shell_integration.zsh</code> on line 32 has the following code:</p>
<pre><code>ver=$(printf "%.0f" $(sw_vers | grep ProductVersion | cut -d':' -f2 | tr -d ' ' | sed -e 's/ //g'))
zsh: bad floating point constant
</code></pre>
<p><a href="https://i.stack.imgur.com/ycwvh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ycwvh.png" alt="line 32 snippet" /></a></p>
<p>I am not sure if there is a bug or if there is something wrong with my setup.</p>
<p>The build version is <strong>3.4.18</strong> and I am running this on MacOS Ventura 13.0.1.</p>
|
[
{
"answer_id": 74507415,
"author": "Kevin C",
"author_id": 4834431,
"author_profile": "https://Stackoverflow.com/users/4834431",
"pm_score": 1,
"selected": false,
"text": "ver ver=13\n sw_vers\nsw_vers | grep ProductVersion\nsw_vers | grep ProductVersion | cut -d':' -f2\nsw_vers | grep ProductVersion | cut -d':' -f2 | tr -d ' '\nsw_vers | grep ProductVersion | cut -d':' -f2 | tr -d ' ' | sed -e 's/ //g'\nprintf \"%.0f\" $(sw_vers | grep ProductVersion | cut -d':' -f2 | tr -d ' ' | sed -e 's/ //g')\n"
},
{
"answer_id": 74508556,
"author": "kiyomi",
"author_id": 18131327,
"author_profile": "https://Stackoverflow.com/users/18131327",
"pm_score": 0,
"selected": false,
"text": "ver=$(printf \"%.0f\" $(sw_vers | grep ProductVersion | cut -d':' -f2 | tr -d ' ' | cut -d'.' -f 1 | sed -e 's/ //g'))\n 13.0.1 printf \"%.0f\" printf \"%.0f\" $(echo some_version_number | tr -d ' ' | cut -d'.' -f 1 | sed -e 's/ //g')\n some_version_number"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18131327/"
] |
74,506,858
|
<p>I am trying to get the nested array from a input value of a checkbox.
How do I handle a nested array?</p>
<p>These are the values:</p>
<pre><code>const othersOptions = [
{procedure:'ORAL PROPHYLAXIS',price: 1000},
{procedure:'TOOTH RESTORATION',price:1200},
{procedure:'TOOTH EXTRACTION',price:800}
];
</code></pre>
<p>This is how I get the values from checkbox. I am guessing that <code>value={[item]}</code> is <code>procedure:'ORAL PROPHYLAXIS',price: 1000</code> <strong>if the <strong>ORAL PROPHYLAXIS</strong> checkbox is checked</strong></p>
<pre><code> <Form>
{othersOptions.map((item, index) => (
<div key={index} className="mb-3">
<Form.Check
value={[item]}
id={[item.procedure]}
type="checkbox"
label={`${item.procedure}`}
onClick={handleChangeCheckbox('Others')}
required
/>
</div>
))}
</Form>
</code></pre>
<p>When I console.log the value it shows that the value is <code>[Object object] this is the value</code>.</p>
<pre><code> const handleChangeCheckbox = input => event => {
var value = event.target.value;
console.log(value, "this is the value")
var isChecked = event.target.checked;
setChecked(current =>
current.map(obj => {
if (obj.option === input) {
if(isChecked){
return {...obj, chosen: [{...obj.chosen, value}] };
}else{
var newArr = obj.chosen;
var index = newArr.indexOf(event.target.value);
newArr.splice(index, 1);
return {...obj, chosen: newArr};
}
}
return obj;
}),
);
console.log(checked);
}
</code></pre>
<p>and this is how I save the nested array:</p>
<pre><code> const [checked, setChecked] = useState([
{ option: 'Others',
chosen: [],
]);
</code></pre>
<p>The reason why I need the procedure and price is so that I can save the values to MongoDB and get the values to another page which is a Create Receipt page. I want the following procedures price to automatically display in the Create Receipt page.Thank you for the help!</p>
|
[
{
"answer_id": 74507415,
"author": "Kevin C",
"author_id": 4834431,
"author_profile": "https://Stackoverflow.com/users/4834431",
"pm_score": 1,
"selected": false,
"text": "ver ver=13\n sw_vers\nsw_vers | grep ProductVersion\nsw_vers | grep ProductVersion | cut -d':' -f2\nsw_vers | grep ProductVersion | cut -d':' -f2 | tr -d ' '\nsw_vers | grep ProductVersion | cut -d':' -f2 | tr -d ' ' | sed -e 's/ //g'\nprintf \"%.0f\" $(sw_vers | grep ProductVersion | cut -d':' -f2 | tr -d ' ' | sed -e 's/ //g')\n"
},
{
"answer_id": 74508556,
"author": "kiyomi",
"author_id": 18131327,
"author_profile": "https://Stackoverflow.com/users/18131327",
"pm_score": 0,
"selected": false,
"text": "ver=$(printf \"%.0f\" $(sw_vers | grep ProductVersion | cut -d':' -f2 | tr -d ' ' | cut -d'.' -f 1 | sed -e 's/ //g'))\n 13.0.1 printf \"%.0f\" printf \"%.0f\" $(echo some_version_number | tr -d ' ' | cut -d'.' -f 1 | sed -e 's/ //g')\n some_version_number"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20542465/"
] |
74,506,870
|
<p>In running the code at the bottom, I add a "total" column to data frame <code>testDF</code>. I need "ID" for instances where "total" > 0. So the output I'm looking for in this example is simply 1 and 50, those ID's where "total" > 0. How would I efficiently compute this using <code>data.table</code>? Noting that the actual database this will be run against has millions of rows so I'm hoping to avoid unnecessary calculations.</p>
<p>I include seemingly extraneous columns "Period_1", "Period_2", and "State", because when I was fooling around with <code>data.table</code> subsetting, in running things like <code>lapply(.SD, sum), by=.(ID)][, if(sum(PUR) > 0) .SD, by=ID]</code>, I was getting errors like
"<em>Error in sum(Period_2) : invalid 'type' (character) of argument</em>"</p>
<p>I'll use these outputs for a "join", which is something I can do in <code>data.table</code> (I think).</p>
<p>Here's a view of the output when running the code:</p>
<p><a href="https://i.stack.imgur.com/c6ICD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/c6ICD.png" alt="enter image description here" /></a></p>
<p>Code:</p>
<pre><code>library(data.table)
testDF <-
data.frame(
ID = as.numeric(c(rep(1,3),rep(50,3),rep(60,3))),
Period_1 = as.numeric(c(1:3,1:3,1:3)),
Period_2 = c("2012-06","2012-07","2012-08","2013-06","2013-07","2013-08","2012-01","2012-02","2012-03"),
PUR = as.numeric(c(rep(10,3),21:23,rep(0,3))),
CA = as.numeric(c(rep(5,3),11:13,rep(0,3))),
State = c("XX","AA","XX","AA","BB","CC","SS","XX","AA")
)
testDF_Adv <- testDF
setDT(testDF_Adv)[, total := sum(PUR + CA), by=list(ID)]
testDF_Adv <- as.data.frame(testDF_Adv)
testDF_Adv
</code></pre>
|
[
{
"answer_id": 74506964,
"author": "DashdotdotDashdotdot",
"author_id": 20548300,
"author_profile": "https://Stackoverflow.com/users/20548300",
"pm_score": 1,
"selected": false,
"text": "library(data.table)\n\ntestDF <-\n data.frame(\n ID = as.numeric(c(rep(1,3),rep(50,3),rep(60,3))),\n Period_1 = as.numeric(c(1:3,1:3,1:3)),\n Period_2 = c(\"2012-06\",\"2012-07\",\"2012-08\",\"2013-06\",\"2013-07\",\"2013-08\",\"2012-01\",\"2012-02\",\"2012-03\"),\n PUR = as.numeric(c(rep(10,3),21:23,rep(0,3))),\n CA = as.numeric(c(rep(5,3),11:13,rep(0,3))),\n State = c(\"XX\",\"AA\",\"XX\",\"AA\",\"BB\",\"CC\",\"SS\",\"XX\",\"AA\")\n )\n\ntestDF_Adv <- testDF\nsetDT(testDF_Adv)[, total:=sum(PUR+CA),by=list(ID)]\ntestDF2 = testDF_Adv[total>0,]\ntestDF2\n"
},
{
"answer_id": 74507016,
"author": "jay.sf",
"author_id": 6574038,
"author_profile": "https://Stackoverflow.com/users/6574038",
"pm_score": 1,
"selected": false,
"text": "setDT(testDF_Adv)[, total := sum(PUR + CA), by=list(ID)][total > 0]\n# ID Period_1 Period_2 PUR CA State total\n# 1: 1 1 2012-06 10 5 XX 45\n# 2: 1 2 2012-07 10 5 AA 45\n# 3: 1 3 2012-08 10 5 XX 45\n# 4: 50 1 2013-06 21 11 AA 102\n# 5: 50 2 2013-07 22 12 BB 102\n# 6: 50 3 2013-08 23 13 CC 102\n"
},
{
"answer_id": 74510057,
"author": "langtang",
"author_id": 4447540,
"author_profile": "https://Stackoverflow.com/users/4447540",
"pm_score": 2,
"selected": true,
"text": "setDT(testDF)[, if(sum(PUR+CA)>0) ID,ID][,ID]\n [1] 1 50\n"
},
{
"answer_id": 74512395,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 0,
"selected": false,
"text": "> setDT(testDF)[, .(ID[sum(PUR + CA) > 0]), ID]$V1\n[1] 1 50\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19657749/"
] |
74,506,894
|
<p>I am getting the error below when I try creating a database. Here is the database.yml:</p>
<pre class="lang-yaml prettyprint-override"><code> default: &default
adapter: postgresql
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
timeout: 5000
development:
adapter: postgresql
encoding: unicode
database: MyDatabase
host: localhost
pool: 5
username: name
password: name`
# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
<<: *default
database: db/test. postgresql
production:
adapter: postgresql
encoding: unicode
database: MyDatabase_Production
host: localhost
pool: 5
username: name
password: name
role: MyRole
</code></pre>
<p>Here is the error:</p>
<pre><code>Database 'MyDatabase' already exists
PG::SyntaxError: ERROR: syntax error at or near "."
LINE 1: CREATE DATABASE "db/test"." postgresql" ENCODING = 'utf8'
^
Couldn't create 'db/test. postgresql' database. Please check your configuration.
rails aborted!
ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR: syntax error at or near "."
LINE 1: CREATE DATABASE "db/test"." postgresql" ENCODING = 'utf8'
^
Caused by:
PG::SyntaxError: ERROR: syntax error at or near "."
LINE 1: CREATE DATABASE "db/test"." postgresql" ENCODING = 'utf8'
^
Tasks: TOP => db:create
(See full trace by running task with --trace)
</code></pre>
<p>I am getting the error above when I run rails db:create up my posgresql database</p>
|
[
{
"answer_id": 74506964,
"author": "DashdotdotDashdotdot",
"author_id": 20548300,
"author_profile": "https://Stackoverflow.com/users/20548300",
"pm_score": 1,
"selected": false,
"text": "library(data.table)\n\ntestDF <-\n data.frame(\n ID = as.numeric(c(rep(1,3),rep(50,3),rep(60,3))),\n Period_1 = as.numeric(c(1:3,1:3,1:3)),\n Period_2 = c(\"2012-06\",\"2012-07\",\"2012-08\",\"2013-06\",\"2013-07\",\"2013-08\",\"2012-01\",\"2012-02\",\"2012-03\"),\n PUR = as.numeric(c(rep(10,3),21:23,rep(0,3))),\n CA = as.numeric(c(rep(5,3),11:13,rep(0,3))),\n State = c(\"XX\",\"AA\",\"XX\",\"AA\",\"BB\",\"CC\",\"SS\",\"XX\",\"AA\")\n )\n\ntestDF_Adv <- testDF\nsetDT(testDF_Adv)[, total:=sum(PUR+CA),by=list(ID)]\ntestDF2 = testDF_Adv[total>0,]\ntestDF2\n"
},
{
"answer_id": 74507016,
"author": "jay.sf",
"author_id": 6574038,
"author_profile": "https://Stackoverflow.com/users/6574038",
"pm_score": 1,
"selected": false,
"text": "setDT(testDF_Adv)[, total := sum(PUR + CA), by=list(ID)][total > 0]\n# ID Period_1 Period_2 PUR CA State total\n# 1: 1 1 2012-06 10 5 XX 45\n# 2: 1 2 2012-07 10 5 AA 45\n# 3: 1 3 2012-08 10 5 XX 45\n# 4: 50 1 2013-06 21 11 AA 102\n# 5: 50 2 2013-07 22 12 BB 102\n# 6: 50 3 2013-08 23 13 CC 102\n"
},
{
"answer_id": 74510057,
"author": "langtang",
"author_id": 4447540,
"author_profile": "https://Stackoverflow.com/users/4447540",
"pm_score": 2,
"selected": true,
"text": "setDT(testDF)[, if(sum(PUR+CA)>0) ID,ID][,ID]\n [1] 1 50\n"
},
{
"answer_id": 74512395,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 0,
"selected": false,
"text": "> setDT(testDF)[, .(ID[sum(PUR + CA) > 0]), ID]$V1\n[1] 1 50\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16443639/"
] |
74,506,904
|
<p>I am making 2 react components (PlayerSearch for sumbitting a form containing target player's name, and PlayerAPI for fetching request). I want it to re-render PlayerAPI everytime I hit the submit button OR everytime the submitted data is updated. So my code looks like this:
In PlayerSearch:</p>
<pre><code>export function PlayerSearch() {
const [formData, setFormData] = useState({ APIkey: "", name: "" });
const [submittedData, setsubmittedData] = useState({ submittedAPIkey:"", submittedname:"" });
const onChange = (event) => {
setFormData({ ...formData, [event.target.name]: event.target.value });
};
function handlesubmit(e) {
e.preventDefault();
setsubmittedData({ ...submittedData, submittedAPIkey: formData.APIkey, submittedname: formData.name });
}
return <div className='player'>
<div className='inputfield'>
<form onSubmit={handlesubmit} method='GET' autoComplete="off">
<div>
<label htmlFor="APIkey">Your API key:</label>
<input placeholder='Your API key' onFocus={(e)=>{e.target.placeholder=''}} type="text" id="APIkey" name="APIkey" value={formData.APIkey} onChange={onChange}/>
</div>
<div>
<label htmlFor="name">Player name:</label>
<input placeholder='Player name' onFocus={(e)=>{e.target.placeholder=''}} type="text" id="name" name="name" value={formData.name} onChange={onChange}/>
</div>
<div>
<button type='submit'>Submit</button>
</div>
</form>
</div>
<div id='result'>
//This is where I render the PlayerAPI
{(submittedData.submittedAPIkey !== "" && submittedData.submittedname !== "") && <PlayerAPI APIkey={submittedData.submittedAPIkey} name={submittedData.submittedname} />}
</div>
</div>
}
</code></pre>
<p>Edit: I've found out that the form submit is not the problem. The problem is in the PlayerAPI and I fixed it.</p>
<p>The PlayerAPI before:</p>
<pre><code>export function PlayerAPI(props) {
const [data, setdata] = useState({ accountId: ''});
const getPlayerID = async () => {
//some API fetching...
}
useEffect(()=>{
getPlayerID();
},[]);
return <div>
<div className='SearchResult'>
hello {JSON.stringify(data)}
</div>
</div>;
}
</code></pre>
<p>The PlayerAPI now:</p>
<pre><code>import { useEffect, useState } from "react";
export function PlayerAPI(props) {
const [data, setdata] = useState({ accountId: ''});
const getPlayerID = async () => {
//some API fetching...
}
useEffect(()=>{
getPlayerID();
},[props.name, props.APIkey]);
return <div>
<div className='SearchResult'>
hello {JSON.stringify(data)}
</div>
</div>;
}
</code></pre>
|
[
{
"answer_id": 74516430,
"author": "lamsmallsmall",
"author_id": 13511160,
"author_profile": "https://Stackoverflow.com/users/13511160",
"pm_score": 1,
"selected": true,
"text": "export function PlayerAPI(props) {\n const [data, setdata] = useState({ accountId: ''});\n const getPlayerID = async () => {\n //some API fetching...\n }\n useEffect(()=>{\n getPlayerID();\n },[]);\n\n return <div>\n <div className='SearchResult'>\n hello {JSON.stringify(data)}\n </div>\n </div>;\n }\n import { useEffect, useState } from \"react\";\n\nexport function PlayerAPI(props) {\n const [data, setdata] = useState({ accountId: ''});\n const getPlayerID = async () => {\n //some API fetching...\n }\n useEffect(()=>{\n getPlayerID();\n },[props.name, props.APIkey]);\n\n return <div>\n <div className='SearchResult'>\n hello {JSON.stringify(data)}\n </div>\n </div>;\n }\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13511160/"
] |
74,506,928
|
<p>Flutter Fix</p>
<pre><code>────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ The plugin google_maps_flutter_android requires a higher Android SDK version. │
│ Fix this issue by adding the following to the file D:\Development\ULTIMAT POS\App POS Backup\UltimatePOS_Flutter_1.7.1\pos\android\app\build.gradle: │
│ android { │
│ defaultConfig { │
│ minSdkVersion 20 │
│ } │
│ } │
│ │
│ │
│ Note that your app won't be available to users running Android SDKs below 20. │
│ Alternatively, try to find a version of this plugin that supports these lower versions of the Android SDK.
│
│ For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration
</code></pre>
|
[
{
"answer_id": 74506953,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 1,
"selected": false,
"text": "android\\app\\build.gradle\n minSdkVersion flutter.minSdkVersion\n minSdkVersion 20 \n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19356936/"
] |
74,506,941
|
<p>I'm coming back to C# after quite a while away from it, but this one is confusing me.</p>
<p>I have a .txt file (<code>strRunnerTXTFile</code>) on my website, and its contents are being read into a variable.</p>
<p>The text file (being read into strRunnerTXTFile) contains this:</p>
<pre><code>"""BrandName"""
No
"""Brand\\Runner 1 Front"""
150mm
"""Brand\\Runner 2 Front"""
198mm
"""Brand\\Runner 3 Front"""
230mm
"""Brand\\Runner 4 Front"""
</code></pre>
<p>After it is read into the variable, the above code now looks like this:</p>
<pre><code>"""BrandName"""
No
"""Brand\\Runner 1 Front"""
150mm
"""Brand\\Runner 2 Front"""198mm
"""Brand\\Runner 3 Front"""
230mm
"""Brand\\Runner 4 Front"""
</code></pre>
<p>The code I'm using to read the file into the variable is this:</p>
<pre><code>WebClient wc = new WebClient(); // create object to use to access web data
byte[] raw = wc.DownloadData(strRunnerTXTFile); // read data text file into variable
if (raw.Length == 0) { ExitWithError("Could not source data from server, or data file is empty.", 5); }
string webData = System.Text.Encoding.UTF8.GetString(raw); // convert into usable format
string[] strTXTInput = webData.Split('\n'); // split array into indexes by new line separation
sRunnerSetName = strTXTInput[0].Replace("\"","");
for (x = 0; x < strTXTInput.Length-1; x++)
{
switch (x)
{
case 0:
sRunnerSetName = strTXTInput[x];
break;
case 1:
sFH = strTXTInput[x];
break;
case 2:
sR1 = strTXTInput[x];
break;
case 3:
sH2 = strTXTInput[x];
break;
case 4:
sR2 = strTXTInput[x];
break;
case 5:
sH3 = strTXTInput[x];
break;
case 6:
sR3 = strTXTInput[x];
break;
case 7:
sH4 = strTXTInput[x];
break;
case 8:
sR4 = strTXTInput[x];
break;
case 9:
sH5 = strTXTInput[x];
break;
case 10:
sR5 = strTXTInput[x];
break;
default:
break;
}
}
createOutputString(RunnerSetFile);
</code></pre>
<p>And then later on ...</p>
<pre><code>public static void createOutputString(string RunnerSetFile)
{
List<Item> list = new List<Item>
{
new Item { Description = sRunnerSetName, SortOrder = iRunnerSetName },
new Item { Description = sFH, SortOrder = iFH },
new Item { Description = sR1, SortOrder = iR1 },
new Item { Description = sH2, SortOrder = iH2 },
new Item { Description = sR2, SortOrder = iR2 },
new Item { Description = sH3, SortOrder = iH3 },
new Item { Description = sR3, SortOrder = iR3 },
new Item { Description = sH4, SortOrder = iH4 },
new Item { Description = sR4, SortOrder = iR4 },
new Item { Description = sH5, SortOrder = iH5 },
new Item { Description = sR5, SortOrder = iR5 }
};
list = list.OrderBy(x => x.SortOrder).ToList();
}
</code></pre>
<p>It seems to be something in the final line there, where it sorts the order. But for the life of me, I cannot figure out why it's combining the two lines. Hopefully one of you can figure this out for me?</p>
|
[
{
"answer_id": 74506953,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 1,
"selected": false,
"text": "android\\app\\build.gradle\n minSdkVersion flutter.minSdkVersion\n minSdkVersion 20 \n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3030087/"
] |
74,506,950
|
<p>I know it sounds weird, as a trade cannot be decided to be a win or a loss until it has been executed, but can we have our original strategy in the form of an indicator in the chart, and after having a win trade by the indicator, only our strategy script should run, and when we lose a trade on the strategy script, our new position will not open until another winning trade is encountered by the indicator script?</p>
<p>Is it possible to do so in TradingView Pinescript code?</p>
|
[
{
"answer_id": 74506953,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 1,
"selected": false,
"text": "android\\app\\build.gradle\n minSdkVersion flutter.minSdkVersion\n minSdkVersion 20 \n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18070351/"
] |
74,506,960
|
<p>this a tkinter gui to input prices. It will add the prices to the empty list and tell the user the the sum of the list. but now i want to use the data outside of the for loop but whatever version of the list i can think of using it always shows up as an empty list.</p>
<pre><code>EXTRAS = []
</code></pre>
<pre><code>def add():
for x in range(1):
EXTRAS.append(user_input1g.get())
EXTRAS_int = [float(x) for x in EXTRAS]
entry_label1g.config(text=str(sum(EXTRAS_int)))
user_input1g.delete(0, 10)
# Entry
user_input1g = tk.Entry(window, width=5)
user_input1g.grid(row=5, column=1)
# Add button
add_button1g = tk.Button(window, text="Add", command=add)
add_button1g.grid(row=5, column=2)
# Empty label
entry_label1g = tk.Label(window, text="")
entry_label1g.grid(row=5, column=4, pady=10)
# $
entry_label2g = tk.Label(window, text="$")
entry_label2g.grid(row=5, column=3, pady=10)
# Description
entry_label3g = tk.Label(window, text="EXTRAS")
entry_label3g.grid(row=5, column=0, pady=10)`
</code></pre>
<p>i tried</p>
<ul>
<li><code>print(EXTRAS)</code> <code>outcome = []</code></li>
<li><code>print(ETRRAS_int)</code> but that doesn't exist outside the loop.</li>
</ul>
<pre><code>def add():
for x in range(1):
EXTRAS.append(user_input1g.get())
EXTRAS_int = [float(x) for x in EXTRAS]
entry_label1g.config(text=str(sum(EXTRAS_int)))
user_input1g.delete(0, 10)
EXTRAS_SUM = sum(EXTRAS_int)
print(EXTRAS_SUM) but that doesnt work either.
</code></pre>
|
[
{
"answer_id": 74507075,
"author": "tryharder",
"author_id": 20553637,
"author_profile": "https://Stackoverflow.com/users/20553637",
"pm_score": -1,
"selected": false,
"text": " import tkinter as tk\nfrom tkinter import *\n\nwindow = Tk()\n\nwindow.title(\"Test Window\")\nwindow.geometry('300x300')\n\nEXTRAS = []\n\ndef add():\n for x in range(1):\n EXTRAS.append(float(user_input1g.get()))\n entry_label1g.config(text=str(sum(EXTRAS)))\n user_input1g.delete(0, 10)\n \n\n\n# Entry\nuser_input1g = tk.Entry(window, width=5)\nuser_input1g.grid(row=5, column=1)\n# Add button\nadd_button1g = tk.Button(window, text=\"Add\", command=add)\nadd_button1g.grid(row=5, column=2)\n# Empty label\nentry_label1g = tk.Label(window, text=\"\")\nentry_label1g.grid(row=5, column=4, pady=10)\n# $\nentry_label2g = tk.Label(window, text=\"$\")\nentry_label2g.grid(row=5, column=3, pady=10)\n# Description\nentry_label3g = tk.Label(window, text=\"EXTRAS\")\nentry_label3g.grid(row=5, column=0, pady=10)\n\nwindow.mainloop()\nprint(EXTRAS)\n"
},
{
"answer_id": 74507188,
"author": "bipbip80",
"author_id": 17987307,
"author_profile": "https://Stackoverflow.com/users/17987307",
"pm_score": -1,
"selected": false,
"text": "global def add():\n global EXTRAS_int\n global EXTRAS\n for x in range(1):\n EXTRAS.append(user_input1g.get())\n EXTRAS_int = [float(x) for x in EXTRAS]\n entry_label1g.config(text=str(sum(EXTRAS_int)))\n user_input1g.delete(0, 10)\n"
},
{
"answer_id": 74510681,
"author": "tryharderagain",
"author_id": 20556712,
"author_profile": "https://Stackoverflow.com/users/20556712",
"pm_score": 2,
"selected": true,
"text": "import tkinter as tk\nfrom tkinter import *\n\nwindow = Tk()\n\nwindow.title(\"Test Window\")\nwindow.geometry('300x300')\n\nEXTRAS = []\nEXTRAS_SUM = 0\n\ndef add():\n global EXTRAS_SUM\n EXTRAS.append(float(user_input1g.get())) \n entry_label1g.config(text=str(sum(EXTRAS)))\n user_input1g.delete(0, 10)\n EXTRAS_SUM = sum(EXTRAS)\n\n\n# Entry\nuser_input1g = tk.Entry(window, width=5)\nuser_input1g.grid(row=5, column=1)\n# Add button\nadd_button1g = tk.Button(window, text=\"Add\", command=add)\nadd_button1g.grid(row=5, column=2)\n# Empty label\nentry_label1g = tk.Label(window, text=\"\")\nentry_label1g.grid(row=5, column=4, pady=10)\n# $\nentry_label2g = tk.Label(window, text=\"$\")\nentry_label2g.grid(row=5, column=3, pady=10)\n# Description\nentry_label3g = tk.Label(window, text=\"EXTRAS\")\nentry_label3g.grid(row=5, column=0, pady=10)\n\nwindow.mainloop()\nprint(EXTRAS) #output: [12.0, 2.0, 5.5]\nprint(EXTRAS_SUM) #output: 19.5\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20039502/"
] |
74,506,980
|
<p>I want to replace all values in my df that are float (excluding nans), with the name of the index of the corresponding row.</p>
<p>I have this:</p>
<pre><code>index1 10.0 190.6
index2 17.9 NaN
index3 NaN 8.0
index4 9.0 70.0
</code></pre>
<p>I want to have this:</p>
<pre><code>index1 index1 index1
index2 index2 NaN
index3 NaN index3
index4 index4 index4
</code></pre>
<p>Any ideas?</p>
|
[
{
"answer_id": 74507316,
"author": "Nuri Taş",
"author_id": 19255749,
"author_profile": "https://Stackoverflow.com/users/19255749",
"pm_score": 3,
"selected": true,
"text": "np.nan df.where output = df.where(df.isna(), df.index.tolist())\n 1 2\n0 \nindex1 index1 index1\nindex2 index2 NaN\nindex3 NaN index3\nindex4 index4 index4\n"
},
{
"answer_id": 74507486,
"author": "Gabino Antuña Ortiz",
"author_id": 17351698,
"author_profile": "https://Stackoverflow.com/users/17351698",
"pm_score": 0,
"selected": false,
"text": "for column in df.columns:\n\n df[column] = [e for e in df.index if df[column].notna]\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13083905/"
] |
74,506,996
|
<p>I want to get the keys of an enum as a type, to make my application type safe in other parts.</p>
<p>Take a look at this code snippet:</p>
<pre><code>enum Layers {
Front = 1,
Middle = 2,
Back = 3,
}
type LayerKeys = key in Layers; // <--- THIS PSEUDOCODE IS NOT WORKING
type LayerConfig = Map<LayerKeys, {}>;
</code></pre>
<p>How can I correctly get the enum keys here?</p>
|
[
{
"answer_id": 74509389,
"author": "mikrowdev",
"author_id": 18715249,
"author_profile": "https://Stackoverflow.com/users/18715249",
"pm_score": 0,
"selected": false,
"text": "enums enum Layers {\n Front = 1,\n Middle = 2,\n Back = 3,\n}\n\nconst keys = $enum(Layers).getKeys();\n\n\ntype LayerKeys = typeof keys[number]\n\ntype LayerConfig = Map<LayerKeys, {}>;\n\n $enum(Layers).getKeys()"
},
{
"answer_id": 74510622,
"author": "jcalz",
"author_id": 2887218,
"author_profile": "https://Stackoverflow.com/users/2887218",
"pm_score": 1,
"selected": false,
"text": "keyof Layers typeof type LayerKeys = keyof typeof Layers\n// type LayerKeys = \"Front\" | \"Middle\" | \"Back\"\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74506996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7036402/"
] |
74,507,006
|
<p>Let's suppose I have the following repository:</p>
<pre><code>public interface ApplicationRepository extends JpaRepository<Application, Integer> {
public boolean existsByCode(String code);
public Optional<Application> findByCode(String code);
}
</code></pre>
<p>And the following service:</p>
<pre><code>@Service
@RequiredArgsConstructor
public class ApplicationService {
private final ApplicationRepository appRepo;
public Application findById(Integer id) throws RecordNotFoundException {
return appRepo.findById(id)
.orElseThrow(() -> new RecordNotFoundException("Application with id: " + id + " could not be found"));
}
public boolean existsByCode(String code) {
return appRepo.existsByCode(code);
}
public Application findByCode(String code) throws RecordNotFoundException {
return appRepo.findByCode(code).orElseThrow(
() -> new RecordNotFoundException("Application with code: " + code + " could not be found"));
}
}
</code></pre>
<ol>
<li><p>Since default repository methods have @Transactional(readOnly = true), should I add the annotation on my custom methods? If so it's better to add the annotation on service methods or repository's?</p>
</li>
<li><p>If I have a third method, which call 2 other methods marked with @Transactional(readOnly = true), is it better to mark also this method with the annotation?</p>
</li>
</ol>
|
[
{
"answer_id": 74509389,
"author": "mikrowdev",
"author_id": 18715249,
"author_profile": "https://Stackoverflow.com/users/18715249",
"pm_score": 0,
"selected": false,
"text": "enums enum Layers {\n Front = 1,\n Middle = 2,\n Back = 3,\n}\n\nconst keys = $enum(Layers).getKeys();\n\n\ntype LayerKeys = typeof keys[number]\n\ntype LayerConfig = Map<LayerKeys, {}>;\n\n $enum(Layers).getKeys()"
},
{
"answer_id": 74510622,
"author": "jcalz",
"author_id": 2887218,
"author_profile": "https://Stackoverflow.com/users/2887218",
"pm_score": 1,
"selected": false,
"text": "keyof Layers typeof type LayerKeys = keyof typeof Layers\n// type LayerKeys = \"Front\" | \"Middle\" | \"Back\"\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11191394/"
] |
74,507,010
|
<p>My goal is to take my very simple "hello world" two-class SpringBoot app and deploy it on Tomcat and show a ThymeLeaf template. I'm compiling with JDK 17 with no errors.</p>
<p>No JAR or WAR (I've tried both, exploded and non-exploded) migrate to the Tomcat directories.</p>
<p>My question is:</p>
<p><strong>Where are the key areas to control deployment from either IntelliJ building methods to Maven settings?</strong></p>
<p>I never see any files migrating regardless of what settings I choose.</p>
<p>The <code>Deployments</code> tab is very confusing to me. I can't see any physical location specified in the settings to ensure things get where they need to be. I've gone through numerous tutorials and nothing causes files to be moved for SpringBoot. I get a <code>404</code> error for every output on localhost.</p>
<p>Thank you in advance.</p>
<p>My app:</p>
<pre><code>
@SpringBootApplication
public class MagicVisionApplication {
public static void main(String[] args) {
SpringApplication.run(MagicVisionApplication.class, args);
}
}
@Controller
public class HomeController {
@RequestMapping(value={"", "/", "home"})
public String displayHomePage(Model model) {
model.addAttribute("username", "John Doe");
return "home.html";
}
}```
</code></pre>
|
[
{
"answer_id": 74512814,
"author": "Dr Tyrell",
"author_id": 6002991,
"author_profile": "https://Stackoverflow.com/users/6002991",
"pm_score": 0,
"selected": false,
"text": "Facets Artifacts"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6002991/"
] |
74,507,060
|
<p>I'm still doing the exercise from the book and the one exercise says that I should create a function: <code>value :: Hand -> Int</code>, which returns the value of the hand.</p>
<p>My code so far looks like this:</p>
<pre><code>data Hand = PairOf Rank | ThreeOf1 Rank | ThreeOf2 Suit
value: Hand -> Int
otherwise = 0
--
</code></pre>
<p>I now have another problem, because I don't know how to describe "Nothing".
Nothing is described here as a possible hand combination in which Pair, ThreeOf1 and ThreeOf2 do not occur.
Would otherwise = 0 work or doesn't that make much sense?</p>
<p>Thanks again for the suggestions, I corrected them! Thanks also in advance for explanations and help.</p>
|
[
{
"answer_id": 74512814,
"author": "Dr Tyrell",
"author_id": 6002991,
"author_profile": "https://Stackoverflow.com/users/6002991",
"pm_score": 0,
"selected": false,
"text": "Facets Artifacts"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,507,067
|
<pre><code>import os
print("enter folder name")
FolderName = input()
flag = os.path.isabs(FolderName)
if flag == False:
path = os.path.abspath(FolderName)
print("The absolute path is: " ,path)
</code></pre>
<p>What am I doing wrong here? Let's say the Folder name input is Neon.</p>
<p>The code output gives <code>C:\Users\Desktop\Codes\Neon\Neon</code></p>
<p>Instead what I want is: <code>C:\Users\Desktop\Codes\Neon\</code></p>
|
[
{
"answer_id": 74507151,
"author": "Alexander",
"author_id": 17829451,
"author_profile": "https://Stackoverflow.com/users/17829451",
"pm_score": 1,
"selected": false,
"text": "os.path.abspath 'Neon' C:\\Users\\Desktop\\Codes\\Neon C:\\Users\\Desktop\\Neon\\Neon fkdjfkjdsk C:\\Users\\Desktop\\Neon\\fkdjfkjdsk os.getcwd()\n os.path.abspath(path)"
},
{
"answer_id": 74507152,
"author": "Amit Itzkovitch",
"author_id": 10574201,
"author_profile": "https://Stackoverflow.com/users/10574201",
"pm_score": 0,
"selected": false,
"text": "C:\\Users\\Desktop\\Codes\\Neon\\ os.path.abspath(\"Neon\") C:\\Users\\Desktop\\Codes\\Neon\\Neon os.path.abspath(\".\")\n"
},
{
"answer_id": 74507231,
"author": "Vasu Deo.S",
"author_id": 9042078,
"author_profile": "https://Stackoverflow.com/users/9042078",
"pm_score": 0,
"selected": false,
"text": "path os abspath import os\n\nos.chdir(r\"C:\\Users\\Desktop\\Codes\")\n\nprint(\"enter folder name\")\nFolderName = input()\n\nflag = os.path.isabs(FolderName)\n\nif flag == False:\n path = os.path.abspath(FolderName)\n print(\"The absolute path is: \" ,path)\n isdir"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19526460/"
] |
74,507,070
|
<p>BigQuery documentation describes <a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical#path_expressions" rel="nofollow noreferrer">path expressions</a>, which look like this:</p>
<pre><code>foo.bar
foo.bar/25
foo/bar:25
foo/bar/25-31
/foo/bar
/25/foo/bar
</code></pre>
<p>But it doesn't say a lot about how and where these path expressions are used. It only briefly mentions:</p>
<blockquote>
<p>A path expression describes how to navigate to an object in a graph of objects.</p>
</blockquote>
<ul>
<li>But what is this graph of objects?</li>
<li>How would you use this syntax with a graph of objects?</li>
<li>What's the meaning of a path expression like <code>foo/bar/25-31</code>?</li>
</ul>
<p>My question is: <strong>what are these Path Expressions the official documentation describes?</strong></p>
<p>I've searched through BigQuery docs but haven't managed to find any other mention of these path expressions. <strong>Is this syntax actually part of BigQuery SQL at all?</strong></p>
<h2>What I've found out so far</h2>
<p>There is an <a href="https://stackoverflow.com/questions/73188154/what-is-a-path-expression-in-bigquery">existing question</a>, which asks roughly the same thing, but for some reason it's downvoted and none of the answers are correct. Though the question it asks is more about a specific detail of the path expression syntax.</p>
<p>Anyway, the answers there propose a few hypotheses as to what path expressions are:</p>
<p><strong>It's not a syntax for referencing tables</strong></p>
<p>The BigQuery Legacy SQL uses syntax that's similar to path expressions for referencing tables:</p>
<pre><code>SELECT state, year FROM [bigquery-public-data:samples.natality]
</code></pre>
<p>But that syntax is only valid in BigQuery Legacy SQL. In the new Google Standard SQL it produces a syntax error. There's a separate documentation for <a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#table_path" rel="nofollow noreferrer">table path syntax</a>, which is different from path expression syntax.</p>
<p><strong>It's not JSONPath syntax</strong></p>
<p><a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/json_functions#JSONPath_format" rel="nofollow noreferrer">JSONPath</a> syntax is documented elsewhere and looks like:</p>
<pre><code>SELECT JSON_QUERY(json_text, '$.class.students[0]')
</code></pre>
<p><strong>It's not a syntax for accessing JSON object graph</strong></p>
<p>There's a separate <a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/operators#json_subscript_operator" rel="nofollow noreferrer">JSON subscript operator</a> syntax, which looks like so:</p>
<pre><code>SELECT json_value.class.students[0]['name']
</code></pre>
<h2>My current hypothesis</h2>
<p>My best guess is that BigQuery doesn't actually support such syntax, and the description in the docs is a mistake.</p>
<p>But please, prove me wrong. I'd really like to know because I'm trying to write a parser for BigQuery SQL, and to do so, I need to understand the whole syntax that BigQuery allows.</p>
|
[
{
"answer_id": 74507151,
"author": "Alexander",
"author_id": 17829451,
"author_profile": "https://Stackoverflow.com/users/17829451",
"pm_score": 1,
"selected": false,
"text": "os.path.abspath 'Neon' C:\\Users\\Desktop\\Codes\\Neon C:\\Users\\Desktop\\Neon\\Neon fkdjfkjdsk C:\\Users\\Desktop\\Neon\\fkdjfkjdsk os.getcwd()\n os.path.abspath(path)"
},
{
"answer_id": 74507152,
"author": "Amit Itzkovitch",
"author_id": 10574201,
"author_profile": "https://Stackoverflow.com/users/10574201",
"pm_score": 0,
"selected": false,
"text": "C:\\Users\\Desktop\\Codes\\Neon\\ os.path.abspath(\"Neon\") C:\\Users\\Desktop\\Codes\\Neon\\Neon os.path.abspath(\".\")\n"
},
{
"answer_id": 74507231,
"author": "Vasu Deo.S",
"author_id": 9042078,
"author_profile": "https://Stackoverflow.com/users/9042078",
"pm_score": 0,
"selected": false,
"text": "path os abspath import os\n\nos.chdir(r\"C:\\Users\\Desktop\\Codes\")\n\nprint(\"enter folder name\")\nFolderName = input()\n\nflag = os.path.isabs(FolderName)\n\nif flag == False:\n path = os.path.abspath(FolderName)\n print(\"The absolute path is: \" ,path)\n isdir"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15982/"
] |
74,507,105
|
<p>i try to concatenate two .txt in loops, here is the file</p>
<pre class="lang-bash prettyprint-override"><code>mn@LeNOVO-220414-A:/mnt/c/Users/LeNOVO/Alnus$ ls
Alnus1.txt Alnus2.txt Alnus3.txt Alnus4.txt Bobi1.txt Bobi2.txt Bobi3.txt Bobi4.txt`
</code></pre>
<p>I try to combine Alnus1 and Bobi1 into a new file named combination1.txt</p>
<p>I am new in bash and need guidance
I here is my failed trial, please take a look.</p>
<pre><code>mn@LeNOVO-220414-A:/mnt/c/Users/LeNOVO/Alnus$ ls
Alnus1.txt Alnus2.txt Alnus3.txt Alnus4.txt Bobi1.txt Bobi2.txt Bobi3.txt Bobi4.txt
mn@LeNOVO-220414-A:/mnt/c/Users/LeNOVO/Alnus$ for name in *1.txt
> do
> other = "${name/1/1}"
> cat "$name" "%other" > "$combination1"
> done
other: command not found
-bash: : No such file or directory
other: command not found
-bash: : No such file or directory
</code></pre>
<p>I try to combine Alnus1 and Bobi1 into a new file named combination1.txt</p>
|
[
{
"answer_id": 74507259,
"author": "Amit Itzkovitch",
"author_id": 10574201,
"author_profile": "https://Stackoverflow.com/users/10574201",
"pm_score": -1,
"selected": false,
"text": "for i in {1..4}; do\n cat \"Alnus${i}.txt\" \"Bobi${i}.txt\" > \"combination${i}.txt\"\ndone\n find . -name \"Alus*.txt\" | wc -l for i in $(seq 1 \"$(find . -name \"Alnus*.txt\" | wc -l)\"); do\n cat \"Alnus${i}.txt\" \"Bobi${i}.txt\" > \"combination${i}.txt\"\ndone\n"
},
{
"answer_id": 74507588,
"author": "M. Nejat Aydin",
"author_id": 13809001,
"author_profile": "https://Stackoverflow.com/users/13809001",
"pm_score": 2,
"selected": true,
"text": "for file in Alnus*.txt; do\n suffix=${file#Alnus}\n cat \"$file\" \"Bobi$suffix\" > \"combination$suffix\"\ndone\n ${file#Alnus} file Alnus"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20527343/"
] |
74,507,106
|
<p>As No import any library To Do This</p>
<pre><code>x=[['A',1],['B',2],['C',3]]
y=[['A',100],['B',200],['C',300]]
z=[['A',1000],['B',2000],['C',3000]]
output must:
{'A':[1,100,1000],'B':[2,200,2000],'C':[3,300,3000]}
</code></pre>
<p>I tried :</p>
<pre><code>dic=dict(filter(lambda i:i[0]==i[0],[x,y,z]))
</code></pre>
<p>So As Data I need first duplicated value to key , and common values to this key as list</p>
|
[
{
"answer_id": 74507131,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 3,
"selected": true,
"text": "x = [[\"A\", 1], [\"B\", 2], [\"C\", 3]]\ny = [[\"A\", 100], [\"B\", 200], [\"C\", 300]]\nz = [[\"A\", 1000], [\"B\", 2000], [\"C\", 3000]]\n\nout = {}\nfor l in (x, y, z):\n for a, b in l:\n out.setdefault(a, []).append(b)\n\nprint(out)\n {\"A\": [1, 100, 1000], \"B\": [2, 200, 2000], \"C\": [3, 300, 3000]}\n dict.setdefault x = [[\"A\", 1], [\"B\", 2], [\"C\", 3]]\ny = [[\"A\", 100], [\"B\", 200], [\"C\", 300]]\nz = [[\"A\", 1000], [\"B\", 2000], [\"C\", 3000]]\n\nout = {}\nfor l in (x, y, z):\n for a, b in l:\n if a in out:\n out[a].append(b)\n else:\n out[a] = [b]\n\nprint(out)\n"
},
{
"answer_id": 74507143,
"author": "Guy",
"author_id": 5168011,
"author_profile": "https://Stackoverflow.com/users/5168011",
"pm_score": 0,
"selected": false,
"text": "zip dict setdefault d = dict()\nfor k, v in zip(*zip(*x, *y, *z)):\n d.setdefault(k, []).append(v)\n\nprint(d) # {'A': [1, 100, 1000], 'B': [2, 200, 2000], 'C': [3, 300, 3000]}\n"
},
{
"answer_id": 74507199,
"author": "Khaled DELLAL",
"author_id": 15852600,
"author_profile": "https://Stackoverflow.com/users/15852600",
"pm_score": 0,
"selected": false,
"text": "dic_={x[0]: [x[1], y[1],z[1]] for (x,y,z) in zip(x, y,z)}\n >>> dic\n>>> {'A': [1, 100, 1000], 'B': [2, 200, 2000], 'C': [3, 300, 3000]}\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19931353/"
] |
74,507,107
|
<p>App.jsx</p>
<pre><code>import { useState } from 'react';
import './App.css';
import NewsContainer from './Components/NewsContainer';
import { Router, Routes, Route } from "react-router-dom"
function App() {
const [mode, setMode] = useState("light")
const changeMode = () => {
if (mode === "light") {
setMode("dark")
document.body.style.backgroundColor = "rgb(30 41 59)"
} else {
setMode("light")
document.body.style.backgroundColor = "white"
}
}
return (
<Router>
<div className='justify-evenly'>
<Routes>
<Route exact path="/" element={<NewsContainer key="general" mode={mode} changeMode={changeMode} category="general" />} />
<Route exact path='/sports' element={<NewsContainer key="sports" mode={mode} changeMode={changeMode} category="sports" />} />
<Route exact path='/buisness' element={<NewsContainer key="buisness" mode={mode} changeMode={changeMode} category="buisness" />} />
<Route exact path='/entertainment' element={<NewsContainer key="entertainment" mode={mode} changeMode={changeMode} category="entertainment" />} />
<Route exact path='/health' element={<NewsContainer key="health" mode={mode} changeMode={changeMode} category="health" />} />
</Routes>
</div>
</Router>
);
}
export default App;
</code></pre>
<p>Navbar.jsx</p>
<pre><code>import { Link } from "react-router-dom";
function Navbar({ mode, changeMode }) {
return (
<div
className={`${mode === "light" ? "bg-gray-100" : "dark : bg-slate-900"} `}
>
<header className="text-gray-600 body-font">
<div className="container mx-auto flex flex-wrap p-5 flex-col md:flex-row items-center">
<li
className={`flex title-font font-medium list-none items-center text-${
mode === "light " ? "gray-900" : "white"
} mb-4 md:mb-0 cursor-pointer`}
>
<span
className={`ml-3 text-xl text-${
mode === "light" ? "black" : "white"
}`}
>
<Link to="/">Hind News</Link>
</span>
</li>
<nav className="md:mr-auto md:ml-4 md:py-1 md:pl-4 md:border-l md:border-gray-400 flex flex-wrap items-center text-base justify-center list-none cursor-pointer">
<li
className={`mr-5 hover:text-${
mode === "light" ? "dark : gray-900" : "white"
}`}
>
<Link to="/sport"> Sports </Link>
</li>
<li
className={`mr-5 hover:text-${
mode === "light" ? "dark : gray-900" : "white"
}`}
>
<Link to="/buisness">Buisness </Link>
</li>
<li
className={`mr-5 hover:text-${
mode === "light" ? " dark:gray-900" : "white"
}`}
>
<Link to="/entertainment">Entertainment </Link>
</li>
<li
className={`mr-5 hover:text-${
mode === "light" ? "dark : gray-900" : "white"
}`}
>
<Link to="/health">Health </Link>
</li>
</nav>
<input
type="text"
className="inline-flex items-center bg-gray-200 border-0 py-1 px-3 focus:outline-none hover:bg-gray-300 rounded text-base mt-4 md:mt-0"
/>
<button className="inline-flex items-center bg-gray-100 border-0 py-1 px-3 focus:outline-none hover:bg-gray-200 rounded text-base mt-4 md:mt-0">
Search
<svg
fill="none"
stroke="currentColor"
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
className="w-4 h-4 ml-1"
viewBox="0 0 24 24"
>
<path d="M5 12h14M12 5l7 7-7 7"></path>
</svg>
</button>
<div className="flex justify-center">
<div className="flex justify-center">
<div className="form-check form-switch">
<input
className="form-check-input appearance-none w-9 -ml-10 rounded-full float-left h-5 align-top bg-white bg-no-repeat bg-contain bg-gray-300 focus:outline-none cursor-pointer shadow-sm ml-60"
type="checkbox"
role="switch"
id="flexSwitchCheckDefault"
onClick={changeMode}
/>
<label
className={`form-check-label inline-block text-${
mode === "light" ? "gray-900" : "white"
} `}
htmlFor="flexSwitchCheckDefault"
>
{" "}
Switch Mode
</label>
</div>
</div>
</div>
</div>
</header>
</div>
);
}
export default Navbar;
</code></pre>
<p>Error on console</p>
<blockquote>
<p>Uncaught TypeError: Cannot read properties of undefined (reading
'pathname')</p>
<p>The above error occurred in the <code><Router></code> component:</p>
<pre><code>at Router (http://localhost:3000/static/js/bundle.js:39615:15)
at App (http://localhost:3000/static/js/bundle.js:33:74)
</code></pre>
<p>Consider adding an error boundary to your tree to customize error
handling behavior. Visit <a href="https://reactjs.org/link/error-boundaries" rel="nofollow noreferrer">https://reactjs.org/link/error-boundaries</a> to
learn more about error boundaries.</p>
</blockquote>
|
[
{
"answer_id": 74507225,
"author": "Tomer_Ra",
"author_id": 11971765,
"author_profile": "https://Stackoverflow.com/users/11971765",
"pm_score": 1,
"selected": false,
"text": "<Link to=\"/sport\"> Sports </Link>\n <Route exact path='/sports' element={<NewsContainer key=\"sports\" mode={mode} changeMode={changeMode} category=\"sports\" />} />\n"
},
{
"answer_id": 74507429,
"author": "Jonathan Wieben",
"author_id": 7879109,
"author_profile": "https://Stackoverflow.com/users/7879109",
"pm_score": 2,
"selected": true,
"text": "BrowserRouter Router Router"
},
{
"answer_id": 74530835,
"author": "Drew Reese",
"author_id": 8690857,
"author_profile": "https://Stackoverflow.com/users/8690857",
"pm_score": 0,
"selected": false,
"text": "Router import { Router, Routes, Route } from \"react-router-dom\"\n declare function Router(\n props: RouterProps\n): React.ReactElement | null;\n\ninterface RouterProps {\n basename?: string;\n children?: React.ReactNode;\n location: Partial<Location> | string; // <-- missing\n navigationType?: NavigationType;\n navigator: Navigator; // <-- missing\n static?: boolean;\n}\n location navigator location pathname Router BrowserRouter HashRouter Router import { BrowserRouter as Router, Routes, Route } from \"react-router-dom\";\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19937233/"
] |
74,507,123
|
<p>Interviewer asked me that what is the data type used by set internally in python and what is the time complexity of inserting value in set.</p>
<p>I tried to search on google but I am not getting any specific answer in google search.</p>
<p>Also, I tried to find the set class to check data type used by set in python but not able to find.</p>
|
[
{
"answer_id": 74507225,
"author": "Tomer_Ra",
"author_id": 11971765,
"author_profile": "https://Stackoverflow.com/users/11971765",
"pm_score": 1,
"selected": false,
"text": "<Link to=\"/sport\"> Sports </Link>\n <Route exact path='/sports' element={<NewsContainer key=\"sports\" mode={mode} changeMode={changeMode} category=\"sports\" />} />\n"
},
{
"answer_id": 74507429,
"author": "Jonathan Wieben",
"author_id": 7879109,
"author_profile": "https://Stackoverflow.com/users/7879109",
"pm_score": 2,
"selected": true,
"text": "BrowserRouter Router Router"
},
{
"answer_id": 74530835,
"author": "Drew Reese",
"author_id": 8690857,
"author_profile": "https://Stackoverflow.com/users/8690857",
"pm_score": 0,
"selected": false,
"text": "Router import { Router, Routes, Route } from \"react-router-dom\"\n declare function Router(\n props: RouterProps\n): React.ReactElement | null;\n\ninterface RouterProps {\n basename?: string;\n children?: React.ReactNode;\n location: Partial<Location> | string; // <-- missing\n navigationType?: NavigationType;\n navigator: Navigator; // <-- missing\n static?: boolean;\n}\n location navigator location pathname Router BrowserRouter HashRouter Router import { BrowserRouter as Router, Routes, Route } from \"react-router-dom\";\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12817895/"
] |
74,507,125
|
<p>In a <code>Row</code>, how can I ensure that the <code>Text</code> with "Hello" in it is perfectly centered and not a bit to the left when the right most inner <code>Row</code> widget has more items than the left most inner <code>Row</code> widget?</p>
<p>Notice in the screenshot that the "Hello" is slight to the left.</p>
<p>I tried using a <code>Stack</code> but that seems to not work well if the text is longer than the available space as it causes the text to then overlap the side-colored widgets.</p>
<p>I am using the following code:</p>
<pre><code>Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
Container(
width: 45,
height: 45,
color: Colors.red,
),
],
),
Text(
"Hello",
textAlign: TextAlign.center,
),
Row(
children: [
Container(
width: 45,
height: 45,
color: Colors.purple,
),
Container(
width: 45,
height: 45,
color: Colors.green,
),
],
)
],
),
)
</code></pre>
<img src="https://i.stack.imgur.com/DqQEi.jpg" width="320" />
|
[
{
"answer_id": 74507171,
"author": "OMi Shah",
"author_id": 5882307,
"author_profile": "https://Stackoverflow.com/users/5882307",
"pm_score": 3,
"selected": true,
"text": "Row Text Row Expanded mainAxisAlignmnet Row MainAxisAlignment.end Center(\n child: Row(\n mainAxisAlignment: MainAxisAlignment.spaceBetween,\n children: [\n Expanded(\n child: Row(\n children: [\n Container(\n width: 45,\n height: 45,\n color: Colors.red,\n ),\n ],\n ),\n ),\n const Expanded(\n child: Text(\n \"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.\",\n textAlign: TextAlign.center,\n ),\n ),\n Expanded(\n child: Row(\n mainAxisAlignment: MainAxisAlignment.end,\n children: [\n Container(\n width: 45,\n height: 45,\n color: Colors.purple,\n ),\n Container(\n width: 45,\n height: 45,\n color: Colors.green,\n ),\n ],\n ),\n ),\n ],\n ),\n)\n Wrap Row Center(\n child: Row(\n mainAxisAlignment: MainAxisAlignment.spaceBetween,\n children: [\n Expanded(\n child: Wrap(\n children: [\n Container(\n width: 45,\n height: 45,\n color: Colors.red,\n ),\n ],\n ),\n ),\n const Expanded(\n child: Text(\n \"Ex qui tempor dolore ex aliquip ex consectetur proident excepteur eu. Velit non sint laboris sit. Ut minim proident irure non ullamco deserunt qui. Quis eu tempor consequat amet irure consequat irure elit. Culpa id in laboris reprehenderit veniam voluptate tempor minim eu reprehenderit sit.\",\n textAlign: TextAlign.center,\n ),\n ),\n Expanded(\n child: Wrap(\n alignment: WrapAlignment.end,\n children: [\n Container(\n width: 45,\n height: 45,\n color: Colors.purple,\n ),\n Container(\n width: 45,\n height: 45,\n color: Colors.green,\n ),\n Container(\n width: 45,\n height: 45,\n color: Colors.orange,\n ),\n Container(\n width: 45,\n height: 45,\n color: Colors.red,\n ),\n ],\n ),\n ),\n ],\n ),\n)\n"
},
{
"answer_id": 74507189,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 1,
"selected": false,
"text": "stack Stack(\n alignment: Alignment.center,\n children: [\n Row(\n mainAxisAlignment: MainAxisAlignment.spaceBetween,\n children: [\n Row(\n children: [\n Container(\n width: 45,\n height: 45,\n color: Colors.red,\n ),\n ],\n ),\n Row(\n children: [\n Container(\n width: 45,\n height: 45,\n color: Colors.purple,\n ),\n Container(\n width: 45,\n height: 45,\n color: Colors.green,\n ),\n ],\n )\n ],\n ),\n Text(\n \"Hello\",\n textAlign: TextAlign.center,\n ),\n ],\n ),\n expanded"
},
{
"answer_id": 74507246,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 0,
"selected": false,
"text": "Stack Center(\n child: Stack(\n alignment: Alignment.center,\n children: [\n Row(\n mainAxisAlignment: MainAxisAlignment.spaceBetween,\n children: [\n Row(\n children: [\n Container(\n width: 45,\n height: 45,\n color: Colors.red,\n ),\n ],\n ),\n Row(\n children: [\n Container(\n width: 45,\n height: 45,\n color: Colors.purple,\n ),\n Container(\n width: 45,\n height: 45,\n color: Colors.green,\n ),\n ],\n )\n ],\n ),\n Text(\n \"Hello\",\n textAlign: TextAlign.center,\n ),\n ],\n ),\n);\n"
},
{
"answer_id": 74512871,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 2,
"selected": false,
"text": "max Text() import 'package:flutter/material.dart';\nimport 'package:flutter/scheduler.dart';\nimport 'package:get/get.dart';\n\nimport 'controllers/controller.dart';\nimport 'dart:math' as math;\n\ndouble firstRowWidth = 0;\ndouble secondRowWidth = 0;\ndouble max = 0;\n\nclass TestPage extends StatefulWidget {\n TestPage({super.key});\n\n @override\n State<TestPage> createState() => _TestPageState();\n}\n\nclass _TestPageState extends State<TestPage> {\n final testController = Get.put(TestController());\n\n @override\n void initState() {\n SchedulerBinding.instance.addPersistentFrameCallback((timeStamp) {\n SchedulerBinding.instance.addPostFrameCallback((_) {\n setState(() {\n max = math.max(secondRowWidth, firstRowWidth);\n });\n });\n });\n\n super.initState();\n }\n\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n body: Center(\n child: Stack(\n alignment: Alignment.center,\n children: [\n Row(\n mainAxisAlignment: MainAxisAlignment.spaceBetween,\n children: [\n row2(),\n row1(),\n ],\n ),\n Positioned(\n width: MediaQuery.of(context).size.width - (max * 2),\n child: Text(\n \"Hello\" * 20,\n textAlign: TextAlign.center,\n ),\n ),\n ],\n ),\n ),\n );\n }\n}\n\nclass row1 extends StatelessWidget {\n const row1({super.key});\n\n @override\n Widget build(BuildContext context) {\n SchedulerBinding.instance.addPostFrameCallback((_) {\n firstRowWidth = context.size!.width;\n });\n return Row(\n children: [\n Container(\n width: 45,\n height: 45,\n color: Colors.purple,\n ),\n Container(\n width: 45,\n height: 45,\n color: Colors.green,\n ),\n ],\n );\n }\n}\n\nclass row2 extends StatelessWidget {\n const row2({\n Key? key,\n }) : super(key: key);\n\n @override\n Widget build(BuildContext context) {\n SchedulerBinding.instance.addPostFrameCallback((_) {\n secondRowWidth = context.size!.width;\n });\n return Row(\n children: [\n Container(\n width: 45,\n height: 45,\n color: Colors.red,\n ),\n ],\n );\n }\n}\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1634905/"
] |
74,507,149
|
<p>I'm working on the frontend part of some REST API (link, json validation and in generale controlling)
I'm trying to figure out how it works in the backhand, there should be a database I guess and each API call correspond to a specific query?</p>
<p>could you suggest me guide on how such implementation are usually build?
I'm only finding formal guide on how to shape url for rest API</p>
<p>thanks</p>
<p>It is a quite generale / cultural question, not technical</p>
|
[
{
"answer_id": 74507171,
"author": "OMi Shah",
"author_id": 5882307,
"author_profile": "https://Stackoverflow.com/users/5882307",
"pm_score": 3,
"selected": true,
"text": "Row Text Row Expanded mainAxisAlignmnet Row MainAxisAlignment.end Center(\n child: Row(\n mainAxisAlignment: MainAxisAlignment.spaceBetween,\n children: [\n Expanded(\n child: Row(\n children: [\n Container(\n width: 45,\n height: 45,\n color: Colors.red,\n ),\n ],\n ),\n ),\n const Expanded(\n child: Text(\n \"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.\",\n textAlign: TextAlign.center,\n ),\n ),\n Expanded(\n child: Row(\n mainAxisAlignment: MainAxisAlignment.end,\n children: [\n Container(\n width: 45,\n height: 45,\n color: Colors.purple,\n ),\n Container(\n width: 45,\n height: 45,\n color: Colors.green,\n ),\n ],\n ),\n ),\n ],\n ),\n)\n Wrap Row Center(\n child: Row(\n mainAxisAlignment: MainAxisAlignment.spaceBetween,\n children: [\n Expanded(\n child: Wrap(\n children: [\n Container(\n width: 45,\n height: 45,\n color: Colors.red,\n ),\n ],\n ),\n ),\n const Expanded(\n child: Text(\n \"Ex qui tempor dolore ex aliquip ex consectetur proident excepteur eu. Velit non sint laboris sit. Ut minim proident irure non ullamco deserunt qui. Quis eu tempor consequat amet irure consequat irure elit. Culpa id in laboris reprehenderit veniam voluptate tempor minim eu reprehenderit sit.\",\n textAlign: TextAlign.center,\n ),\n ),\n Expanded(\n child: Wrap(\n alignment: WrapAlignment.end,\n children: [\n Container(\n width: 45,\n height: 45,\n color: Colors.purple,\n ),\n Container(\n width: 45,\n height: 45,\n color: Colors.green,\n ),\n Container(\n width: 45,\n height: 45,\n color: Colors.orange,\n ),\n Container(\n width: 45,\n height: 45,\n color: Colors.red,\n ),\n ],\n ),\n ),\n ],\n ),\n)\n"
},
{
"answer_id": 74507189,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 1,
"selected": false,
"text": "stack Stack(\n alignment: Alignment.center,\n children: [\n Row(\n mainAxisAlignment: MainAxisAlignment.spaceBetween,\n children: [\n Row(\n children: [\n Container(\n width: 45,\n height: 45,\n color: Colors.red,\n ),\n ],\n ),\n Row(\n children: [\n Container(\n width: 45,\n height: 45,\n color: Colors.purple,\n ),\n Container(\n width: 45,\n height: 45,\n color: Colors.green,\n ),\n ],\n )\n ],\n ),\n Text(\n \"Hello\",\n textAlign: TextAlign.center,\n ),\n ],\n ),\n expanded"
},
{
"answer_id": 74507246,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 0,
"selected": false,
"text": "Stack Center(\n child: Stack(\n alignment: Alignment.center,\n children: [\n Row(\n mainAxisAlignment: MainAxisAlignment.spaceBetween,\n children: [\n Row(\n children: [\n Container(\n width: 45,\n height: 45,\n color: Colors.red,\n ),\n ],\n ),\n Row(\n children: [\n Container(\n width: 45,\n height: 45,\n color: Colors.purple,\n ),\n Container(\n width: 45,\n height: 45,\n color: Colors.green,\n ),\n ],\n )\n ],\n ),\n Text(\n \"Hello\",\n textAlign: TextAlign.center,\n ),\n ],\n ),\n);\n"
},
{
"answer_id": 74512871,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 2,
"selected": false,
"text": "max Text() import 'package:flutter/material.dart';\nimport 'package:flutter/scheduler.dart';\nimport 'package:get/get.dart';\n\nimport 'controllers/controller.dart';\nimport 'dart:math' as math;\n\ndouble firstRowWidth = 0;\ndouble secondRowWidth = 0;\ndouble max = 0;\n\nclass TestPage extends StatefulWidget {\n TestPage({super.key});\n\n @override\n State<TestPage> createState() => _TestPageState();\n}\n\nclass _TestPageState extends State<TestPage> {\n final testController = Get.put(TestController());\n\n @override\n void initState() {\n SchedulerBinding.instance.addPersistentFrameCallback((timeStamp) {\n SchedulerBinding.instance.addPostFrameCallback((_) {\n setState(() {\n max = math.max(secondRowWidth, firstRowWidth);\n });\n });\n });\n\n super.initState();\n }\n\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n body: Center(\n child: Stack(\n alignment: Alignment.center,\n children: [\n Row(\n mainAxisAlignment: MainAxisAlignment.spaceBetween,\n children: [\n row2(),\n row1(),\n ],\n ),\n Positioned(\n width: MediaQuery.of(context).size.width - (max * 2),\n child: Text(\n \"Hello\" * 20,\n textAlign: TextAlign.center,\n ),\n ),\n ],\n ),\n ),\n );\n }\n}\n\nclass row1 extends StatelessWidget {\n const row1({super.key});\n\n @override\n Widget build(BuildContext context) {\n SchedulerBinding.instance.addPostFrameCallback((_) {\n firstRowWidth = context.size!.width;\n });\n return Row(\n children: [\n Container(\n width: 45,\n height: 45,\n color: Colors.purple,\n ),\n Container(\n width: 45,\n height: 45,\n color: Colors.green,\n ),\n ],\n );\n }\n}\n\nclass row2 extends StatelessWidget {\n const row2({\n Key? key,\n }) : super(key: key);\n\n @override\n Widget build(BuildContext context) {\n SchedulerBinding.instance.addPostFrameCallback((_) {\n secondRowWidth = context.size!.width;\n });\n return Row(\n children: [\n Container(\n width: 45,\n height: 45,\n color: Colors.red,\n ),\n ],\n );\n }\n}\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18133119/"
] |
74,507,180
|
<p>We've been using RocksDb for years. There's a (.NET) process using RocksDbSharp to generate RocskDb data. There's a C++ library that reads them. Both from 2018 or so. Both use Snappy compression. The C++ library is compiled under C++ 11.</p>
<p>We're trying to upgrade to newer RocksDb now. In unit tests, the new C++ library can create new files and read them just fine. However, it crashes (segmentation fault) on the first <code>rocksdb::DB::Open</code> call when accessing the existing data. More specifically, the call stack goes to <code>LoadTableHandlers</code>.</p>
<p>Here is the source code, nothing fancy:</p>
<pre class="lang-cpp prettyprint-override"><code> rocksdb::DB* db;
rocksdb::Options options;
options.compression = rocksdb::CompressionType::kSnappyCompression;
options.create_if_missing = false;
rocksdb::Status status = rocksdb::DB::Open(options, myValidPath, &db);
</code></pre>
<p>See the call stack below.</p>
<p>ZwWaitForSingleObject 0x00007ffff97ad144
WaitForSingleObjectEx 0x00007ffff6ef306e
pthread_join 0x0000000064945edc
_ZNSt6thread4joinEv 0x000000006fce0577
rocksdb::VersionBuilder::Rep::LoadTableHandlers(rocksdb::InternalStats*, int, bool, bool, std::shared_ptr<rocksdb::SliceTransform const> const&, unsigned long long) 0x00000000009747d8
rocksdb::VersionBuilder::LoadTableHandlers(rocksdb::InternalStats*, int, bool, bool, std::shared_ptr<rocksdb::SliceTransform const> const&, unsigned long long) 0x00000000007e86fb
rocksdb::VersionEditHandler::LoadTables(rocksdb::ColumnFamilyData*, bool, bool) 0x00000000007ea471
rocksdb::VersionEditHandler::CheckIterationResult(rocksdb::log::Reader const&, rocksdb::Status*) 0x00000000007ec8c8
rocksdb::VersionEditHandlerBase::Iterate(rocksdb::log::Reader&, rocksdb::Status*) 0x00000000007ebe4c
rocksdb::VersionSet::Recover(std::vector<rocksdb::ColumnFamilyDescriptor, std::allocatorrocksdb::ColumnFamilyDescriptor > const&, bool, std::__cxx11::basic_string<char, std::char_traits, std::allocator ><em>, bool) 0x00000000005bc135
rocksdb::DBImpl::Recover(std::vector<rocksdb::ColumnFamilyDescriptor, std::allocatorrocksdb::ColumnFamilyDescriptor > const&, bool, bool, bool, unsigned long long</em>, rocksdb::DBImpl::RecoveryContext*) 0x0000000000570caf
rocksdb::DBImpl::Open(rocksdb::DBOptions const&, std::__cxx11::basic_string<char, std::char_traits, std::allocator > const&, std::vector<rocksdb::ColumnFamilyDescriptor, std::allocatorrocksdb::ColumnFamilyDescriptor > const&, std::vector<rocksdb::ColumnFamilyHandle*, std::allocatorrocksdb::ColumnFamilyHandle* >*, rocksdb::DB**, bool, bool) 0x00000000005698bb
rocksdb::DB::Open(rocksdb::Options const&, std::__cxx11::basic_string<char, std::char_traits, std::allocator > const&, rocksdb::DB**) 0x000000000056b88f
main TestMain.cpp:131
__tmainCRTStartup 0x00000000004013c7
mainCRTStartup 0x00000000004014fb
BaseThreadInitThunk 0x00007ffff8a174b4
RtlUserThreadStart 0x00007ffff97626a1
0x0000000000000000</p>
<p>Do we need to tweak something in the options?</p>
|
[
{
"answer_id": 74507171,
"author": "OMi Shah",
"author_id": 5882307,
"author_profile": "https://Stackoverflow.com/users/5882307",
"pm_score": 3,
"selected": true,
"text": "Row Text Row Expanded mainAxisAlignmnet Row MainAxisAlignment.end Center(\n child: Row(\n mainAxisAlignment: MainAxisAlignment.spaceBetween,\n children: [\n Expanded(\n child: Row(\n children: [\n Container(\n width: 45,\n height: 45,\n color: Colors.red,\n ),\n ],\n ),\n ),\n const Expanded(\n child: Text(\n \"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.\",\n textAlign: TextAlign.center,\n ),\n ),\n Expanded(\n child: Row(\n mainAxisAlignment: MainAxisAlignment.end,\n children: [\n Container(\n width: 45,\n height: 45,\n color: Colors.purple,\n ),\n Container(\n width: 45,\n height: 45,\n color: Colors.green,\n ),\n ],\n ),\n ),\n ],\n ),\n)\n Wrap Row Center(\n child: Row(\n mainAxisAlignment: MainAxisAlignment.spaceBetween,\n children: [\n Expanded(\n child: Wrap(\n children: [\n Container(\n width: 45,\n height: 45,\n color: Colors.red,\n ),\n ],\n ),\n ),\n const Expanded(\n child: Text(\n \"Ex qui tempor dolore ex aliquip ex consectetur proident excepteur eu. Velit non sint laboris sit. Ut minim proident irure non ullamco deserunt qui. Quis eu tempor consequat amet irure consequat irure elit. Culpa id in laboris reprehenderit veniam voluptate tempor minim eu reprehenderit sit.\",\n textAlign: TextAlign.center,\n ),\n ),\n Expanded(\n child: Wrap(\n alignment: WrapAlignment.end,\n children: [\n Container(\n width: 45,\n height: 45,\n color: Colors.purple,\n ),\n Container(\n width: 45,\n height: 45,\n color: Colors.green,\n ),\n Container(\n width: 45,\n height: 45,\n color: Colors.orange,\n ),\n Container(\n width: 45,\n height: 45,\n color: Colors.red,\n ),\n ],\n ),\n ),\n ],\n ),\n)\n"
},
{
"answer_id": 74507189,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 1,
"selected": false,
"text": "stack Stack(\n alignment: Alignment.center,\n children: [\n Row(\n mainAxisAlignment: MainAxisAlignment.spaceBetween,\n children: [\n Row(\n children: [\n Container(\n width: 45,\n height: 45,\n color: Colors.red,\n ),\n ],\n ),\n Row(\n children: [\n Container(\n width: 45,\n height: 45,\n color: Colors.purple,\n ),\n Container(\n width: 45,\n height: 45,\n color: Colors.green,\n ),\n ],\n )\n ],\n ),\n Text(\n \"Hello\",\n textAlign: TextAlign.center,\n ),\n ],\n ),\n expanded"
},
{
"answer_id": 74507246,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 0,
"selected": false,
"text": "Stack Center(\n child: Stack(\n alignment: Alignment.center,\n children: [\n Row(\n mainAxisAlignment: MainAxisAlignment.spaceBetween,\n children: [\n Row(\n children: [\n Container(\n width: 45,\n height: 45,\n color: Colors.red,\n ),\n ],\n ),\n Row(\n children: [\n Container(\n width: 45,\n height: 45,\n color: Colors.purple,\n ),\n Container(\n width: 45,\n height: 45,\n color: Colors.green,\n ),\n ],\n )\n ],\n ),\n Text(\n \"Hello\",\n textAlign: TextAlign.center,\n ),\n ],\n ),\n);\n"
},
{
"answer_id": 74512871,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 2,
"selected": false,
"text": "max Text() import 'package:flutter/material.dart';\nimport 'package:flutter/scheduler.dart';\nimport 'package:get/get.dart';\n\nimport 'controllers/controller.dart';\nimport 'dart:math' as math;\n\ndouble firstRowWidth = 0;\ndouble secondRowWidth = 0;\ndouble max = 0;\n\nclass TestPage extends StatefulWidget {\n TestPage({super.key});\n\n @override\n State<TestPage> createState() => _TestPageState();\n}\n\nclass _TestPageState extends State<TestPage> {\n final testController = Get.put(TestController());\n\n @override\n void initState() {\n SchedulerBinding.instance.addPersistentFrameCallback((timeStamp) {\n SchedulerBinding.instance.addPostFrameCallback((_) {\n setState(() {\n max = math.max(secondRowWidth, firstRowWidth);\n });\n });\n });\n\n super.initState();\n }\n\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n body: Center(\n child: Stack(\n alignment: Alignment.center,\n children: [\n Row(\n mainAxisAlignment: MainAxisAlignment.spaceBetween,\n children: [\n row2(),\n row1(),\n ],\n ),\n Positioned(\n width: MediaQuery.of(context).size.width - (max * 2),\n child: Text(\n \"Hello\" * 20,\n textAlign: TextAlign.center,\n ),\n ),\n ],\n ),\n ),\n );\n }\n}\n\nclass row1 extends StatelessWidget {\n const row1({super.key});\n\n @override\n Widget build(BuildContext context) {\n SchedulerBinding.instance.addPostFrameCallback((_) {\n firstRowWidth = context.size!.width;\n });\n return Row(\n children: [\n Container(\n width: 45,\n height: 45,\n color: Colors.purple,\n ),\n Container(\n width: 45,\n height: 45,\n color: Colors.green,\n ),\n ],\n );\n }\n}\n\nclass row2 extends StatelessWidget {\n const row2({\n Key? key,\n }) : super(key: key);\n\n @override\n Widget build(BuildContext context) {\n SchedulerBinding.instance.addPostFrameCallback((_) {\n secondRowWidth = context.size!.width;\n });\n return Row(\n children: [\n Container(\n width: 45,\n height: 45,\n color: Colors.red,\n ),\n ],\n );\n }\n}\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/279174/"
] |
74,507,229
|
<p>I'm a little new here, this is my first post. I have a c++ project in CLion that is structured like so:</p>
<pre><code>project-root/
├─ cmake-build-debug/
├─ controller/
├─ model/
│ ├─ foo/
│ │ ├─ a.h *
│ │ ├─ a.cpp *
│ ├─ bar/
│ │ ├─ b.h *
│ │ ├─ b.cpp *
├─ view/
│ ├─ c.h *
│ ├─ c.cpp *
├─ new_file
├─CMakeLists.txt
├─main.cpp *
</code></pre>
<p>I've starred the actual cpp and h files just for visual purposes.
In a.h, suppose I'd like to include b.h. The way I'd like to do this in a.h is by doing:</p>
<pre><code>#include "project-root/model/bar/b.h"
</code></pre>
<p>Similarly, I'd like to use this pattern for all includes. For example, if I wanted to include a.h in c.h, in c.h I'd do:</p>
<pre><code>#include "project-root/model/foo/a.h"
</code></pre>
<p>And, just one more example, even if I was in main.cpp and I'd like to include c.h, I'd do:</p>
<pre><code>#include "project-root/view/c.h"
</code></pre>
<p>I tried doing the following in my CMakeLists.txt file:</p>
<pre><code>cmake_minimum_required(VERSION 3.22)
project(project-root)
set(CMAKE_CXX_STANDARD 17) // this ".." seems incorrect
include_directories(..)
add_executable(project-root main.cpp <the rest of all the .h and .cpp files>)
</code></pre>
<p>And actually, this works! However, I think it seems a little weird to have <code>include_directories(..)</code>, since there's a relative path above the project root. That doesn't seem correct to me.</p>
<p>I originally thought <code>include_directory(.)</code> would work, but unfortunately, no dice. When I try to do <code>#include project-root/model/bar/b.h</code> in a.h, I get an error saying <code>project-root/model/bar/b.h not found</code></p>
|
[
{
"answer_id": 74507612,
"author": "Tarek Dakhran",
"author_id": 7406469,
"author_profile": "https://Stackoverflow.com/users/7406469",
"pm_score": 0,
"selected": false,
"text": "include_directories(${PROJECT_SOURCE_DIR})\n"
},
{
"answer_id": 74507633,
"author": "Quimby",
"author_id": 7691729,
"author_profile": "https://Stackoverflow.com/users/7691729",
"pm_score": 1,
"selected": false,
"text": ".. project-root #include \"foo.h\" #include <foo.h> <> \"\" <> <> \"\" internal . // root of a git repository\n├── include/\n│ └── project-name/\n│ ├── model/\n│ │ └── foo/\n│ │ └── a.h\n│ └── view/\n│ └── c.h\n├── src/\n│ ├── model/\n│ │ ├── foo/\n│ │ │ └── a.cpp\n│ │ └── bar/\n│ │ ├── b.h\n│ │ └── b.cpp\n│ ├── view/\n│ │ └── c.cpp\n│ └── main.cpp\n└── CMakeLists.txt\n CMakeLists.txt //Global\ncmake_minimum_required(VERSION 3.22)\nproject(project-name)\n//Repository-wide options\nset(CMAKE_CXX_STANDARD 17)\n\n//Local\nadd_executable(project-root)\n\ntarget_include_directories(project-name PUBLIC include)\ntarget_include_directories(project-name PRIVATE src)\n\n// Project-specific options\n// Assumes gcc/clang toolchain as an example.\ntarget_compile_options(project-name -Wall -Wextra -Werror -pedantic)\n\ntarget_sources(project-name \n PUBLIC \n include/project-name/model/foo/a.h\n include/project-name/view/c.h\n PRIVATE\n src/model/foo/b.h\n src/model/foo/b.cpp\n src/view/c.cpp\n src/main.cpp\n)\n target_ //Global CMakeLists.txt add_subdirectory //Local CMakeLists.txt a.h c.h #include <project-name/model/foo/a.h> b.h b.cpp #include \"b.h\" #include \"model/foo/b.h\" <> b.cpp b.h ../ subdir/b.h b.{cpp,h} include /usr/include src src"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20553696/"
] |
74,507,306
|
<p>I have some issue with using Fetch API JavaScript method when sending some simple <code>formData</code> like so:</p>
<pre><code>function register() {
var formData = new FormData();
var textInputName = document.getElementById('textInputName');
var sexButtonActive = document.querySelector('#buttonsMW > .btn.active');
var imagesInput = document.getElementById('imagesInput');
formData.append('name', textInputName.value);
if (sexButtonActive != null){
formData.append('sex', sexButtonActive.html())
} else {
formData.append('sex', "");
}
formData.append('images', imagesInput.files[0]);
fetch('/user/register', {
method: 'POST',
data: formData,
})
.then(response => response.json());
}
document.querySelector("form").addEventListener("submit", register);
</code></pre>
<p>And on the server side (FastAPI):</p>
<pre><code>@app.post("/user/register", status_code=201)
def register_user(name: str = Form(...), sex: str = Form(...), images: List[UploadFile] = Form(...)):
try:
print(name)
print(sex)
print(images)
return "OK"
except Exception as err:
print(err)
print(traceback.format_exc())
return "Error"
</code></pre>
<p>After clicking on the submit button I get <code>Error 422: Unprocessable entity</code>. So, if I'm trying to add header <code>Content-Type: multipart/form-data</code>, it also doesn't help cause I get another <code>Error 400: Bad Request</code>. I want to understand what I am doing wrong, and how to process <code>formData</code> without such errors?</p>
|
[
{
"answer_id": 74507628,
"author": "Chris",
"author_id": 17865804,
"author_profile": "https://Stackoverflow.com/users/17865804",
"pm_score": 2,
"selected": true,
"text": "422 images images List File File Form images: List[UploadFile] = File(...)\n ^^^^ \n UploadFile File() images: List[UploadFile]\n body data fetch() FormData fetch('/user/register', {\n method: 'POST',\n body: formData,\n })\n .then(res => {...\n files form Content-Type multipart/form-data"
},
{
"answer_id": 74509649,
"author": "Egor Zamotaev",
"author_id": 12236467,
"author_profile": "https://Stackoverflow.com/users/12236467",
"pm_score": 0,
"selected": false,
"text": "formData.append('images', imagesInput.files[0]);\n for (const image of imagesInput.files) {\n formData.append('images', image);\n}\n images: List[UploadFile] = File(...) Name: Bob\nSex: Man\nImages: [<starlette.datastructures.UploadFile object at 0x7fe07abf04f0>]\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12236467/"
] |
74,507,313
|
<p>I tried to google my problem but I couldn't found it, that's why I ask.</p>
<p><strong>Error: unresolved reference: AlertDialog</strong></p>
<p><strong>Question:</strong> How to import AlertDialog because if I google it then I see different methods that causing the error above, e.g. <code>import android.app.AlertDialog</code> or <code>import androidx.appcompat.app.AlertDialog</code> or something else, I need something universal that will never break. I'm wondering why the <code>#include <...></code> in C++ never get expired and lasts for many years.</p>
<p>Import from <a href="https://geeksforgeeks.org/how-to-create-a-custom-yes-no-dialog-in-android-with-kotlin/" rel="nofollow noreferrer">https://geeksforgeeks.org/how-to-create-a-custom-yes-no-dialog-in-android-with-kotlin/</a></p>
<pre><code>import android.app.AlertDialog
</code></pre>
<p>Import from <a href="https://www.geeksforgeeks.org/how-to-create-an-alert-dialog-box-in-android/" rel="nofollow noreferrer">https://www.geeksforgeeks.org/how-to-create-an-alert-dialog-box-in-android/</a></p>
<pre><code>import androidx.appcompat.app.AlertDialog;
</code></pre>
<p>Import from <a href="https://www.digitalocean.com/community/tutorials/android-alert-dialog-using-kotlin" rel="nofollow noreferrer">https://www.digitalocean.com/community/tutorials/android-alert-dialog-using-kotlin</a></p>
<pre><code>import android.support.v7.app.AlertDialog;
</code></pre>
<p><strong>Code in "MainActivity.kt" (Kotlin with C++ in Android Studio Dolphin | 2021.3.1 Patch 1)</strong></p>
<pre><code>package com.emcengine.emceditor
import android.app.NativeActivity
import android.os.Bundle
import android.content.Context
import android.view.inputmethod.InputMethodManager
import android.view.KeyEvent
import java.util.concurrent.LinkedBlockingQueue
//_/--------------------------------------------------\_
import android.app.AlertDialog // error: unresolved reference: AlertDialog
// \--------------------------------------------------/
class MainActivity : NativeActivity() {
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
fun showSoftInput() {
val inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.showSoftInput(this.window.decorView, 0)
}
fun hideSoftInput() {
val inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(this.window.decorView.windowToken, 0)
}
// Queue for the Unicode characters to be polled from native code (via pollUnicodeChar())
private var unicodeCharacterQueue: LinkedBlockingQueue<Int> = LinkedBlockingQueue()
// We assume dispatchKeyEvent() of the NativeActivity is actually called for every
// KeyEvent and not consumed by any View before it reaches here
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
if (event.action == KeyEvent.ACTION_DOWN) {
unicodeCharacterQueue.offer(event.getUnicodeChar(event.metaState))
}
return super.dispatchKeyEvent(event)
}
fun pollUnicodeChar(): Int {
return unicodeCharacterQueue.poll() ?: 0
}
//_/--------------------------------------------------\_
fun messageBox() {
AlertDialog.Builder builder // error: unresolved reference: AlertDialog
//builder = new AlertDialog.Builder(this)
}
// \--------------------------------------------------/
}
</code></pre>
|
[
{
"answer_id": 74507964,
"author": "sebschaef",
"author_id": 3672033,
"author_profile": "https://Stackoverflow.com/users/3672033",
"pm_score": 2,
"selected": false,
"text": "AlertDialog import androidx.appcompat.app.AlertDialog val builder: AlertDialog = AlertDialog.Builder(context)\n"
},
{
"answer_id": 74508185,
"author": "m0skit0",
"author_id": 898478,
"author_profile": "https://Stackoverflow.com/users/898478",
"pm_score": 2,
"selected": false,
"text": "import android.app.AlertDialog\n AlertDialog import android.support.v7.app.AlertDialog\n AlertDialog import androidx.appcompat.app.AlertDialog\n AlertDialog"
},
{
"answer_id": 74511512,
"author": "cactustictacs",
"author_id": 13598222,
"author_profile": "https://Stackoverflow.com/users/13598222",
"pm_score": 2,
"selected": false,
"text": "Compat Compat Activities AppCompatActivity Activity Fragment androidx Fragment support AlertDialog androidx.appcompat:appcompat"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19565845/"
] |
74,507,320
|
<p>I have a column where almost every cell is made of a combination of numbers and letters and symbols ("TS-403" or "TSM-7600"). I want every char that's <em>not</em> an integer to be deleted/replaced with an empty string, so that I'm left only with numbers ("403").</p>
<p>I've thought up of two approaches:</p>
<p>I think the best one is to create an array of integers with the numbers 0-9, and then iterate through the cells with a for loop where if the string in a cell contains a char that's <em>not</em> in the array, then that symbol (not the entire cell) should be erased.</p>
<pre><code>Sub fixRequestNmrs()
Dim intArr() as Integer
ReDim intArr(1 to 10)
For i = 0 to 9
intArr(i) = i
Next i
Dim bRange as Range
Set bRange = Sheets(1).Columns(2)
For Each cell in bRange.Cells
if cell.Value
// if cell includes char that is not in the intArr,
// then that char should be deleted/replaced.
...
End Sub()
</code></pre>
<p>Perhaps the second approach is easier, which would be to use the <code>Split()</code> function as the '-' is always followed by the numbers, and then have that first substring replaced with "". I'm very confused on how to use the Split() function in combination with a range and a replace funtion though...</p>
<pre><code>For Each cell in bRange.Cells
Cells.Split(?, "-")
...
</code></pre>
|
[
{
"answer_id": 74507786,
"author": "VBasic2008",
"author_id": 9814069,
"author_profile": "https://Stackoverflow.com/users/9814069",
"pm_score": 3,
"selected": true,
"text": "''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n' Purpose: Returns an integer composed from the digits of a string.\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\nFunction DigitsToInteger(ByVal SearchString As String) As Long\n\n Dim ResultString As String\n Dim Char As String\n Dim n As Long\n \n For n = 1 To Len(SearchString)\n Char = Mid(SearchString, n, 1)\n If Char Like \"[0-9]\" Then ResultString = ResultString & Char\n Next n\n \n If Len(ResultString) = 0 Then Exit Function\n\n DigitsToInteger = CLng(ResultString)\n\nEnd Function\n Sub DigitsToIntegerTEST()\n\n Const FIRST_ROW As Long = 2\n\n ' Read: Reference the (single-column) range.\n \n Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code\n Dim ws As Worksheet: Set ws = wb.Worksheets(\"Sheet1\")\n \n Dim LastRow As Long: LastRow = ws.Cells(ws.Rows.Count, \"B\").End(xlUp).Row\n If LastRow < FIRST_ROW Then Exit Sub ' no data\n \n Dim rg As Range: Set rg = ws.Range(\"B2\", ws.Cells(LastRow, \"B\"))\n Dim rCount As Long: rCount = rg.Rows.Count\n \n ' Read: Return the values from the range in an array.\n \n Dim Data() As Variant\n \n If rCount = 1 Then\n ReDim Data(1 To 1, 1 To 1): Data(1, 1) = rg.Value\n Else\n Data = rg.Value\n End If\n \n ' Modify: Use the function to replace the values with integers.\n \n Dim r As Long\n \n For r = 1 To rCount\n Data(r, 1) = DigitsToInteger(CStr(Data(r, 1)))\n Next r\n \n ' Write: Return the modifed values in the range.\n \n rg.Value = Data\n ' To test the results in the column adjacent to the right, instead use:\n 'rg.Offset(, 1).Value = Data\n\nEnd Sub\n Sub DigitsToIntegerSimpleTest()\n Const S As String = \"TSM-7600sdf\"\n Debug.Print DigitsToInteger(S) ' Result 7600\nEnd Sub\n =DigitsToInteger(A1)\n"
},
{
"answer_id": 74508945,
"author": "Ron Rosenfeld",
"author_id": 2872922,
"author_profile": "https://Stackoverflow.com/users/2872922",
"pm_score": 2,
"selected": false,
"text": "CONCAT =CONCAT(IFERROR(--MID(A1,SEQUENCE(LEN(A1)),1),\"\"))\n"
},
{
"answer_id": 74511266,
"author": "T.M.",
"author_id": 6460297,
"author_profile": "https://Stackoverflow.com/users/6460297",
"pm_score": 1,
"selected": false,
"text": "GetVal() arr String2Arr() Application.Match Instr() Val() Function GetVal(ByVal s As String) As Double\n Dim arr: arr = String2Arr(s): Debug.Print Join(arr, \"|\")\n Dim chars: chars = Split(\" ,',+,-,.,0,A\", \",\")\n Dim catCodes: catCodes = Application.Match(arr, chars) 'No 3rd zero-argument!!\n Dim tmp$: tmp = Join(catCodes, \"\"): Debug.Print Join(catCodes, \"|\")\n Dim pos&: pos = InStr(tmp, 6) ' Pos 6: Digits; pos 1-5,7: other symbols/chars\n GetVal = Val(Mid(s, pos)) ' calculate value of right substring\nEnd Function\n Val String2Arr() Function String2Arr(ByVal s As String)\n s = StrConv(s, vbUnicode)\n String2Arr = Split(s, vbNullChar, Len(s) \\ 2)\nEnd Function\n Dim s As String\n s = \"aA+*&$%(y#,'/\\)!-12034.56blabla\"\n Debug.Print GetVal(s) ' ~~> 12034.56\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20197062/"
] |
74,507,323
|
<p>I need to hide a <code><section></code> in my HTML with JavaScript while highlighting the text or to show it otherwise.</p>
<p>My selection works in this way:</p>
<pre><code>document.addEventListener('click', function(){
var selected = window.getSelection();
var links = document.getElementsByClassName("linkAnnotation");
if (selected == '') {
links.setAttribute('style', 'display:block;');
} else {
links.setAttribute('style', 'display:none;');
}
})
</code></pre>
<p>but this <code>setAttribute</code> does not work as other hundreds of tries that I have done.</p>
<p>Can someone save my life??</p>
<p>Every <code>setAttribute</code>, <code>style.innerHTML</code>, etc.</p>
|
[
{
"answer_id": 74507786,
"author": "VBasic2008",
"author_id": 9814069,
"author_profile": "https://Stackoverflow.com/users/9814069",
"pm_score": 3,
"selected": true,
"text": "''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n' Purpose: Returns an integer composed from the digits of a string.\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\nFunction DigitsToInteger(ByVal SearchString As String) As Long\n\n Dim ResultString As String\n Dim Char As String\n Dim n As Long\n \n For n = 1 To Len(SearchString)\n Char = Mid(SearchString, n, 1)\n If Char Like \"[0-9]\" Then ResultString = ResultString & Char\n Next n\n \n If Len(ResultString) = 0 Then Exit Function\n\n DigitsToInteger = CLng(ResultString)\n\nEnd Function\n Sub DigitsToIntegerTEST()\n\n Const FIRST_ROW As Long = 2\n\n ' Read: Reference the (single-column) range.\n \n Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code\n Dim ws As Worksheet: Set ws = wb.Worksheets(\"Sheet1\")\n \n Dim LastRow As Long: LastRow = ws.Cells(ws.Rows.Count, \"B\").End(xlUp).Row\n If LastRow < FIRST_ROW Then Exit Sub ' no data\n \n Dim rg As Range: Set rg = ws.Range(\"B2\", ws.Cells(LastRow, \"B\"))\n Dim rCount As Long: rCount = rg.Rows.Count\n \n ' Read: Return the values from the range in an array.\n \n Dim Data() As Variant\n \n If rCount = 1 Then\n ReDim Data(1 To 1, 1 To 1): Data(1, 1) = rg.Value\n Else\n Data = rg.Value\n End If\n \n ' Modify: Use the function to replace the values with integers.\n \n Dim r As Long\n \n For r = 1 To rCount\n Data(r, 1) = DigitsToInteger(CStr(Data(r, 1)))\n Next r\n \n ' Write: Return the modifed values in the range.\n \n rg.Value = Data\n ' To test the results in the column adjacent to the right, instead use:\n 'rg.Offset(, 1).Value = Data\n\nEnd Sub\n Sub DigitsToIntegerSimpleTest()\n Const S As String = \"TSM-7600sdf\"\n Debug.Print DigitsToInteger(S) ' Result 7600\nEnd Sub\n =DigitsToInteger(A1)\n"
},
{
"answer_id": 74508945,
"author": "Ron Rosenfeld",
"author_id": 2872922,
"author_profile": "https://Stackoverflow.com/users/2872922",
"pm_score": 2,
"selected": false,
"text": "CONCAT =CONCAT(IFERROR(--MID(A1,SEQUENCE(LEN(A1)),1),\"\"))\n"
},
{
"answer_id": 74511266,
"author": "T.M.",
"author_id": 6460297,
"author_profile": "https://Stackoverflow.com/users/6460297",
"pm_score": 1,
"selected": false,
"text": "GetVal() arr String2Arr() Application.Match Instr() Val() Function GetVal(ByVal s As String) As Double\n Dim arr: arr = String2Arr(s): Debug.Print Join(arr, \"|\")\n Dim chars: chars = Split(\" ,',+,-,.,0,A\", \",\")\n Dim catCodes: catCodes = Application.Match(arr, chars) 'No 3rd zero-argument!!\n Dim tmp$: tmp = Join(catCodes, \"\"): Debug.Print Join(catCodes, \"|\")\n Dim pos&: pos = InStr(tmp, 6) ' Pos 6: Digits; pos 1-5,7: other symbols/chars\n GetVal = Val(Mid(s, pos)) ' calculate value of right substring\nEnd Function\n Val String2Arr() Function String2Arr(ByVal s As String)\n s = StrConv(s, vbUnicode)\n String2Arr = Split(s, vbNullChar, Len(s) \\ 2)\nEnd Function\n Dim s As String\n s = \"aA+*&$%(y#,'/\\)!-12034.56blabla\"\n Debug.Print GetVal(s) ' ~~> 12034.56\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13405870/"
] |
74,507,354
|
<p>I have an assignment about divide and conquer which isn't the problem at all; the actual problem is that I can't convert the given string into the 2dimentional array it wants me to. The problem's running time has to be O(nlogn) which is why I can't use multiple loops for this solution.
The input string would be something like:</p>
<blockquote>
<p>[[0,2,3],[2,5,3] , [1,2022,5] , [2,5,77]]</p>
</blockquote>
<p>And I have to put it into a two dimentional array like so. I saw a few question on stackoverflow like this one, but I can't get the solutions right on Java, that's why I asked this question.
So here is what I have done by far (which I'm super ashamed of):</p>
<pre><code> public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String inputs = scan.nextLine();
String[] numbers=new String[100];
int[][] arr;
numbers=inputs.split("[");
for (String is : numbers) {
System.out.println(is);
}
boolean flag=false;
}
</code></pre>
<p>I realised the split function does not work like that.It gives me errors.</p>
<p>Would you please help me convert a given string that has a 2d array like template to an actual 2d array?I'd be very thankful if you'd help.</p>
|
[
{
"answer_id": 74507786,
"author": "VBasic2008",
"author_id": 9814069,
"author_profile": "https://Stackoverflow.com/users/9814069",
"pm_score": 3,
"selected": true,
"text": "''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n' Purpose: Returns an integer composed from the digits of a string.\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\nFunction DigitsToInteger(ByVal SearchString As String) As Long\n\n Dim ResultString As String\n Dim Char As String\n Dim n As Long\n \n For n = 1 To Len(SearchString)\n Char = Mid(SearchString, n, 1)\n If Char Like \"[0-9]\" Then ResultString = ResultString & Char\n Next n\n \n If Len(ResultString) = 0 Then Exit Function\n\n DigitsToInteger = CLng(ResultString)\n\nEnd Function\n Sub DigitsToIntegerTEST()\n\n Const FIRST_ROW As Long = 2\n\n ' Read: Reference the (single-column) range.\n \n Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code\n Dim ws As Worksheet: Set ws = wb.Worksheets(\"Sheet1\")\n \n Dim LastRow As Long: LastRow = ws.Cells(ws.Rows.Count, \"B\").End(xlUp).Row\n If LastRow < FIRST_ROW Then Exit Sub ' no data\n \n Dim rg As Range: Set rg = ws.Range(\"B2\", ws.Cells(LastRow, \"B\"))\n Dim rCount As Long: rCount = rg.Rows.Count\n \n ' Read: Return the values from the range in an array.\n \n Dim Data() As Variant\n \n If rCount = 1 Then\n ReDim Data(1 To 1, 1 To 1): Data(1, 1) = rg.Value\n Else\n Data = rg.Value\n End If\n \n ' Modify: Use the function to replace the values with integers.\n \n Dim r As Long\n \n For r = 1 To rCount\n Data(r, 1) = DigitsToInteger(CStr(Data(r, 1)))\n Next r\n \n ' Write: Return the modifed values in the range.\n \n rg.Value = Data\n ' To test the results in the column adjacent to the right, instead use:\n 'rg.Offset(, 1).Value = Data\n\nEnd Sub\n Sub DigitsToIntegerSimpleTest()\n Const S As String = \"TSM-7600sdf\"\n Debug.Print DigitsToInteger(S) ' Result 7600\nEnd Sub\n =DigitsToInteger(A1)\n"
},
{
"answer_id": 74508945,
"author": "Ron Rosenfeld",
"author_id": 2872922,
"author_profile": "https://Stackoverflow.com/users/2872922",
"pm_score": 2,
"selected": false,
"text": "CONCAT =CONCAT(IFERROR(--MID(A1,SEQUENCE(LEN(A1)),1),\"\"))\n"
},
{
"answer_id": 74511266,
"author": "T.M.",
"author_id": 6460297,
"author_profile": "https://Stackoverflow.com/users/6460297",
"pm_score": 1,
"selected": false,
"text": "GetVal() arr String2Arr() Application.Match Instr() Val() Function GetVal(ByVal s As String) As Double\n Dim arr: arr = String2Arr(s): Debug.Print Join(arr, \"|\")\n Dim chars: chars = Split(\" ,',+,-,.,0,A\", \",\")\n Dim catCodes: catCodes = Application.Match(arr, chars) 'No 3rd zero-argument!!\n Dim tmp$: tmp = Join(catCodes, \"\"): Debug.Print Join(catCodes, \"|\")\n Dim pos&: pos = InStr(tmp, 6) ' Pos 6: Digits; pos 1-5,7: other symbols/chars\n GetVal = Val(Mid(s, pos)) ' calculate value of right substring\nEnd Function\n Val String2Arr() Function String2Arr(ByVal s As String)\n s = StrConv(s, vbUnicode)\n String2Arr = Split(s, vbNullChar, Len(s) \\ 2)\nEnd Function\n Dim s As String\n s = \"aA+*&$%(y#,'/\\)!-12034.56blabla\"\n Debug.Print GetVal(s) ' ~~> 12034.56\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15433010/"
] |
74,507,517
|
<p>I'm just starting out with angualar and wanted to push data into Firebase Database in angular , currently using post for that but some random data is getting appended into the database.</p>
<p>The code is as follows:</p>
<p>Angular was giving error when not specifying the key , so gave 'value'</p>
<pre><code>this.http.post('https://farmio-3lbue-default-random-rtdb.firebaseio.com/products.json' , { 'value' : 'Carrot'}).subscribe(res=>{
console.log(res , 'post')
}, error=> console.log(error))
</code></pre>
<p>Firebase database snippet:
<a href="https://i.stack.imgur.com/akv9K.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/akv9K.png" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/akv9K.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/akv9K.png" alt="enter image description here" /></a></p>
<p>want to add as the first three items.</p>
<p>PS : data is getting added and getting successful response but is not working as expected</p>
|
[
{
"answer_id": 74508208,
"author": "Avraham Weinstein",
"author_id": 8938503,
"author_profile": "https://Stackoverflow.com/users/8938503",
"pm_score": 0,
"selected": false,
"text": "Array { 'value' : 'Carrot'} 'Carrot' this.http.post('https://farmio-3lbue-default-random-rtdb.firebaseio.com/products.json' , 'Carrot')\n HttpClient post any"
},
{
"answer_id": 74509150,
"author": "Frank van Puffelen",
"author_id": 209103,
"author_profile": "https://Stackoverflow.com/users/209103",
"pm_score": 1,
"selected": false,
"text": "POST -N.... PUT // \nthis.http.put(\n 'https://farmio-3lbue-default-random-rtdb.firebaseio.com/products/4.json',\n // \n { 'value' : 'Carrot'}\n)\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12876430/"
] |
74,507,567
|
<p>How to modify an array based on the value as key?</p>
<pre><code>array(
array(
"name" => "BIBAR",
"cutoff" => 20220725,
"totals" => 5614
),
array(
"name" => "BIBAR",
"cutoff" => 20220810,
"totals" => 5614
),
array(
"name" => "BIBAR",
"cutoff" => 20220825,
"totals" => 5614
)
);
</code></pre>
<p>I tried the following but it's not working:</p>
<pre><code>foreach($cutoffs as $catoff) {
$ii = 0;
$sums[$ii][$catoff] = array_filter($array, function($val){
return $val['cutoff'] === $catoff ? $val['totals'] : $val;
});
$ii++;
}
</code></pre>
<p>My desired array:</p>
<pre><code>array(
'20221025' => array(
12345,
12343,
24442
),
'20221110' => array(
3443,
744334
)
)
</code></pre>
<p>I'm stuck here for hours ... Please help</p>
|
[
{
"answer_id": 74508208,
"author": "Avraham Weinstein",
"author_id": 8938503,
"author_profile": "https://Stackoverflow.com/users/8938503",
"pm_score": 0,
"selected": false,
"text": "Array { 'value' : 'Carrot'} 'Carrot' this.http.post('https://farmio-3lbue-default-random-rtdb.firebaseio.com/products.json' , 'Carrot')\n HttpClient post any"
},
{
"answer_id": 74509150,
"author": "Frank van Puffelen",
"author_id": 209103,
"author_profile": "https://Stackoverflow.com/users/209103",
"pm_score": 1,
"selected": false,
"text": "POST -N.... PUT // \nthis.http.put(\n 'https://farmio-3lbue-default-random-rtdb.firebaseio.com/products/4.json',\n // \n { 'value' : 'Carrot'}\n)\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20476491/"
] |
74,507,600
|
<p>Absolute Kong noob here; I have a small Golang docker container running a simple Api which just returns the datetime (port 3000).
Checked by running http://localhost:3000/timecheck - works.</p>
<pre><code>Installed Kong DB version Postgress conform the Kong instructions.
Created a service:
curl -i -s -X POST http://localhost:8001/services \
--data 'name=ts' \
--data 'url=http://0.0.0.0:3000'
201 Created
Setup the route:
curl -i -X POST http://localhost:8001/services/ts/routes \
--data 'paths[]=/ts' \
--data 'name=ts'
201 created
checked with: curl -X GET http://localhost:8001/services/ts/routes/ts
If I go to http://localhost:8000/ts name resolution failed..
or
http://localhost:8000/timecheck (timecheck being the handler in Golang)
I am doing something VERY wrong? ANY help would be apperciated!!
</code></pre>
|
[
{
"answer_id": 74508208,
"author": "Avraham Weinstein",
"author_id": 8938503,
"author_profile": "https://Stackoverflow.com/users/8938503",
"pm_score": 0,
"selected": false,
"text": "Array { 'value' : 'Carrot'} 'Carrot' this.http.post('https://farmio-3lbue-default-random-rtdb.firebaseio.com/products.json' , 'Carrot')\n HttpClient post any"
},
{
"answer_id": 74509150,
"author": "Frank van Puffelen",
"author_id": 209103,
"author_profile": "https://Stackoverflow.com/users/209103",
"pm_score": 1,
"selected": false,
"text": "POST -N.... PUT // \nthis.http.put(\n 'https://farmio-3lbue-default-random-rtdb.firebaseio.com/products/4.json',\n // \n { 'value' : 'Carrot'}\n)\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2979994/"
] |
74,507,602
|
<p>I try launch my project on react. I wrote Router and when i launch project i see nothing</p>
<p>It's my code, what's wrong ?</p>
<pre><code>import "./App.css";
import "./Components/MainContent/Main/MainContent.module.css"
import "./Components/Header/Header.module.css"
import "./Components/Navbar/Navbar.module.css"
import Header from "./Components/Header/Header";
import Navbar from "./Components/Navbar/Navbar";
import MainContent from "./Components/MainContent/Main/MainContent";
import {Router, Route, Routes} from "react-router-dom";
import Catalog from "./Components/MainContent/Catalog/Catalog"
import Busket from "./Components/MainContent/Busket/Busket"
import Contacts from "./Components/MainContent/Contacts/Contacts"
import Support from "./Components/MainContent/Support/Support"
function App() {
return (
<div className="appWeb">
<Header />
<Navbar />
<Router>
<Routes>
<Route path='/MainContent' element={<MainContent/>} />
<Route path='/Catalog' element={<Catalog/>} />
<Route path='/Busket' element={<Busket/>} />
<Route path='/Contacts' element={<Contacts/>} />
<Route path='/Support' element={<Support/>} />
</Routes>
</Router>
</div>
);
}
export default App;
</code></pre>
<p>I try wrap div className="appWeb" in Router, didn't help</p>
|
[
{
"answer_id": 74508208,
"author": "Avraham Weinstein",
"author_id": 8938503,
"author_profile": "https://Stackoverflow.com/users/8938503",
"pm_score": 0,
"selected": false,
"text": "Array { 'value' : 'Carrot'} 'Carrot' this.http.post('https://farmio-3lbue-default-random-rtdb.firebaseio.com/products.json' , 'Carrot')\n HttpClient post any"
},
{
"answer_id": 74509150,
"author": "Frank van Puffelen",
"author_id": 209103,
"author_profile": "https://Stackoverflow.com/users/209103",
"pm_score": 1,
"selected": false,
"text": "POST -N.... PUT // \nthis.http.put(\n 'https://farmio-3lbue-default-random-rtdb.firebaseio.com/products/4.json',\n // \n { 'value' : 'Carrot'}\n)\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20290737/"
] |
74,507,605
|
<pre><code>sql ="""INSERT INTO birthday(team, birthday)
VALUES ('Norway', {"2020-01-01": "Ram's BDay"}));"""
</code></pre>
<p>Above sql statement throws an error while inserting.</p>
<blockquote>
<p>ProgrammingError: (1064, 'You have an error in your SQL syntax; check
the manual that corresponds to your MySQL server ver</p>
</blockquote>
<p>Based on manual attempts I know it is related to apostrophe. Is it possible to insert the above statement, I don't have the control over apostrophe coming in the data stream.</p>
|
[
{
"answer_id": 74507635,
"author": "Aryan R.H",
"author_id": 14382828,
"author_profile": "https://Stackoverflow.com/users/14382828",
"pm_score": -1,
"selected": false,
"text": "sql ='\"\"\"INSERT INTO birthday(team, birthday)\n VALUES (\\'Norway\\', {\"2020-01-01\": \"Ram\\'s BDay\"}));\"\"\"'\n"
},
{
"answer_id": 74507753,
"author": "Bernd Buffen",
"author_id": 5247279,
"author_profile": "https://Stackoverflow.com/users/5247279",
"pm_score": 0,
"selected": false,
"text": "sql =\"\"\"INSERT INTO birthday(team, birthday)\n VALUES ('Norway', \"{\\\"2020-01-01\\\": \\\"Ram's BDay\\\"}\" );\"\"\"\n sql =\"\"\"INSERT INTO birthday(team, birthday)\n VALUES ('Norway', '{\"2020-01-01\": \"Ram\\'s BDay\"}' );\"\"\"\n mysql> CREATE TABLE birthday(team VARCHAR(100), birthday VARCHAR(100)) ;\nQuery OK, 0 rows affected (0.14 sec)\n\nmysql> \nmysql> INSERT INTO birthday(team, birthday)\n -> VALUES ('Norway', \"{\\\"2020-01-01\\\": \\\"Ram's BDay\\\"}\" );\nQuery OK, 1 row affected (0.06 sec)\n\nmysql> SELECT * FROM birthday;\n+--------+------------------------------+\n| team | birthday |\n+--------+------------------------------+\n| Norway | {\"2020-01-01\": \"Ram's BDay\"} |\n+--------+------------------------------+\n1 row in set (0.03 sec)\n\nmysql> \n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17900863/"
] |
74,507,615
|
<p>I have a fragment in which I have two <code>TextView</code>s with hint texts. When a user clicks on the first one a bottom sheet dialog opens and shows a list of possible options. User selects an option, and the option info is displayed in the first <code>TextView</code> instead of hint text. When the user clicks on the second <code>TextView</code> the very same bottom sheet dialog opens, but shows a filtered list of options (the list is filtered based on the first choice). User selects an option and the option info is displayed in the second <code>TextView</code> instead of the hint text as well. I have achieved to have this by using only one ViewModel for the fragment itself, but it doesn't seem right because the ViewModel does too much. Therefore, I tried using two ViewModels: one for the fragment itself to update when the options are selected, and one for the bottom sheet dialog to load the data and show them in the list. But the issue is that I cannot share the selected option from the bottom sheet dialog ViewModel to the fragment ViewModel. Is there a way to achieve what I want to achieve by using two ViewModels?</p>
|
[
{
"answer_id": 74508028,
"author": "Xəyal Şərifli",
"author_id": 20432696,
"author_profile": "https://Stackoverflow.com/users/20432696",
"pm_score": 0,
"selected": false,
"text": "interface BottomSheetClickListener {\n fun onDialogClick(view: View, string: String)\n}\n class BottomSheetDialog(\n private val listener: BottomSheetClickListener\n) : BottomSheetDialogFragment() {\n textView.setOnClickListener {\n listener.onDialogClick(it,\"String\")\n }\n}\n class HomeFragment : Fragment(), BottomSheetClickListener {\n \n private fun openBottomSheetDialog(){\n val dialog = BottomSheetDialog(this)\n dialog.show(childFragmentManager, \"dialog\")\n }\n\n override fun onDialogClick(string: String, id: Int) {\n //Get string from bottom sheet dialog string\n }\n}\n"
},
{
"answer_id": 74572563,
"author": "Aniruddh Parihar",
"author_id": 8031784,
"author_profile": "https://Stackoverflow.com/users/8031784",
"pm_score": 0,
"selected": false,
"text": "ViewModel Fragment ViewModel ViewModel ViewModel sharedModel = activity?.run {\n ViewModelProviders.of(this)[SharedViewModel::class.java]\n } ?: throw Exception(\"Invalid Activity\")\nlocalViewModel = ViewModelProviders.of(this).get(LocalViewModel::class.java)\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13455858/"
] |
74,507,648
|
<p>I'm trying to create b2c user to sign in only with their user name without entering email address using Microsoft Graph calls.</p>
<p>Usually I use below graph call to create users in normal tenant:</p>
<pre><code>POST https://graph.microsoft.com/v1.0/users
Content-type: application/json
{
"displayName": " ",
"passwordProfile" : {
"password": "password-value",
"forceChangePasswordNextSignIn": false
},
"passwordPolicies": "DisablePasswordExpiration"
}
</code></pre>
<p>I want these users to sign in only with their user name.
Is their any approach to get these from graph calls?</p>
|
[
{
"answer_id": 74514438,
"author": "Sridevi",
"author_id": 18043665,
"author_profile": "https://Stackoverflow.com/users/18043665",
"pm_score": 3,
"selected": true,
"text": "\"signInType\": \"userName\" POST https://graph.microsoft.com/v1.0/users\nContent-type: application/json\n\n{\n \"displayName\": \"Sri Devi\",\n \"identities\": [\n {\n \"signInType\": \"userName\",\n \"issuer\": \"yourb2ctenant.onmicrosoft.com\",\n \"issuerAssignedId\": \"username_of_user\"\n }\n ],\n \"passwordProfile\" : {\n \"password\": \"password-value\",\n \"forceChangePasswordNextSignIn\": false\n },\n \"passwordPolicies\": \"DisablePasswordExpiration\"\n}\n issuer"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19865113/"
] |
74,507,656
|
<p>I created an indicator and then want to use it to test in strategy but my trades are only 2 or 3 while the indicator shows so many in the chart, not sure what am i doing wrong?</p>
<pre><code>strategy('AMI short', overlay = true)
ema5 = ta.ema(close,100)
rsi = ta.rsi(close, 14)
plot(ema100, linewidth = 2, color = color.yellow)
currentcrossbelow = close < low[1]
previousdetachedabove = low[1] > ema100[1]
shortSignal = currentcrossbelow and previousdetachedabove and high < high[1]
bgcolor(shortSignal ? color.new(color.red, 40) : na)
SL = 0.05
TP = 0.10
shortStop = strategy.position_avg_price*(1+SL)
shortProfit = strategy.position_avg_price*(1-TP)
if shortSignal
strategy.entry('Short', strategy.short, 1)
if strategy.position_avg_price > 0
strategy.exit('closeShort', stop = shortStop, limit = shortProfit)
</code></pre>
|
[
{
"answer_id": 74514438,
"author": "Sridevi",
"author_id": 18043665,
"author_profile": "https://Stackoverflow.com/users/18043665",
"pm_score": 3,
"selected": true,
"text": "\"signInType\": \"userName\" POST https://graph.microsoft.com/v1.0/users\nContent-type: application/json\n\n{\n \"displayName\": \"Sri Devi\",\n \"identities\": [\n {\n \"signInType\": \"userName\",\n \"issuer\": \"yourb2ctenant.onmicrosoft.com\",\n \"issuerAssignedId\": \"username_of_user\"\n }\n ],\n \"passwordProfile\" : {\n \"password\": \"password-value\",\n \"forceChangePasswordNextSignIn\": false\n },\n \"passwordPolicies\": \"DisablePasswordExpiration\"\n}\n issuer"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20537640/"
] |
74,507,661
|
<p>This is my code for now,
Id like it to say ADD when hovering</p>
<pre><code>.b:hover {
background: white;
color:rgb(180, 179, 179) ;
}
.b:hover a {
background:white;
color: rgb(180, 179, 179);
}
.b a {
display:inline-block;
width: 98%;
}
</code></pre>
<pre><code><div id="b1"; class = b>
<a href="test.html">9.99€</a>
</div>
</code></pre>
<p>tried everything that i know off</p>
|
[
{
"answer_id": 74507829,
"author": "Martin Dobruský",
"author_id": 20164692,
"author_profile": "https://Stackoverflow.com/users/20164692",
"pm_score": 0,
"selected": false,
"text": "<div id=\"b1\"; class = b>\n <a href=\"test.html\"></a>\n</div>\n .b a {\n display:inline-block;\n width: 98%;\n}\n\n.b a:after {\n content:'9.99€';\n}\n\n.b a:hover:after {\n content:'ADD';\n background:white;\n color: rgb(180, 179, 179);\n}\n"
},
{
"answer_id": 74508104,
"author": "Ankit",
"author_id": 19757319,
"author_profile": "https://Stackoverflow.com/users/19757319",
"pm_score": 1,
"selected": false,
"text": ".b a:after .b a:hover:after .b:hover {\n background: white;\n color:rgb(180, 179, 179) ;\n}\n.b a:after {\n content: '9.99€';\n}\n.b a:hover:after {\n content: \"new Text\"\n}\n <div id=\"b1\"; class =\"b\">\n <a href=\"test.html\"></a>\n</div>"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20553569/"
] |
74,507,665
|
<p>I am working on a website that will take user data from the form and show it in the table below. I am using indexedDB and everything works locally on my laptop, but when I deploy it to GitHub pages, I get this error:
NotFoundError: Failed to execute 'transaction' on 'IDBDatabase': One of the specified object stores was not found.</p>
<pre><code>let db;
let request = window.indexedDB.open("newDatabase", 1);
</code></pre>
<pre><code>request.onupgradeneeded = function (event) {var db = event.target.result;
var objectStore = db.createObjectStore("client", {autoIncrement: true,});
</code></pre>
<pre><code>objectStore.createIndex("name", "name", { unique: false });
objectStore.createIndex("lastName", "lastName", { unique: false });
objectStore.createIndex("email", "email", { unique: true });
objectStore.createIndex("ID", "ID", { unique: true });
objectStore.createIndex("postal", "postal", { unique: false });
objectStore.createIndex("phoneNumber", "phoneNumber", { unique: true });
</code></pre>
<pre><code>var formElements = document.getElementById("form");
var request = db
.transaction(["client"], 'readwrite')
.objectStore("client")
.add({
name: formElements[0].value,
lastName: formElements[1].value,
email: formElements[2].value,
postal: formElements[3].value,
ID: formElements[4].value,
phoneNumber: formElements[5].value,
});
</code></pre>
<p>I read on the internet that it may happen when the name of an objectStore is different from the name in the transaction, but it is not the case here, they are both the same. I tried changing them to other names, but the issue was still there...</p>
<pre><code>db.createObjectStore("client", {autoIncrement: true,});
.
.
.
var request = db
.transaction(["client"], 'readwrite')
</code></pre>
|
[
{
"answer_id": 74507923,
"author": "WolverinDEV",
"author_id": 7588455,
"author_profile": "https://Stackoverflow.com/users/7588455",
"pm_score": 1,
"selected": false,
"text": "onupgradeneeded open client"
},
{
"answer_id": 74529399,
"author": "PiotrWesoly",
"author_id": 18311214,
"author_profile": "https://Stackoverflow.com/users/18311214",
"pm_score": 1,
"selected": true,
"text": "request.onupgradeneeded objectStore request.onerror request.onupgradeneeded = function (event) {\nvar db = event.target.result;\nconsole.log(\"Object Store creation\");\nvar objectstore = db.createObjectStore(\"client\", {\n autoIncrement: true,\n});\n\nobjectstore.createIndex(\"name\", \"name\", { unique: false });\nobjectstore.createIndex(\"lastName\", \"lastName\", { unique: false });\nobjectstore.createIndex(\"email\", \"email\", { unique: true});\nobjectstore.createIndex(\"ID\", \"ID\", { unique: true }); //HERE WAS THE PROBLEM\nobjectstore.createIndex(\"postal\", \"postal\", { unique: false });\nobjectstore.createIndex(\"phoneNumber\", \"phoneNumber\", { unique: true});\n\nfor (var i in clientData) {\n objectstore.add(clientData[i]); // Here was the error thrown\n}\n};\n\nconst clientData = [\n {\n name: \"Piotr\",\n lastName: \"Wesoly\",\n email: \"PiotrWesoly@gmail.com\",\n ID: 'CCU238293', //The same ID as in the other client\n postal: \"90-234\",\n phoneNumber: \"500500200\"\n },\n {\n name: \"Pawel\",\n lastName: \"Rosiak\",\n email: \"pawelRosiak@gmail.com\",\n ID: 'CCU238293', //The same ID as in the other client\n postal: \"93-234\",\n phoneNumber: \"500400200\"\n },\n ];\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18311214/"
] |
74,507,673
|
<p>My assignment ask us to ask the user to enter a number and print the factorial of it,</p>
<p>it also ask us to not allow the user to chose any negative number or number over 25, when they do, we loop them back to scanner to re renter a number</p>
<p>we were also told to store the number in a long, but when I do, if the user enters a number over 20 and =<25, the answer becomes a negative causing a long overflow.</p>
<p>I tried changing the long to BigInteger, but when I keep getting an error on ever line i use BigInteger instead of long</p>
<pre><code>boolean correctInputn= false;
while(!correctInputn)
{
long number;// declares variables for storing number
long factorial = 1;// declare variable for storing factorial
System.out.println("Enter a number between 1 and 25"); // tells user to enter number
number = scanner.nextLong();
if (number <0)
{System.out.println("Positive numbers only");// if number entered is negative
correctInputn = false; continue;} // if user enters number less than 0 loops back to code start
else if (number > 25)
{ System.out.println("Number to large to print");
correctInputn = false; continue;} // if user enters number over 25 loops back to code start
else {
// if user enter 10, counter starts at 10 and runs to two
for(long mynumber = number; mynumber >= 1; mynumber--) {
factorial = factorial*mynumber; // mynumber would contain different values and that is multiplied by value present in factorial value and stored again in factorial variable
}
System.out.println("The factorial of " + number +" is equal to " + factorial);
break;
}
}
</code></pre>
|
[
{
"answer_id": 74507834,
"author": "rzwitserloot",
"author_id": 768644,
"author_profile": "https://Stackoverflow.com/users/768644",
"pm_score": 3,
"selected": true,
"text": "BigInteger long int double short float char byte boolean + String toString() .multiply .add factorial = factorial.multiply(myNumber) BigInteger BigInteger.valueOf(20)"
},
{
"answer_id": 74512300,
"author": "StaurosChs",
"author_id": 20537635,
"author_profile": "https://Stackoverflow.com/users/20537635",
"pm_score": -1,
"selected": false,
"text": "**I FOUND A SOLUTION AND NOW IT DOESNT OVERFLOW**\n**MAIN**\n import java.util.Scanner;\n public class Main {\n public static void main(String[] args) {\n Factorial factNum;\n Scanner in = new Scanner(System.in);\n boolean flagCheck = false;\n\n System.out.println(\"Please give a number between 0 - 25: \");\n factNum = new Factorial(in.nextLong());\n\n //check if the number is in the limits\n while(!flagCheck) {\n\n if (factNum.getVarForFact() < 0){\n System.out.println(\"Number must be over 0. Please enter again a \n number between 0-25\");\n factNum = new Factorial(in.nextLong());\n } else if (factNum.getVarForFact() > 25){\n System.out.println(\"Number must be under 25. Please enter again a \n number between 0-25\");\n factNum = new Factorial(in.nextLong());\n } else if (factNum.getVarForFact() == 0) {\n factNum.setFinalFact(1);\n System.out.println(\"The factorial of \" + factNum.getVarForFact() + \" \n is \" + factNum.getFinalFact());\n flagCheck = true;\n } else{\n factNum.factorial();\n System.out.println(\"The factorial of \" + factNum.getVarForFact() + \" \n is \" + factNum.getFactorial());\n flagCheck = true;\n }\n }\n\n }\n}\n import java.math.BigInteger;\n\n class Factorial {\n //variable for storing the given number and find the factorial\n private long varForFact;\n private long finalFact;\n\n private BigInteger factorial = BigInteger.ONE;\n //Constructor\n Factorial(long varForFact){\n this.varForFact = varForFact;\n }\n\n //Getter\n public long getVarForFact(){\n return this.varForFact;\n }\n\n public long getFinalFact() {\n return finalFact;\n }\n\n public BigInteger getFactorial() {\n return factorial;\n }\n\n //Setter\n public void setVarForFact(long varForFact){\n this.varForFact = varForFact;\n }\n\n\n public void setFinalFact(long finalFact) {\n this.finalFact = finalFact;\n }\n\n //factorial method, it will return the factorial\n public void factorial(){\n\n for (long i = this.varForFact; i > 0; i--) {\n this.factorial = this.factorial.multiply(BigInteger.valueOf(i));\n }\n }\n}\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20545889/"
] |
74,507,674
|
<p>So when I try to access the update function inside a resource controller, when I hit submit to go there (posts/{id}) I go to the show function of the controller (witch has the same path (posts/{id}).
How can I go the the update path, and access the update function?</p>
<p>So here is the view with its from of the edit function, that will "update" the title:</p>
<pre><code>@extends('layouts.app')
@section('content')
<h1>Edit Post</h1>
<form method="get" action="/posts/{{$post->id}}">
@csrf
<input type="hidden" name="_method" value="PUT">
<input type="text" name="title" placeholder="Enter title" value="{{$post->title}}">
<input type="submit" name="submit">
</form>
@endsection
</code></pre>
<p>And here is the update function of the controller, that will get the values from the upper view and update the post with that id:</p>
<pre><code>public function update(Request $request, $id)
{
//
$post = Post::findOrFail($id);
$post->update($request->all());
return redirect('/posts');
}
</code></pre>
<p>And this is the show function that is going to run after I hit submit, instead of the update:</p>
<pre><code>public function show($id)
{
//
$post = Post::findOrFail($id);
return view('posts.show', compact('post'));
}
</code></pre>
<p>The view of show function, in case you need it:</p>
<pre><code>@extends('layouts.app')
@section('content')
<h1>{{$post->title}}</h1>
@endsection
</code></pre>
<p>When I hit submit it should check first the update function of controller, and render its code, because both update function and show function have the same path posts/{id}.
<a href="https://i.stack.imgur.com/lYflX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lYflX.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74507834,
"author": "rzwitserloot",
"author_id": 768644,
"author_profile": "https://Stackoverflow.com/users/768644",
"pm_score": 3,
"selected": true,
"text": "BigInteger long int double short float char byte boolean + String toString() .multiply .add factorial = factorial.multiply(myNumber) BigInteger BigInteger.valueOf(20)"
},
{
"answer_id": 74512300,
"author": "StaurosChs",
"author_id": 20537635,
"author_profile": "https://Stackoverflow.com/users/20537635",
"pm_score": -1,
"selected": false,
"text": "**I FOUND A SOLUTION AND NOW IT DOESNT OVERFLOW**\n**MAIN**\n import java.util.Scanner;\n public class Main {\n public static void main(String[] args) {\n Factorial factNum;\n Scanner in = new Scanner(System.in);\n boolean flagCheck = false;\n\n System.out.println(\"Please give a number between 0 - 25: \");\n factNum = new Factorial(in.nextLong());\n\n //check if the number is in the limits\n while(!flagCheck) {\n\n if (factNum.getVarForFact() < 0){\n System.out.println(\"Number must be over 0. Please enter again a \n number between 0-25\");\n factNum = new Factorial(in.nextLong());\n } else if (factNum.getVarForFact() > 25){\n System.out.println(\"Number must be under 25. Please enter again a \n number between 0-25\");\n factNum = new Factorial(in.nextLong());\n } else if (factNum.getVarForFact() == 0) {\n factNum.setFinalFact(1);\n System.out.println(\"The factorial of \" + factNum.getVarForFact() + \" \n is \" + factNum.getFinalFact());\n flagCheck = true;\n } else{\n factNum.factorial();\n System.out.println(\"The factorial of \" + factNum.getVarForFact() + \" \n is \" + factNum.getFactorial());\n flagCheck = true;\n }\n }\n\n }\n}\n import java.math.BigInteger;\n\n class Factorial {\n //variable for storing the given number and find the factorial\n private long varForFact;\n private long finalFact;\n\n private BigInteger factorial = BigInteger.ONE;\n //Constructor\n Factorial(long varForFact){\n this.varForFact = varForFact;\n }\n\n //Getter\n public long getVarForFact(){\n return this.varForFact;\n }\n\n public long getFinalFact() {\n return finalFact;\n }\n\n public BigInteger getFactorial() {\n return factorial;\n }\n\n //Setter\n public void setVarForFact(long varForFact){\n this.varForFact = varForFact;\n }\n\n\n public void setFinalFact(long finalFact) {\n this.finalFact = finalFact;\n }\n\n //factorial method, it will return the factorial\n public void factorial(){\n\n for (long i = this.varForFact; i > 0; i--) {\n this.factorial = this.factorial.multiply(BigInteger.valueOf(i));\n }\n }\n}\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20337580/"
] |
74,507,680
|
<p><a href="https://stackoverflow.com/a/8978435/1335492">https://stackoverflow.com/a/8978435/1335492</a></p>
<p>...shows how to call a python script from LibreOffice BASIC: (<a href="https://stackoverflow.com/questions/7591656/how-can-i-call-a-python-macro-in-a-cell-formula-in-openoffice-org-calc/8978435#8978435">How can I call a Python macro in a cell formula in OpenOffice.Org Calc?</a>
)</p>
<pre><code>Function invokeScriptFunc(..., args As Array, outIdxs As Array, outArgs As Array)
...
invokeScriptFunc = oScript.invoke(args, outIdxs, outArgs)
end Function
</code></pre>
<p>But that doesn't work for me. I get "BASIC runtime error. Argument is not optional" for outArgs. On the other hand, "oScript.invoke(args, Array(), Array())" is not an error.</p>
<p>The example has not been wrong for 10 years, it's unlikely to be wrong today. But I've not got an example of it working with a python script that returns a list: perhaps that is my problem.</p>
<p>The script I am trying to use is:</p>
<pre><code>def MyFunc(a,b):
return [a,b]
</code></pre>
<p>I don't get the error when I try</p>
<pre><code>Function invokeScriptFunc(..., args As Array, outIdxs As Array)
...
dim outArgs as array
invokeScriptFunc = oScript.invoke(args, outIdxs, outArgs)
end Function
</code></pre>
<p>or</p>
<pre><code> invokeScriptFunc = oScript.invoke(args, outIdxs, array())
</code></pre>
<p>but either way, I'm no closer to seeing the return value I want. FWIW, when I "dim outArgs as array", .invoke returns an object with lbound=0 and ubound=-1. outArgs(0) is not valid.</p>
<p>I'm not trying to parse the output: that comes later. I'm just trying to get it to run without error.</p>
|
[
{
"answer_id": 74507834,
"author": "rzwitserloot",
"author_id": 768644,
"author_profile": "https://Stackoverflow.com/users/768644",
"pm_score": 3,
"selected": true,
"text": "BigInteger long int double short float char byte boolean + String toString() .multiply .add factorial = factorial.multiply(myNumber) BigInteger BigInteger.valueOf(20)"
},
{
"answer_id": 74512300,
"author": "StaurosChs",
"author_id": 20537635,
"author_profile": "https://Stackoverflow.com/users/20537635",
"pm_score": -1,
"selected": false,
"text": "**I FOUND A SOLUTION AND NOW IT DOESNT OVERFLOW**\n**MAIN**\n import java.util.Scanner;\n public class Main {\n public static void main(String[] args) {\n Factorial factNum;\n Scanner in = new Scanner(System.in);\n boolean flagCheck = false;\n\n System.out.println(\"Please give a number between 0 - 25: \");\n factNum = new Factorial(in.nextLong());\n\n //check if the number is in the limits\n while(!flagCheck) {\n\n if (factNum.getVarForFact() < 0){\n System.out.println(\"Number must be over 0. Please enter again a \n number between 0-25\");\n factNum = new Factorial(in.nextLong());\n } else if (factNum.getVarForFact() > 25){\n System.out.println(\"Number must be under 25. Please enter again a \n number between 0-25\");\n factNum = new Factorial(in.nextLong());\n } else if (factNum.getVarForFact() == 0) {\n factNum.setFinalFact(1);\n System.out.println(\"The factorial of \" + factNum.getVarForFact() + \" \n is \" + factNum.getFinalFact());\n flagCheck = true;\n } else{\n factNum.factorial();\n System.out.println(\"The factorial of \" + factNum.getVarForFact() + \" \n is \" + factNum.getFactorial());\n flagCheck = true;\n }\n }\n\n }\n}\n import java.math.BigInteger;\n\n class Factorial {\n //variable for storing the given number and find the factorial\n private long varForFact;\n private long finalFact;\n\n private BigInteger factorial = BigInteger.ONE;\n //Constructor\n Factorial(long varForFact){\n this.varForFact = varForFact;\n }\n\n //Getter\n public long getVarForFact(){\n return this.varForFact;\n }\n\n public long getFinalFact() {\n return finalFact;\n }\n\n public BigInteger getFactorial() {\n return factorial;\n }\n\n //Setter\n public void setVarForFact(long varForFact){\n this.varForFact = varForFact;\n }\n\n\n public void setFinalFact(long finalFact) {\n this.finalFact = finalFact;\n }\n\n //factorial method, it will return the factorial\n public void factorial(){\n\n for (long i = this.varForFact; i > 0; i--) {\n this.factorial = this.factorial.multiply(BigInteger.valueOf(i));\n }\n }\n}\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1335492/"
] |
74,507,688
|
<p>I recentyl started to learn javascrtipt, react, and NodeJS and I encountered a problem that the internet can't seem to fix. My nodeJs server publishes data on my localhost:7000 in the format (this works):</p>
<pre><code>{
"carbs":18,
"fats":0,
"kcal":184,
"productName":"Jenever bessen-",
"protein":0,
"sugars":18
},
etc.
</code></pre>
<p>I then fetch the data in my hooks folder in request.js:</p>
<pre><code> const API_URL = 'http://localhost:7000';
// Load planets and return as JSON.
async function httpGetNutrition() {
const response = await fetch(`${API_URL}/nutrition`); //works
console.log('fetched data')
return await response.json(); //works
}
export {
httpGetNutrition,
};
</code></pre>
<p>Here After, I use the fetched data and try to add it in 'getNutrition'. To code I added currently maps the objects of 'fetchedNutrition' and adds them to the useState 'nutrition'. The 'item' object prints correctly, however, when I 'setNutrition' and console.log(nutrition), an empty array is passed.</p>
<pre><code> import { useCallback, useEffect, useState } from "react";
import { httpGetNutrition } from "./requests";
function UseNutrition()
{
const [nutrition, setNutrition] = useState([])
const [loading, setLoading] = useState(true)
const getNutrition = useCallback(async () => {
setLoading(true)
try
{
const fetchedNutrition = await httpGetNutrition(); //works
fetchedNutrition.map((item) => {
console.log(item) //prints correctly
setNutrition([...nutrition, item]); //adds items to nutrition array
console.log(nutrition) //returns empty array
})
if (nutrition.length > 0) //nutrition.length returns 0 -> empty array
{
console.log('set nutrition succesfully')
console.log(nutrition.length)
}
else
{
console.log('data is of length 0')
}
}
catch (err)
{
setLoading(false)
console.log(`error: ${err}`)
}
},[]);
if (loading)
{
<div className="loading">
<h1>loading...</h1>
</div>
}
useEffect(() => {
getNutrition()
}, [getNutrition]);
return nutrition
}
export default UseNutrition;
</code></pre>
<p>Other ways I tried:</p>
<ul>
<li>setNutrition([...nutrition, ...item])</li>
<li>remove the .map and add 'fetchedNutrition' to 'setNutrition': setNutrition(fetchedNutrition). However, this yields the following error for both cases:</li>
</ul>
<pre><code>react-dom.development.js:14887 Uncaught Error: Objects are not valid as a React child (found: object with keys {carbs, fats, kcal, productName, protein, sugars}). If you meant to render a collection of children, use an array instead.
at throwOnInvalidObjectType
</code></pre>
<p>I have looked at similar posts only, which suggested both methods, but unfortunately non have worked for me yet. Not sure what is the root of the issue here, maybe anyone could suggest something?</p>
<p>Thanks in advance</p>
<p>I tried decomposing the object with ... notation, {} notation, mapping, defining the children in the useState method and adding the values in a loop.</p>
|
[
{
"answer_id": 74507781,
"author": "stasdes",
"author_id": 2091359,
"author_profile": "https://Stackoverflow.com/users/2091359",
"pm_score": 1,
"selected": false,
"text": " import { useCallback, useEffect, useState } from \"react\";\n import { httpGetNutrition } from \"./requests\";\n\n function UseNutrition()\n { \n const [nutritions, setNutritions] = useState([])\n const [loading, setLoading] = useState(true)\n \n const getNutrition = useCallback(async () => {\n setLoading(true)\n try \n {\n const fetchedNutrition = await httpGetNutrition(); //works\n setNutritions(fetchedNutrition)\n }\n catch (err)\n {\n console.log(`error: ${err}`)\n } finally {\n setLoading(false)\n }\n },[]);\n\n if (loading)\n {\n <div className=\"loading\">\n <h1>loading...</h1>\n </div>\n }\n\n useEffect(() => {\n getNutrition()\n }, [getNutrition]);\n\n return nutritions.map((nutrition) => <div key={nutrition.productName}>{nitrition.productName}</div>)\n }\n\n export default UseNutrition;\n"
},
{
"answer_id": 74507857,
"author": "tezarsurya",
"author_id": 20538454,
"author_profile": "https://Stackoverflow.com/users/20538454",
"pm_score": 0,
"selected": false,
"text": "setNutrition([...fetchedNutrition]) // without fetchedNutrition.map()\n useEffect(() => {\n console.log(nutrition)\n if (nutrition.length > 0) {\n console.log('set nutrition succesfully')\n console.log(nutrition.length)\n } else {\n console.log('data is of length 0')\n }\n}, [nutrition])\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20088080/"
] |
74,507,690
|
<p>I am trying to create a ListView to display a bunch of custom cells, and I need it to update when I modify its content. I have bound its ItemsSource to an ObservableCollection, and I have a method that updates this collection whenever I need. This method is called when I add an element to a persistent collection stored with the Settings plugin, or when the page appears because I can also modify that persistent collection from another page. However, the ListView won't update unless I switch to another tab of my app before coming back.</p>
<p>Here's my code:</p>
<p>ViewModel:</p>
<pre><code> public ObservableCollection<ViewCell> Cells { get; set; }
public PlugManagerViewModel()
{
Title = "Mes prises";
Cells = new ObservableCollection<ViewCell>();
}
public void RefreshPlugList()
{
Cells.Clear();
foreach ((string name, string desc, _) in Settings.PlugListContent)
{
CustomCell cell = new CustomCell
{
Title = name,
Detail = desc
};
Cells.Add(cell);
}
}
</code></pre>
<p>XAML:</p>
<pre><code><ListView x:Name="plugList" x:FieldModifier="public" VerticalScrollBarVisibility="Default" SelectionMode="None" RowHeight="90" VerticalOptions="FillAndExpand" ItemSelected="OpenPlugDetail" ItemsSource="{Binding Cells}">
<ListView.ItemTemplate>
<DataTemplate>
<models:CustomCell Title="{Binding Title}" Detail="{Binding Detail}"></models:CustomCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</code></pre>
<p>XAML.cs:</p>
<pre><code> PlugManagerViewModel _viewModel;
public PlugManagerPage()
{
InitializeComponent();
_viewModel = (PlugManagerViewModel)this.BindingContext;
}
protected override void OnAppearing()
{
base.OnAppearing();
_viewModel.RefreshPlugList();
}
public async void AddPlug(object sender, EventArgs e)
{
//Code to modify Settings.PlugListContent
_viewModel.RefreshPlugList();
}
public async void OpenPlugDetail(object sender, SelectedItemChangedEventArgs e)
{
//Code to change page and reset selected item
}
</code></pre>
<p>I have already looked up a bunch of other threads and I can't find a working solution. Is my binding broken or is it something else ?</p>
|
[
{
"answer_id": 74507781,
"author": "stasdes",
"author_id": 2091359,
"author_profile": "https://Stackoverflow.com/users/2091359",
"pm_score": 1,
"selected": false,
"text": " import { useCallback, useEffect, useState } from \"react\";\n import { httpGetNutrition } from \"./requests\";\n\n function UseNutrition()\n { \n const [nutritions, setNutritions] = useState([])\n const [loading, setLoading] = useState(true)\n \n const getNutrition = useCallback(async () => {\n setLoading(true)\n try \n {\n const fetchedNutrition = await httpGetNutrition(); //works\n setNutritions(fetchedNutrition)\n }\n catch (err)\n {\n console.log(`error: ${err}`)\n } finally {\n setLoading(false)\n }\n },[]);\n\n if (loading)\n {\n <div className=\"loading\">\n <h1>loading...</h1>\n </div>\n }\n\n useEffect(() => {\n getNutrition()\n }, [getNutrition]);\n\n return nutritions.map((nutrition) => <div key={nutrition.productName}>{nitrition.productName}</div>)\n }\n\n export default UseNutrition;\n"
},
{
"answer_id": 74507857,
"author": "tezarsurya",
"author_id": 20538454,
"author_profile": "https://Stackoverflow.com/users/20538454",
"pm_score": 0,
"selected": false,
"text": "setNutrition([...fetchedNutrition]) // without fetchedNutrition.map()\n useEffect(() => {\n console.log(nutrition)\n if (nutrition.length > 0) {\n console.log('set nutrition succesfully')\n console.log(nutrition.length)\n } else {\n console.log('data is of length 0')\n }\n}, [nutrition])\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19668911/"
] |
74,507,763
|
<p>I bought the book <code>Programming Rust: Fast, Safe Systems Development 2nd Edition</code> a couple weeks ago to learn <code>Rust</code>. At the moment, I am struggling with the topic <code>&T</code> and <code>mut &T</code>.</p>
<p>In the book, the author has mentioned the following regarding to references:</p>
<blockquote>
<p>You can’t borrow a mutable reference to a read-only value.</p>
</blockquote>
<p>What does it mean? An example would be nice.</p>
|
[
{
"answer_id": 74507807,
"author": "cafce25",
"author_id": 442760,
"author_profile": "https://Stackoverflow.com/users/442760",
"pm_score": 3,
"selected": true,
"text": "let a = 99;\nlet b = &mut a;\n"
},
{
"answer_id": 74507924,
"author": "at54321",
"author_id": 15602349,
"author_profile": "https://Stackoverflow.com/users/15602349",
"pm_score": 0,
"selected": false,
"text": "let x = 42;\nlet mut y = 42;\nlet _a = &x; // This is fine\nlet _b = &mut x; // This is NOT \nlet _c = &y; // This is fine (even though y is mut)\nlet _d = &mut y; // This is fine\n let mut y = 42;\nlet r = &y; // This is fine\nlet m = &mut r; // This is NOT (cannot borrow `r` as mutable, as it is not declared as mutable)\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1743843/"
] |
74,507,765
|
<p>I've two python class 'tuples' and and i want to compare contents on both of them and get only which is only in 'deactivated' tuple for eg.,</p>
<pre><code>deactivated = ((34, 'abcd'), (250, 'def'), (350, 'xyz'))
schedules = ((34, 'abcd'), (250, 'def'))
to_deactivate = ()
</code></pre>
<p>in here, i want to push <code>(350, 'xyz')</code> which is not in schedules to another variable <code>to_deactivate</code>.</p>
<p>I've looked into some of the solutions online but most of them are just comparing whether the tuples are same or not. Please help me out on this.</p>
|
[
{
"answer_id": 74507799,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 1,
"selected": true,
"text": "deactivated = ((34, \"abcd\"), (250, \"def\"), (350, \"xyz\"))\nschedules = ((34, \"abcd\"), (250, \"def\"))\n\nto_deactivate = tuple(tpl for tpl in deactivated if tpl not in schedules)\nprint(to_deactivate)\n ((350, 'xyz'),)\n"
},
{
"answer_id": 74507830,
"author": "Karthik",
"author_id": 20224646,
"author_profile": "https://Stackoverflow.com/users/20224646",
"pm_score": 0,
"selected": false,
"text": "deactivated = ((34, 'abcd'), (250, 'def'), (350, 'xyz'))\nschedules = ((34, 'abcd'), (250, 'def'))\nto_deactivate = ()\nfor i in range(len(deactivated)):\n if deactivated[i] not in schedules:\n to_deactivate += deactivated[i]\nprint(to_deactivate)\n"
},
{
"answer_id": 74508164,
"author": "chrslg",
"author_id": 20037042,
"author_profile": "https://Stackoverflow.com/users/20037042",
"pm_score": 2,
"selected": false,
"text": "sets in in to_deactivate = deactivated - schedules\n to_deactivate=tuple(set(deactivated)-set(schedules))\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17994187/"
] |
74,507,771
|
<p>I cannot manage to get the following code to work. I am trying to dynamically generate the following SVG in JS:</p>
<pre><code><svg xmlns="http://www.w3.org/2000/svg" height="48" width="48"><path d="m12.45 37.65-2.1-2.1L21.9 24 10.35 12.45l2.1-2.1L24 21.9l11.55-11.55 2.1 2.1L26.1 24l11.55 11.55-2.1 2.1L24 26.1Z"/></svg>
</code></pre>
<p>I have tried:</p>
<pre class="lang-js prettyprint-override"><code>let closeButton = document.createElement("svg");
closeButton.setAttribute("height", "48");
closeButton.setAttribute("width", "48");
let closeButtonPath = document.createElementNS('http://www.w3.org/2000/svg',"path");
closeButtonPath.setAttributeNS(null, "d", "m12.45 37.65-2.1-2.1L21.9 24 10.35 12.45l2.1-2.1L24 21.9l11.55-11.55 2.1 2.1L26.1 24l11.55 11.55-2.1 2.1L24 26.1Z");
closeButton.appendChild(closeButtonPath);
this.#form.appendChild(closeButton);
</code></pre>
|
[
{
"answer_id": 74508720,
"author": "pier farrugia",
"author_id": 19996700,
"author_profile": "https://Stackoverflow.com/users/19996700",
"pm_score": 0,
"selected": false,
"text": "let svg_str = '<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48px\" height=\"48px\"><path d=\"m12.45 37.65-2.1-2.1L21.9 24 10.35 12.45l2.1-2.1L24 21.9l11.55-11.55 2.1 2.1L26.1 24l11.55 11.55-2.1 2.1L24 26.1Z\"/></svg>';\ndocument.querySelector('#button1').innerHTML = svg_str;\n\n\n// if height and widht has to be changed otherwise you put them directly in svg_str\nconst h = 48 + 'px';\nconst w = 48 + 'px';\n// if path is a variable otherwise you put directly in svg_str\nconst path_d = \"m12.45 37.65-2.1-2.1L21.9 24 10.35 12.45l2.1-2.1L24 21.9l11.55-11.55 2.1 2.1L26.1 24l11.55 11.55-2.1 2.1L24 26.1Z\";\n\nsvg_str = '<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"' + w + '\" height=\"' + h + '\"><path d=\"' + path_d + '\"/></svg>';\ndocument.querySelector('#button2').innerHTML = svg_str; <div id=\"button1\">\n\n</div>\n<div id=\"button2\">\n\n</div>"
},
{
"answer_id": 74509794,
"author": "Danny '365CSI' Engelman",
"author_id": 2520800,
"author_profile": "https://Stackoverflow.com/users/2520800",
"pm_score": 0,
"selected": false,
"text": "<style>\n svg-icon { background:pink }\n</style>\n\n<svg-icon></svg-icon>\n<svg-icon width=\"80\"></svg-icon>\n<svg-icon width=\"180\"></svg-icon>\n\n<script>\ncustomElements.define(\"svg-icon\", class extends HTMLElement{\n connectedCallback(){\n this.style.display = \"inline-block\";\n let width = (this.getAttribute(\"width\") || 48) + \"px\";\n this.innerHTML =`<svg width=\"${width}\" height=\"${width}\" viewBox=\"0 0 48 44\">`\n + `<path d=\"m12.4 37.6-2.1-2.1 11.6-11.5-11.6-11.6 2.1-2.1 11.6 11.6 11.6-11.6 2.1 2.1-11.6 11.6 11.6 11.6-2.1 2.1-11.6-11.6z\"/>`\n + `</svg>`;\n }\n});\n</script>"
},
{
"answer_id": 74510384,
"author": "herrstrietzel",
"author_id": 15015675,
"author_profile": "https://Stackoverflow.com/users/15015675",
"pm_score": 2,
"selected": true,
"text": "svg createElementNS() createElement() this.#form let form = document.getElementById('form');\nform.appendChild(closeButton);\n const ns =\"http://www.w3.org/2000/svg\";\n\nlet closeIconSvg = document.createElementNS(ns, \"svg\");\ncloseIconSvg.setAttribute(\"viewBox\", \"0 0 48 48\");\ncloseIconSvg.classList.add('closeIconSvg');\n\nlet closeIconPath = document.createElementNS(ns,\"path\"); \ncloseIconPath.setAttribute(\"d\", \"m12.45 37.65 -2.1-2.1L21.9 24 10.35 12.45l2.1-2.1L24 21.9l11.55-11.55 2.1 2.1L26.1 24l11.55 11.55-2.1 2.1L24 26.1Z\");\ncloseIconSvg.appendChild(closeIconPath);\n\n//let form = document.getElementById('form');\nlet closeButton = document.getElementById('btnClose');\ncloseButton.appendChild(closeIconSvg); *{\n box-sizing:border-box\n}\n\n.form{\n font-size:48px;\n display:flex;\n align-items:center;\n}\n\ninput, \n.btnClose{\n margin:0;\n padding:0.15em 0.3em 0.3em 0.3em;\n font-size:1em;\n border:1px solid #ccc;\n background:#fff;\n}\n\n.closeIconSvg{\n width:auto;\n height:1em;\n vertical-align: -0.25em;\n} <form id=\"form\" class=\"form\" action=\"\">\n <input type=\"text\" placeholder=\"name\">\n <button id=\"btnClose\" class=\"btnClose\" type=\"button\"></button>\n</form>"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6017833/"
] |
74,507,779
|
<p>I have a json string date value as below:</p>
<pre><code>{[
{
"id": "2044020453",
"startDate": "2022-11-19T04:14:11+07:00",
"endDate": "2022-11-19T04:14:11+07:00",
}
]}
string endDate = JsonConvert.SerializeObject(jo["endDate"], Formatting.None, new
JsonSerializerSettings
{
DateTimeZoneHandling = DateTimeZoneHandling.Utc
});
endDate value is "\"2022-11-18T21:14:11Z\""
DateTime endDateTime = DateTime.ParseExact(endDate, "yyyy-MM-
ddTHH:mm:ssZ",System.Globalization.CultureInfo.InvariantCulture);
</code></pre>
<p>Always fails to convert to date because there is a backslash in-front and end of the "endDate"</p>
<p>how to clean the backslash?</p>
<p>I have tried:</p>
<pre><code>endDate.Replace("\\", "") --> no luck
Regex.Unescape(endDate) also no luck
</code></pre>
<p>anybody can help?</p>
|
[
{
"answer_id": 74507792,
"author": "Tarik",
"author_id": 990750,
"author_profile": "https://Stackoverflow.com/users/990750",
"pm_score": -1,
"selected": true,
"text": "endDate.Replace(\"\\\"\", \"\")\n"
},
{
"answer_id": 74508000,
"author": "Tim Schmelter",
"author_id": 284240,
"author_profile": "https://Stackoverflow.com/users/284240",
"pm_score": 1,
"selected": false,
"text": "\"2022-11-18T21:14:11Z\"\n endDate = endDate.Trim('\"');\n DateTime endDateTime = DateTime.Parse(endDate, CultureInfo.InvariantCulture);\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16844607/"
] |
74,507,804
|
<pre><code>x = int(input())
y = int(input())
z = int(input())
print(x, y, z)
</code></pre>
<p>When I input y an error shows up:
<strong>ValueError: invalid literal for int() with base 10: ''</strong></p>
<p>I didn't know what to try so I just messed around and when I did the following it somehow worked</p>
<pre><code>x = int(input())
print(x)
y = int(input())
print(y)
z = int(input())
print(z)
print(x, y, z)
</code></pre>
<p>so my question is why it doesn't work without prints</p>
<p>So apparently PYCharm is the problem. When I input the same numbers in VSC or any online python compiler I get what I input. I guess I won't be using PYCharm anymore.</p>
|
[
{
"answer_id": 74507837,
"author": "Paz Bazak",
"author_id": 16597971,
"author_profile": "https://Stackoverflow.com/users/16597971",
"pm_score": 0,
"selected": false,
"text": "\"asd\"\n\"!\"\n\" \"\n\"12lorem\"\n"
},
{
"answer_id": 74507841,
"author": "Cartroo",
"author_id": 1955509,
"author_profile": "https://Stackoverflow.com/users/1955509",
"pm_score": 1,
"selected": false,
"text": "input() int() >>> x = int(input())\n123\n>>> type(x)\n<class 'int'>\n>>> x\n123\n int() >>> int(\"hello\")\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nValueError: invalid literal for int() with base 10: 'hello'\n input() int()"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20503795/"
] |
74,507,864
|
<p>I have files that contain both strings and floats. I am interested in finding the floats after a specific string. Any help in writing such a function that reads the file look for that specific string and returns the float after it will be much appreciated.</p>
<p>Thanks</p>
<p>An example of a file is</p>
<pre><code>lines = """aaaaaaaaaaaaaaa bbbbbbbbbbbbbbb cccccccccc
qq vvv rrr ssssa 22.6
zzzzx bbbb 12.0
xxxxxxxxxx -1.099
zzzz bbb nnn 33.5"""
</code></pre>
<pre><code>import re
lines = """aaaaaaaaaaaaaaa bbbbbbbbbbbbbbb cccccccccc
qq vvv rrr ssssa 22.6
zzzzx bbbb 12.0
xxxxxxxxxx -1.099
zzzz bbb nnn 33.5"""
str_to_search = 'xxxxxxxxxx'
num = re.findall(r'^' + str_to_search + r' (\d+\.\d+)', lines, flags=re.M)
print(num)
</code></pre>
<p>This works if there are no negative signs. In other words, if the number after the string 'xxxxxxxxxx' is 1.099 rather than '-1.099', it works fine. The question I have is how to generalize so it accounts for negative numbers as well given that it can be positive number (no sign in this case) or a negative number (with a negative sign in this case)</p>
|
[
{
"answer_id": 74507901,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 2,
"selected": false,
"text": "(-?\\d+\\.?\\d*)\n import re\n\nlines = \"\"\"aaaaaaaaaaaaaaa bbbbbbbbbbbbbbb cccccccccc\nqq vvv rrr ssssa 22.6\nzzzzx bbbb 12.0\nxxxxxxxxxx -1.099\nzzzz bbb nnn 33.5\nxxxxxxxxxx 1.099\"\"\"\n\nstr_to_search = \"xxxxxxxxxx\"\nnum = re.findall(fr\"(?m)^{str_to_search}\\s+(-?\\d+\\.?\\d*)\", lines)\nprint(num)\n ['-1.099', '1.099']\n"
},
{
"answer_id": 74507952,
"author": "Abinashbunty",
"author_id": 13858770,
"author_profile": "https://Stackoverflow.com/users/13858770",
"pm_score": 3,
"selected": true,
"text": "num = re.findall(r'^' + str_to_search + r' (-?\\d+\\.?\\d*)', lines, flags=re.M)\n"
},
{
"answer_id": 74507955,
"author": "MarshiDev",
"author_id": 20553546,
"author_profile": "https://Stackoverflow.com/users/20553546",
"pm_score": 1,
"selected": false,
"text": "lines = \"\"\"aaaaaaaaaaaaaaa bbbbbbbbbbbbbbb cccccccccc\nqq vvv rrr ssssa 22.6\nzzzzx bbbb 12.0\nxxxxxxxxxx -1.099\nzzzz bbb nnn 33.5\"\"\"\n\nlines = lines.replace(\"\\n\", \" \").split(\" \") # replace the newlines with spaces to split them as well\n\ntry:\n float_index = lines.index(\"xxxxxxxxxx\") + 1 # Get the element after the string you are trying to find\n\n num = float(lines[float_index])\nexcept Exception as e:\n print(e)\n\nprint(num)\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19545800/"
] |
74,507,872
|
<p>Here's the code of a solid diamond and I want to remove the middle and leave the edges.</p>
<p>From this,</p>
<p><a href="https://i.stack.imgur.com/Eo6XY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Eo6XY.png" alt="enter image description here" /></a></p>
<p>to this,</p>
<p><a href="https://i.stack.imgur.com/QrOe8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QrOe8.png" alt="enter image description here" /></a></p>
<pre><code>public void DiamondOne()
{
int i, j, count = 1, number;
Console.Write("Enter number of rows:");
number = int.Parse(Console.ReadLine());
count = number - 1;
for (j = 1; j <= number; j++)
{
for (i = 1; i <= count; i++)
Console.Write(" ");
count--;
for (i = 1; i <= 2 * j - 1; i++)
Console.Write("*");
Console.WriteLine();
}
count = 1;
for (j = 1; j <= number - 1; j++)
{
for (i = 1; i <= count; i++)
Console.Write(" ");
count++;
for (i = 1; i <= 2 * (number - j) - 1; i++)
Console.Write("*");
Console.WriteLine();
}
Console.ReadLine();
}
</code></pre>
|
[
{
"answer_id": 74508009,
"author": "Gabriel Stancu",
"author_id": 8187400,
"author_profile": "https://Stackoverflow.com/users/8187400",
"pm_score": 2,
"selected": true,
"text": " public void Diamond()\n {\n Console.WriteLine(\"Enter number of rows:\");\n bool isNumber = int.TryParse(Console.ReadLine(), out int rowsNr);\n\n if (!isNumber)\n {\n Console.WriteLine(\"Not a number!\");\n return;\n }\n\n // print the upper half\n for (int rowIndex = 0; rowIndex < rowsNr - 1; rowIndex++)\n {\n for (int colIndex = 0; colIndex <= 2 * rowsNr; colIndex++)\n {\n if (colIndex == Math.Abs(rowsNr - rowIndex) || colIndex == Math.Abs(rowsNr + rowIndex))\n {\n Console.Write(\"*\");\n }\n else\n {\n Console.Write(\" \");\n }\n }\n Console.WriteLine();\n }\n\n // print the lower half\n for (int rowIndex = 1; rowIndex <= rowsNr; rowIndex++)\n {\n for (int colIndex = 0; colIndex <= 2 * rowsNr; colIndex++)\n {\n if (colIndex == rowIndex || colIndex == 2 * rowsNr - rowIndex)\n {\n Console.Write(\"*\");\n }\n else\n {\n Console.Write(\" \");\n }\n }\n\n Console.WriteLine();\n }\n }\n"
},
{
"answer_id": 74508076,
"author": "Martin Brown",
"author_id": 20553,
"author_profile": "https://Stackoverflow.com/users/20553",
"pm_score": 0,
"selected": false,
"text": "// Get the number of rows\nint rows;\ndo\n{\n Console.WriteLine(\"Enter number of rows:\");\n} while (!int.TryParse(Console.ReadLine(), out rows));\n\n// Print diamond\nDiamondOne(rows, Console.Out);\n\n// Wait for key press\nConsole.WriteLine(\"Press any key to exit\");\nConsole.ReadKey(true);\n\nstatic void DiamondOne(int rows, TextWriter output)\n{\n for (int currentRow = 0; currentRow < rows; currentRow++)\n {\n OutputRow(rows, output, currentRow);\n }\n\n for (int currentRow = rows - 2; currentRow >= 0; currentRow--)\n {\n OutputRow(rows, output, currentRow);\n }\n}\n\nstatic void OutputRow(int rows, TextWriter output, int currentRow)\n{\n int indentation = rows - currentRow - 1;\n int diamondCentre = Math.Max((currentRow * 2) - 1, 0);\n\n output.Write(new string(' ', indentation));\n output.Write('*');\n output.Write(new string(' ', diamondCentre));\n if (currentRow != 0) output.Write('*');\n output.WriteLine();\n}\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15142082/"
] |
74,507,891
|
<p>I understand that SmtpClient doesn't support many modern protocols so the recommendation is use MailKit, but with SmtpClient using System.Net.Mail the password was not required. With Mailkit I must Authanticate with password in my code.</p>
<pre><code>using (var client = new SmtpClient ()) {
client.Connect ("smtp.friends.com", 587, false);
// Note: only needed if the SMTP server requires authentication
client.Authenticate ("joey", "password");
client.Send (message);
client.Disconnect (true);
}
</code></pre>
<p>Could I don't use the password visible in my code, please ? How ?</p>
<p>Thank you</p>
|
[
{
"answer_id": 74508009,
"author": "Gabriel Stancu",
"author_id": 8187400,
"author_profile": "https://Stackoverflow.com/users/8187400",
"pm_score": 2,
"selected": true,
"text": " public void Diamond()\n {\n Console.WriteLine(\"Enter number of rows:\");\n bool isNumber = int.TryParse(Console.ReadLine(), out int rowsNr);\n\n if (!isNumber)\n {\n Console.WriteLine(\"Not a number!\");\n return;\n }\n\n // print the upper half\n for (int rowIndex = 0; rowIndex < rowsNr - 1; rowIndex++)\n {\n for (int colIndex = 0; colIndex <= 2 * rowsNr; colIndex++)\n {\n if (colIndex == Math.Abs(rowsNr - rowIndex) || colIndex == Math.Abs(rowsNr + rowIndex))\n {\n Console.Write(\"*\");\n }\n else\n {\n Console.Write(\" \");\n }\n }\n Console.WriteLine();\n }\n\n // print the lower half\n for (int rowIndex = 1; rowIndex <= rowsNr; rowIndex++)\n {\n for (int colIndex = 0; colIndex <= 2 * rowsNr; colIndex++)\n {\n if (colIndex == rowIndex || colIndex == 2 * rowsNr - rowIndex)\n {\n Console.Write(\"*\");\n }\n else\n {\n Console.Write(\" \");\n }\n }\n\n Console.WriteLine();\n }\n }\n"
},
{
"answer_id": 74508076,
"author": "Martin Brown",
"author_id": 20553,
"author_profile": "https://Stackoverflow.com/users/20553",
"pm_score": 0,
"selected": false,
"text": "// Get the number of rows\nint rows;\ndo\n{\n Console.WriteLine(\"Enter number of rows:\");\n} while (!int.TryParse(Console.ReadLine(), out rows));\n\n// Print diamond\nDiamondOne(rows, Console.Out);\n\n// Wait for key press\nConsole.WriteLine(\"Press any key to exit\");\nConsole.ReadKey(true);\n\nstatic void DiamondOne(int rows, TextWriter output)\n{\n for (int currentRow = 0; currentRow < rows; currentRow++)\n {\n OutputRow(rows, output, currentRow);\n }\n\n for (int currentRow = rows - 2; currentRow >= 0; currentRow--)\n {\n OutputRow(rows, output, currentRow);\n }\n}\n\nstatic void OutputRow(int rows, TextWriter output, int currentRow)\n{\n int indentation = rows - currentRow - 1;\n int diamondCentre = Math.Max((currentRow * 2) - 1, 0);\n\n output.Write(new string(' ', indentation));\n output.Write('*');\n output.Write(new string(' ', diamondCentre));\n if (currentRow != 0) output.Write('*');\n output.WriteLine();\n}\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19944354/"
] |
74,507,898
|
<p>I want to remove everthing between <strong>.com/</strong> to <strong>?utm</strong></p>
<p>How can I do that?
I use Notepad++ and Kate.</p>
<pre><code>https://www.forexample.com/cat.belt?utm2900&eav=AfbHJya2K7Mbg2mPWatN
https://www.forexample.com/cat.food?utm89748&eav=AfbHJya2K7Mbg2mPWatN
https://www.forexample.com/dog.necklace?utm25875&eav=AfbHJya2K7Mbg2mPWatN
https://www.forexample.com/dog.belt?utm25285&eav=AfbHJya2K7Mbg2mPWatN
https://www.forexample.com/dog.food?utm785844&eav=AfbHJya2K7Mbg2mPWatN
</code></pre>
<p>I tried to Google the solution, but nothing really works.</p>
|
[
{
"answer_id": 74508077,
"author": "akash",
"author_id": 9839769,
"author_profile": "https://Stackoverflow.com/users/9839769",
"pm_score": 1,
"selected": false,
"text": "(^.*?\\.com\\/)(?:.*?)(\\?utm.*$) $1$2"
},
{
"answer_id": 74509020,
"author": "Matteo B.",
"author_id": 20555223,
"author_profile": "https://Stackoverflow.com/users/20555223",
"pm_score": 2,
"selected": false,
"text": "(?:^.*?\\.com\\/)(.*?)(?:\\?utm.*$) $1"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13776038/"
] |
74,507,905
|
<p><a href="https://i.stack.imgur.com/0YcS9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0YcS9.png" alt="" /></a></p>
<p>How am i to fix the this any type error?</p>
<p>I tried passing custom type but that didn't work</p>
|
[
{
"answer_id": 74508077,
"author": "akash",
"author_id": 9839769,
"author_profile": "https://Stackoverflow.com/users/9839769",
"pm_score": 1,
"selected": false,
"text": "(^.*?\\.com\\/)(?:.*?)(\\?utm.*$) $1$2"
},
{
"answer_id": 74509020,
"author": "Matteo B.",
"author_id": 20555223,
"author_profile": "https://Stackoverflow.com/users/20555223",
"pm_score": 2,
"selected": false,
"text": "(?:^.*?\\.com\\/)(.*?)(?:\\?utm.*$) $1"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10641250/"
] |
74,507,915
|
<p>I have a dataframe called <em>movie_df</em> that has more than 3000 values of <strong>title, score, and rating.</strong>
Titles are unique. Scores are 0.0 - 10.0. Ratings are either PG-13, G, R, or X.
They are sorted by their rating, then ascending score.</p>
<p>I want to find the highest rated title per rating. The highest rated title doesn't have an equal rating with another title.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>title</th>
<th>score</th>
<th>rating</th>
</tr>
</thead>
<tbody>
<tr>
<td>avengers</td>
<td>5.4</td>
<td>PG-13</td>
</tr>
<tr>
<td>captain america</td>
<td>6.7</td>
<td>PG-13</td>
</tr>
<tr>
<td>iron man</td>
<td>8.6</td>
<td>PG-13</td>
</tr>
<tr>
<td>...</td>
<td>...</td>
<td>...</td>
</tr>
<tr>
<td>spiderman</td>
<td>7</td>
<td>R</td>
</tr>
<tr>
<td>daredevil</td>
<td>8.2</td>
<td>R</td>
</tr>
<tr>
<td>deadpool</td>
<td>10</td>
<td>R</td>
</tr>
</tbody>
</table>
</div>
<p>Expected output:
PG-13 : Iron Man,
R : Deadpool</p>
<p>I don't want to use a loop to find the highest rated title.</p>
<p>I tried:</p>
<pre><code>movie_df.sort_values(by=['rating', 'score'], inplace=True) # sort by rating, score
print(movie_df.to_string()) # to show dataframe
movie_df.groupby('rating').max()
</code></pre>
<p>It shows me the correct highest score, but the title is wrong. It shows me the max title too, but I don't want that. I want to know the title associated with the highest score.</p>
<p>Here is the actual data I'm using with its highest rated titles:
<a href="https://i.stack.imgur.com/bPcvk.png" rel="nofollow noreferrer">Rated G Actual</a>, <a href="https://i.stack.imgur.com/pOYKC.png" rel="nofollow noreferrer">NC-17 Actual</a>, <a href="https://i.stack.imgur.com/tWe0q.png" rel="nofollow noreferrer">PG Actual</a>, <a href="https://i.stack.imgur.com/gE1CA.png" rel="nofollow noreferrer">PG-13 Actual</a>, <a href="https://i.stack.imgur.com/FhDFd.png" rel="nofollow noreferrer">R Actual</a></p>
<p>And the <a href="https://i.stack.imgur.com/vNbVo.png" rel="nofollow noreferrer">output</a>:
<a href="https://i.stack.imgur.com/eGzDI.png" rel="nofollow noreferrer">Rated G output</a>, <a href="https://i.stack.imgur.com/uboCW.png" rel="nofollow noreferrer">PG Output</a>, <a href="https://i.stack.imgur.com/USYJg.png" rel="nofollow noreferrer">PG-13 Output</a>, <a href="https://i.stack.imgur.com/2ZHvf.png" rel="nofollow noreferrer">R Output</a></p>
|
[
{
"answer_id": 74507983,
"author": "jolyne",
"author_id": 16436207,
"author_profile": "https://Stackoverflow.com/users/16436207",
"pm_score": 0,
"selected": false,
"text": "movie_df.groupby('rating').idxmax()"
},
{
"answer_id": 74508013,
"author": "Oghli",
"author_id": 5169186,
"author_profile": "https://Stackoverflow.com/users/5169186",
"pm_score": 0,
"selected": false,
"text": "data = [['avengers', 5.4 ,'PG-13'],\n['captain america', 6.7, 'PG-13'],\n['spiderman', 7, 'R'],\n['daredevil', 8.2, 'R'],\n['iron man', 8.6, 'PG-13'],\n['deadpool', 10, 'R']]\n \ndf = pd.DataFrame(data, columns=['title', 'score', 'rating']) \n# Method 1 using lambda function\ndf = df.groupby('rating').apply(lambda x: x.sort_values('score', ascending = False).head(1))\nprint(df.reset_index(drop=True))\n\n# Method 2 \ndf = df.sort_values('score', ascending = False).groupby('rating').head(1)\nprint(df.reset_index(drop=True))\n title score rating\n0 iron man 8.6 PG-13\n1 deadpool 10.0 R\n title score rating\n0 deadpool 10.0 R\n1 iron man 8.6 PG-13\n"
},
{
"answer_id": 74508021,
"author": "Khaled DELLAL",
"author_id": 15852600,
"author_profile": "https://Stackoverflow.com/users/15852600",
"pm_score": 1,
"selected": false,
"text": "movie_df.reset_index(drop=True, inplace=True)\n\nm=max(movie_df['score'])\n\nprint(movie_df['rating'][list(movie_df['score']).index(m)])\n\n groupby() agg()"
},
{
"answer_id": 74508569,
"author": "lowrain",
"author_id": 20554268,
"author_profile": "https://Stackoverflow.com/users/20554268",
"pm_score": 0,
"selected": false,
"text": "movie_df[\"rank\"] = movie_df.groupby(\"rating\")[\"score\"].rank(\"dense\", ascending=False)\nmovie_df[movie_df[\"rank\"]==1.0][['title','score']]\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20554268/"
] |
74,507,938
|
<p>I'm making a loader for my React application in the form of a pizza that loses a piece every second.
<a href="https://i.stack.imgur.com/IS5g5.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IS5g5.jpg" alt="enter image description here" /></a></p>
<p>When I refresh the page, my loader doesn't behave correctly. Images appear simultaneously.</p>
<p><a href="https://i.stack.imgur.com/7OvLe.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7OvLe.jpg" alt="enter image description here" /></a></p>
<p>Below is the code for my component:</p>
<pre><code>import React, {useEffect, useState} from 'react';
import './Loader.css'
import pizza0 from '../../images/loader/pizza0.png'
import pizza1 from '../../images/loader/pizza1.png'
import pizza2 from '../../images/loader/pizza2.png'
import pizza3 from '../../images/loader/pizza3.png'
import pizza4 from '../../images/loader/pizza4.png'
import pizza5 from '../../images/loader/pizza5.png'
const Loader = () => {
const [imageStatus, setImageStatus] = useState({zero: true, first: false, second: false, third: false, fourth: false, fifth: false})
const [currentImage, setCurrentImage] = useState(0)
useEffect(() => {
setTimeout(() => action(), 1000);
const newCurrentImage = currentImage === 5 ? 0 : currentImage + 1
setCurrentImage(newCurrentImage)
}, [imageStatus])
function action() {
switch (currentImage) {
case 0:
setImageStatus({...imageStatus, zero: false, first: true})
break;
case 1:
setImageStatus({...imageStatus, first: false, second: true})
break;
case 2:
setImageStatus({...imageStatus, second: false, third: true})
break;
case 3:
setImageStatus({...imageStatus, third: false, fourth: true})
break;
case 4:
setImageStatus({...imageStatus, fourth: false, fifth: true})
break;
case 5:
setImageStatus({...imageStatus, fifth: false, zero: true})
break;
}
}
function PizzaImg0() {
return (
<img src={pizza0} className={imageStatus.zero ? "pizza active" : "pizza"}/>
);
}
function PizzaImg1() {
return (
<img src={pizza1} className={imageStatus.first ? "pizza active" : "pizza"}/>
);
}
function PizzaImg2() {
return (
<img src={pizza2} className={imageStatus.second ? "pizza active" : "pizza"}/>
);
}
function PizzaImg3() {
return (
<img src={pizza3} className={imageStatus.third ? "pizza active" : "pizza"}/>
);
}
function PizzaImg4() {
return (
<img src={pizza4} className={imageStatus.fourth ? "pizza active" : "pizza"}/>
);
}
function PizzaImg5() {
return (
<img src={pizza5} className={imageStatus.fifth ? "pizza active" : "pizza"}/>
);
}
return (
<div>
<PizzaImg0/>
<PizzaImg1/>
<PizzaImg2/>
<PizzaImg3/>
<PizzaImg4/>
<PizzaImg5/>
</div>
);
};
export default Loader;
</code></pre>
<p>And very simple css</p>
<pre><code>.pizza {
height: 120px;
display: none;
}
.pizza.active {
display: flex;
}
</code></pre>
<p>At the same time, if I switch to another tab or open an IDE and then return to the page, the loader works fine.
What changes in terms of React when I leave and then return to the page? And what can I do to get rid of the problem?</p>
|
[
{
"answer_id": 74507969,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 0,
"selected": false,
"text": "currentImage useEffect(() => {\n const newCurrentImage = currentImage === 5 ? 0 : currentImage + 1\n setCurrentImage(newCurrentImage)\n}, [imageStatus])\n\nuseEffect(() => {\n setTimeout(() => action(), 1000); \n}, [currentImage])\n"
},
{
"answer_id": 74508142,
"author": "Armin Ayari",
"author_id": 8863489,
"author_profile": "https://Stackoverflow.com/users/8863489",
"pm_score": 2,
"selected": true,
"text": "import React, { useEffect, useState, useRef } from 'react'\nimport './Loader.css'\nimport pizza0 from '../../images/loader/pizza0.png'\nimport pizza1 from '../../images/loader/pizza1.png'\nimport pizza2 from '../../images/loader/pizza2.png'\nimport pizza3 from '../../images/loader/pizza3.png'\nimport pizza4 from '../../images/loader/pizza4.png'\nimport pizza5 from '../../images/loader/pizza5.png'\n\nconst Loader = () => {\n const imageSrcs = useRef([pizza0, pizza1, pizza2, pizza3, pizza4, pizza5])\n const [currentImage, setCurrentImage] = useState(0)\n\n useEffect(() => {\n const timeoutId = setTimeout(() => {\n setCurrentImage((prevValue) => (prevValue === 5 ? 0 : prevValue + 1))\n }, 1000)\n\n return () => clearTimeout(timeoutId)\n }, [])\n\n return (\n <div>\n <img src={imageSrcs.current[currentImage]} className={'pizza active'} />\n </div>\n )\n}\n\nexport default Loader"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18146547/"
] |
74,507,966
|
<p>I want to read everything that is on stdin after 10 seconds and then break. The code I've been able to write so far is:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
int main() {
sleep(10);
char c;
while (1) { // My goal is to modify this while statement to break after it has read everything.
c = getchar();
putchar(c);
}
printf("Everything has been read from stdin");
}
</code></pre>
<p>So when the letter "c" is entered before the 10 seconds have elapsed, it should print "c" (after <code>sleep</code> is done) and then "Everything has been read from stdin".</p>
<p>So far I have tried:</p>
<ul>
<li>Checking if <code>c</code> is <code>EOF</code> -> <code>getchar</code> and similar functions never return <code>EOF</code> for <code>stdin</code></li>
<li>Using a <code>stat</code>-type function on <code>stdin</code> -> <code>stat</code>-ing <code>stdin</code> always returns 0 for size (<code>st_size</code>).</li>
</ul>
|
[
{
"answer_id": 74507969,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 0,
"selected": false,
"text": "currentImage useEffect(() => {\n const newCurrentImage = currentImage === 5 ? 0 : currentImage + 1\n setCurrentImage(newCurrentImage)\n}, [imageStatus])\n\nuseEffect(() => {\n setTimeout(() => action(), 1000); \n}, [currentImage])\n"
},
{
"answer_id": 74508142,
"author": "Armin Ayari",
"author_id": 8863489,
"author_profile": "https://Stackoverflow.com/users/8863489",
"pm_score": 2,
"selected": true,
"text": "import React, { useEffect, useState, useRef } from 'react'\nimport './Loader.css'\nimport pizza0 from '../../images/loader/pizza0.png'\nimport pizza1 from '../../images/loader/pizza1.png'\nimport pizza2 from '../../images/loader/pizza2.png'\nimport pizza3 from '../../images/loader/pizza3.png'\nimport pizza4 from '../../images/loader/pizza4.png'\nimport pizza5 from '../../images/loader/pizza5.png'\n\nconst Loader = () => {\n const imageSrcs = useRef([pizza0, pizza1, pizza2, pizza3, pizza4, pizza5])\n const [currentImage, setCurrentImage] = useState(0)\n\n useEffect(() => {\n const timeoutId = setTimeout(() => {\n setCurrentImage((prevValue) => (prevValue === 5 ? 0 : prevValue + 1))\n }, 1000)\n\n return () => clearTimeout(timeoutId)\n }, [])\n\n return (\n <div>\n <img src={imageSrcs.current[currentImage]} className={'pizza active'} />\n </div>\n )\n}\n\nexport default Loader"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15209993/"
] |
74,507,974
|
<p>This is inside Class component (d is reurning date objects, set is settings component)</p>
<pre><code> Maanantai = new DayLayout(d.state.maanantai)
Tiistai = new DayLayout(d.state.tiistai)
Keskiviikko = new DayLayout(d.state.keskiviikko)
Torstai = new DayLayout(d.state.torstai)
Perjantai = new DayLayout(d.state.perjantai)
Lauantai = new DayLayout(d.state.lauantai)
Sunnuntai = new DayLayout(d.state.sunnuntai)
set = new Settings
return (
<div>
<div><h3>Otsikko palkki</h3></div>
{(() => {
if (set.getWeekstart != "Maanantai") {
return (
<Sunnuntai/>
)
}
})()}
<Maanantai/>
<Tiistai/>
<keskiviikko/>
<Torstai/>
<Perjantai/>
<Lauantai/>
{(() => {
if (set.getWeekstart == "Maanantai") {
return (
<Sunnuntai/>
)
}
})()}
</div>
);
</code></pre>
<p>I am trying to render multiple week day tables. How ever VisualStudio code displayis errors in this code and ot dont work. Somehow it dont acccept acept new classes as objects, is there way a from and component from class object?</p>
|
[
{
"answer_id": 74507969,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 0,
"selected": false,
"text": "currentImage useEffect(() => {\n const newCurrentImage = currentImage === 5 ? 0 : currentImage + 1\n setCurrentImage(newCurrentImage)\n}, [imageStatus])\n\nuseEffect(() => {\n setTimeout(() => action(), 1000); \n}, [currentImage])\n"
},
{
"answer_id": 74508142,
"author": "Armin Ayari",
"author_id": 8863489,
"author_profile": "https://Stackoverflow.com/users/8863489",
"pm_score": 2,
"selected": true,
"text": "import React, { useEffect, useState, useRef } from 'react'\nimport './Loader.css'\nimport pizza0 from '../../images/loader/pizza0.png'\nimport pizza1 from '../../images/loader/pizza1.png'\nimport pizza2 from '../../images/loader/pizza2.png'\nimport pizza3 from '../../images/loader/pizza3.png'\nimport pizza4 from '../../images/loader/pizza4.png'\nimport pizza5 from '../../images/loader/pizza5.png'\n\nconst Loader = () => {\n const imageSrcs = useRef([pizza0, pizza1, pizza2, pizza3, pizza4, pizza5])\n const [currentImage, setCurrentImage] = useState(0)\n\n useEffect(() => {\n const timeoutId = setTimeout(() => {\n setCurrentImage((prevValue) => (prevValue === 5 ? 0 : prevValue + 1))\n }, 1000)\n\n return () => clearTimeout(timeoutId)\n }, [])\n\n return (\n <div>\n <img src={imageSrcs.current[currentImage]} className={'pizza active'} />\n </div>\n )\n}\n\nexport default Loader"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6244317/"
] |
74,507,998
|
<p>I have python dictionary with the below items :</p>
<pre><code>> ...
> {'HostName': 'DEMOBDDBX00100.demo', 'BackupStatus': 'SUCCESS'}
> {'HostName': 'DEMOBDDBX00200.demo', 'BackupStatus': 'SUCCESS'}
> {'HostName': 'DEMOBDDBX10101.demo', 'BackupStatus': 'FAILURE'}
> {'HostName': 'DEMOBDDBX10102.demo', 'BackupStatus': 'FAILURE'}
> {'HostName': 'DEMOBDDBX10201.demo', 'BackupStatus': 'FAILURE'}
> {'HostName': 'DEMOBDDBX10202.demo', 'BackupStatus': 'FAILURE'}
> {'HostName': 'DEMOBDMBX00100.demo', 'BackupStatus': 'SUCCESS'}
> {'HostName': 'DEMOBDMBX00200.demo', 'BackupStatus': 'SUCCESS'}
> {'HostName': 'DEMOBDMBX10101.demo', 'BackupStatus': 'FAILURE'}
> {'HostName': 'DEMOBDMBX10102.demo', 'BackupStatus': 'FAILURE'}
> {'HostName': 'DEMODACRT10100.demo', 'BackupStatus': 'SUCCESS'}
> {'HostName': 'DEMODACRT10200.demo', 'BackupStatus': 'SUCCESS'}
> {'HostName': 'DEMODACTS10101.demo', 'BackupStatus': 'SUCCESS'}
> {'HostName': 'DEMODACTS10102.demo', 'BackupStatus': 'SUCCESS'}
> {'HostName': 'DEMOKLIRT10100.demo', 'BackupStatus': 'SUCCESS'}
> {'HostName': 'DEMOKLIRT10200.demo', 'BackupStatus': 'SUCCESS'}
> {'HostName': 'DEMOKNORT10100.demo', 'BackupStatus': 'SUCCESS'}
> {'HostName': 'DEMOKNORT10200.demo', 'BackupStatus': 'SUCCESS'}
> {'HostName': 'DEMOKOSRT10200.demo', 'BackupStatus': 'SUCCESS'}
> {'HostName': 'DEMOLABTS10300.demo', 'BackupStatus': 'SUCCESS'}
> {'HostName': 'DEMOLABTS10400.demo', 'BackupStatus': 'SUCCESS'}
> ...
</code></pre>
<p>I need to filter out the values in Hostname only if the <code>BackupStatus == "FAILURE"</code>
I need the output as:</p>
<pre><code> {'HostName': 'DEMOBDMBX10101.demo', 'BackupStatus': 'FAILURE'}
{'HostName': 'DEMOBDDBX10101.demo', 'BackupStatus': 'FAILURE'}
{'HostName': 'DEMOBDDBX10102.demo', 'BackupStatus': 'FAILURE'}
{'HostName': 'DEMOBDDBX10201.demo', 'BackupStatus': 'FAILURE'}
{'HostName': 'DEMOBDDBX10202.demo', 'BackupStatus': 'FAILURE'}`
</code></pre>
<p>Can someone please help me with this?</p>
|
[
{
"answer_id": 74507969,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 0,
"selected": false,
"text": "currentImage useEffect(() => {\n const newCurrentImage = currentImage === 5 ? 0 : currentImage + 1\n setCurrentImage(newCurrentImage)\n}, [imageStatus])\n\nuseEffect(() => {\n setTimeout(() => action(), 1000); \n}, [currentImage])\n"
},
{
"answer_id": 74508142,
"author": "Armin Ayari",
"author_id": 8863489,
"author_profile": "https://Stackoverflow.com/users/8863489",
"pm_score": 2,
"selected": true,
"text": "import React, { useEffect, useState, useRef } from 'react'\nimport './Loader.css'\nimport pizza0 from '../../images/loader/pizza0.png'\nimport pizza1 from '../../images/loader/pizza1.png'\nimport pizza2 from '../../images/loader/pizza2.png'\nimport pizza3 from '../../images/loader/pizza3.png'\nimport pizza4 from '../../images/loader/pizza4.png'\nimport pizza5 from '../../images/loader/pizza5.png'\n\nconst Loader = () => {\n const imageSrcs = useRef([pizza0, pizza1, pizza2, pizza3, pizza4, pizza5])\n const [currentImage, setCurrentImage] = useState(0)\n\n useEffect(() => {\n const timeoutId = setTimeout(() => {\n setCurrentImage((prevValue) => (prevValue === 5 ? 0 : prevValue + 1))\n }, 1000)\n\n return () => clearTimeout(timeoutId)\n }, [])\n\n return (\n <div>\n <img src={imageSrcs.current[currentImage]} className={'pizza active'} />\n </div>\n )\n}\n\nexport default Loader"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74507998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20554387/"
] |
74,508,012
|
<p>How can I shift characters in a string to the right?
For Example I want to shift every letter of "Hello" 3 times to the right. The ending letter starts at the beginning. So the output should be "lloHe".</p>
<p>I tried to do it with a pointer. But the output is just "k". The program just takes the "h" from the hello and shifts it 3 digits to the right from the alphabet. But thats not what I intended to do. Any tips you can give me?</p>
<pre><code>#include <stdio.h>
int main () {
int a[5] = {'h','e','l', 'l','o','\0'};
char i;
char ptr;
ptr = a;
printf ("%c\n",ptr+3);
return 0;
}
</code></pre>
|
[
{
"answer_id": 74507969,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 0,
"selected": false,
"text": "currentImage useEffect(() => {\n const newCurrentImage = currentImage === 5 ? 0 : currentImage + 1\n setCurrentImage(newCurrentImage)\n}, [imageStatus])\n\nuseEffect(() => {\n setTimeout(() => action(), 1000); \n}, [currentImage])\n"
},
{
"answer_id": 74508142,
"author": "Armin Ayari",
"author_id": 8863489,
"author_profile": "https://Stackoverflow.com/users/8863489",
"pm_score": 2,
"selected": true,
"text": "import React, { useEffect, useState, useRef } from 'react'\nimport './Loader.css'\nimport pizza0 from '../../images/loader/pizza0.png'\nimport pizza1 from '../../images/loader/pizza1.png'\nimport pizza2 from '../../images/loader/pizza2.png'\nimport pizza3 from '../../images/loader/pizza3.png'\nimport pizza4 from '../../images/loader/pizza4.png'\nimport pizza5 from '../../images/loader/pizza5.png'\n\nconst Loader = () => {\n const imageSrcs = useRef([pizza0, pizza1, pizza2, pizza3, pizza4, pizza5])\n const [currentImage, setCurrentImage] = useState(0)\n\n useEffect(() => {\n const timeoutId = setTimeout(() => {\n setCurrentImage((prevValue) => (prevValue === 5 ? 0 : prevValue + 1))\n }, 1000)\n\n return () => clearTimeout(timeoutId)\n }, [])\n\n return (\n <div>\n <img src={imageSrcs.current[currentImage]} className={'pizza active'} />\n </div>\n )\n}\n\nexport default Loader"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74508012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20554373/"
] |
74,508,024
|
<p>Since mid 2022 it is now possible to get rid of <code>setup.py</code>, <code>setup.cfg</code> in favor of <code>pyproject.toml</code>. Editable installs work with recent versions of setuptools and pip and even the official <a href="https://packaging.python.org/en/latest/tutorials/packaging-projects/" rel="nofollow noreferrer">packaging tutorial</a> switched away from <code>setup.py</code> to <code>pyproject.toml</code>.</p>
<p>However, documentation regarding <code>requirements.txt</code> seems to be have been also removed, and I wonder where to put the <strong>pinned requirements</strong> now?</p>
<p>As a refresher: It used to be common practice to put the dependencies (without version pinning) in <code>setup.py</code> avoiding issues when this package gets installed with other packages needing the same dependencies but with conflicting version requirements. For packaging libraries a <code>setup.py</code> was usually sufficient.</p>
<p>For deployments (i.e. non libraries) you usually also provided a <code>requirements.txt</code> with version-pinned dependencies. So you don't accidentally get the latest and greatest but the exact versions of dependencies that that package has been tested with.</p>
<p>So my question is, did anything change? Do you still put the pinned requirements in the <code>requirements.txt</code> when used together with <code>pyproject.toml</code>? Or is there an extra section
for that in <code>pyproject.toml</code>? Is there some documentation on that somewhere?</p>
|
[
{
"answer_id": 74508233,
"author": "OranShuster",
"author_id": 2750734,
"author_profile": "https://Stackoverflow.com/users/2750734",
"pm_score": 1,
"selected": false,
"text": "pyproject.toml Requirements File Format requirements.txt"
},
{
"answer_id": 74508850,
"author": "Volodymyr Pivoshenko",
"author_id": 20554409,
"author_profile": "https://Stackoverflow.com/users/20554409",
"pm_score": -1,
"selected": false,
"text": "poetry pip pyproject.toml"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74508024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2881414/"
] |
74,508,043
|
<p>Please help me.</p>
<p>How can I call the changeAutoSlide() function on the class component Slide. How to pass this function to Parent.</p>
<p>Here function View is Child and class Slide is Parent component.</p>
<p>I want to stop the interval on component Slide with life cycle</p>
<p>Thanks.</p>
<pre><code>export default class Slider extends Component {
componentDidMount() {
this.autoSlide();
}
autoSlide = (interval) => {
return interval;
};
render() {
return <View autoSlide={this.autoSlide} />;
}
}
const View = () => {
const [slideIndex, setSlideIndex] = useState(1);
const setIndex = () => {
if (slideIndex > 0) {
setSlideIndex(slideIndex + 1);
}
if (slideIndex === 20) {
setSlideIndex(20 - slideIndex + 1);
}
};
const changeAutoSlide = () => {
const interval = setInterval(setIndex, 2000);
return autoSlide(interval);
};
changeAutoSlide(); //// I want pass this func on component Slide
return (
<section>
<h2>Hello React</h2>
</section>
);
};
</code></pre>
|
[
{
"answer_id": 74508274,
"author": "Azzy",
"author_id": 2122822,
"author_profile": "https://Stackoverflow.com/users/2122822",
"pm_score": 0,
"selected": false,
"text": "class Slider extends Component { \n\nconstructor(props) {\n super(props);\n // Don't call this.setState() here!\n this.state = { autoSlide: false };\n\n}\n\n render () {\n return <View autoSlide={this.state.autoSlide} />;\n }\n\n}\n\nconst View = ({ autoSlide = false }) => {\n\n useEffect(() => {\n\n // depending on autoSlide, you can stop or start the interval here\n\n let intervalId\n if (autoSlide) { \n intervalId = setInterval(setIndex, 2000);\n }\n\n return () => {\n // cleanup previous interval here\n intervalId && clearInterval(intervalId)\n }\n\n }, [autoSlide])\n\n return (\n \n )\n\n}\n"
},
{
"answer_id": 74509042,
"author": "Alex Yepes",
"author_id": 10339463,
"author_profile": "https://Stackoverflow.com/users/10339463",
"pm_score": 2,
"selected": true,
"text": "export default class Slider extends Component {\n constructor(props) {\n super(props);\n this.state = {\n slideIndex: 1\n }\n }\n componentDidMount() {\n this.autoSlide();\n }\n\n setIndex = () => {\n if (this.state.slideIndex > 0) {\n this.setState({\n slideIndex: this.state.slideIndex + 1\n }) \n }\n if (this.state.slideIndex === 20) {\n this.setState({\n slideIndex: 20 - this.state.slideIndex + 1\n }) \n }\n };\n\n changeAutoSlide = () => {\n const interval = setInterval(setIndex, 2000);\n return this.autoSlide(interval);\n };\n\n autoSlide = (interval) => {\n return interval;\n };\n\n render() {\n return <View autoSlide={this.autoSlide} setIndex={this.setIndex} changeAutoSlide={this.changeAutoSlide} />;\n }\n}\n const View = (props) => {\n // Use the props in this component like: \n // props.changeAutoSlide()\n // props.autoSlide \n // props.setIndex()\n\n return (\n <section>\n <h2>Hello React</h2>\n </section>\n );\n};\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74508043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20554299/"
] |
74,508,046
|
<p>I have a column named Interest with 10 values. I need to use function in R to multiply the values in the "Interest" column by 2 and to create a new column with the new multiplied values within the function.</p>
<p>Appreciate help, please.</p>
<p>I use the formula as :</p>
<pre><code>col<-function(col){
double<-col*2
return(double)
}
df_col_double
</code></pre>
<p>Col = the name for the Interest column and double as the new column with the multipled values.</p>
|
[
{
"answer_id": 74508266,
"author": "Julian",
"author_id": 14137004,
"author_profile": "https://Stackoverflow.com/users/14137004",
"pm_score": 0,
"selected": false,
"text": "mtcars col <- function(.data, col) {\n \n .data |> \n dplyr::mutate(dplyr::across({{col}}, ~.x*2, .names = \"double_{col}\"))\n}\ncol(mtcars,col = carb)\n"
},
{
"answer_id": 74508538,
"author": "user12256545",
"author_id": 12256545,
"author_profile": "https://Stackoverflow.com/users/12256545",
"pm_score": 0,
"selected": false,
"text": "doublecol <- function(data,col) {\n data[\"new_col\"]<-data[col]*2\n return(data)\n}\n\ndoublecol(iris,\"Sepal.Length\" )\n"
},
{
"answer_id": 74509320,
"author": "SALAR",
"author_id": 12517976,
"author_profile": "https://Stackoverflow.com/users/12517976",
"pm_score": 1,
"selected": false,
"text": "library(tidyverse)\nmtcars %>% mutate(. , hp_2=hp*2)\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74508046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20554500/"
] |
74,508,063
|
<p>I wanted to horizontally center an img element within an article element by using the margin: 0 auto; declaration.</p>
<p>For some reason, only the auto part of the value doesn't work as intended, because changing it to a number does.</p>
<p>Why is this? I suspect it has something to do with the article being a flex item because using the display: flex; declaration on it corrects the problem.</p>
<p>So, I realize I can still center the img element by turning its parent, the article, into a flex container.</p>
<p>But I don't understand why this is and how to make sense of it, and that's what's bugging me.</p>
<p>Specifically, why does only the auto part of the margin value not work on the img element when it's inside a flex item?</p>
<p>Also, once I use display: flex; on the article element, is it better practice to use margin: 0 auto; or justify-content: center; to center the image?</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>* {
padding: 0;
margin: 0;
display: border-box;
}
body {
display: flex;
justify-content: center;
align-items: center;
width: 100vw;
height: 100vh;
}
main {
display: flex;
justify-content: center;
align-items: center;
width: 1420px;
height: 500px;
background-color: hsl(212, 45%, 89%);
box-shadow: 0 15px 27px 0 hsla(0, 0%, 86%, 0.905);
}
article {
height: 300px;
width: 200px;
border-radius: 20px;
background-color: hsl(0, 0%, 100%);
box-shadow: 0 15px 20px 0 hsl(214, 41%, 85%);
}
img {
margin: 0 auto;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- displays site properly based on user's device -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Outfit&display=swap" rel="stylesheet">
<link rel="stylesheet" href="CSS/style.css">
<link rel="icon" href="images/favicon-32x32.png" sizes="32x32" type="image/png">
<meta name="description" content="QR Code for Frontend Mentor Homepage">
<meta name="author" content="Ryan R.">
<title>Frontend Mentor | QR Code</title>
</head>
<body>
<main>
<article>
<img src="https://qrcg-free-editor.qr-code-generator.com/main/assets/images/websiteQRCode_noFrame.png" alt="QR code" width="170" height="170">
</article>
</main>
</body>
</html></code></pre>
</div>
</div>
</p>
<p><a href="https://codepen.io/rrincones/pen/rNKpmpy" rel="nofollow noreferrer">CODEPEN</a></p>
|
[
{
"answer_id": 74508266,
"author": "Julian",
"author_id": 14137004,
"author_profile": "https://Stackoverflow.com/users/14137004",
"pm_score": 0,
"selected": false,
"text": "mtcars col <- function(.data, col) {\n \n .data |> \n dplyr::mutate(dplyr::across({{col}}, ~.x*2, .names = \"double_{col}\"))\n}\ncol(mtcars,col = carb)\n"
},
{
"answer_id": 74508538,
"author": "user12256545",
"author_id": 12256545,
"author_profile": "https://Stackoverflow.com/users/12256545",
"pm_score": 0,
"selected": false,
"text": "doublecol <- function(data,col) {\n data[\"new_col\"]<-data[col]*2\n return(data)\n}\n\ndoublecol(iris,\"Sepal.Length\" )\n"
},
{
"answer_id": 74509320,
"author": "SALAR",
"author_id": 12517976,
"author_profile": "https://Stackoverflow.com/users/12517976",
"pm_score": 1,
"selected": false,
"text": "library(tidyverse)\nmtcars %>% mutate(. , hp_2=hp*2)\n"
}
] |
2022/11/20
|
[
"https://Stackoverflow.com/questions/74508063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20554185/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.