QuestionId
stringlengths 8
8
| AnswerId
stringlengths 8
8
| QuestionBody
stringlengths 91
22.3k
| QuestionTitle
stringlengths 17
149
| AnswerBody
stringlengths 48
20.9k
|
---|---|---|---|---|
76391013 | 76391051 | I have for example the following np array
array([[ True, False, False],
[False, True, True],
[ True, True, True],
[False, True, True],
[False, True, True],
[ True, False, False],
[ True, True, False],
[False, False, True]])
I want to count the number of consecutive Trues along the columns, so in the above example, the first column contains 3 blocks of consecutive Trues, the second column contains 2 blocks, and the third contains 2 blocks. The output should then be
array([3, 2, 2])
I know I can do loops for each columns, like in this answer for a one-dimensional array, but what is a numpy-way for doing this on a 2-d array?
| How to count number of consecutive Trues in a numpy array along a given axis? | Use boolean arithmetic to identify the True that are not followed by a True (using slicing and pad), then sum the True per column:
out = ((a != np.pad(a[1:], ((0,1), (0,0)), constant_values=False))
& a).sum(axis=0)
Or:
out = (a & ~np.pad(a[1:], ((0,1), (0,0)), constant_values=False)).sum(axis=0)
Output:
array([3, 2, 2])
|
76390971 | 76391062 | I came across this when defaulting the three-way-comparison operator (spaceship operator).
Let's consider this small example:
#include <set>
#include <limits>
struct A {
float x;
auto operator<=>(A const& other) const = default; // will be std::partial_ordering
};
int main()
{
std::set<A>{ A{.x = std::numeric_limits<float>::quiet_NaN()}, A{.x = 1.f} };
}
Here we have a struct A that has one member of type float and defaults the <=> operator. Due tot he float member, the return type of the <=> operator will be std::partial_ordering. Partial ordering allows the category std::partial_ordering::unordered for elements that cannot be put into a specific order relative to other elements. For float this would affect nan for example. Any comparison of a float to nan will yield false.
Now, containers like std::set order their elements for being able to do binary search. For this they basically do a < comparison. Wouldn't this be broken for any type defining a partial ordering? In the example above, I can create a set of A and it compiles just fine. This seems like a pitfall to me because I assume that as soon as an element is inserted into the set that yields std::partial_ordering::unordered, the ordering inside the set would basically be broken, and various operations on the set would just cease to work correctly. Is my assumption correct?
Now, I know that it is possible in C++ to actually compare floats using a strong ordering. For this the function std::strong_order exists. So to fix the code, I could manually implement the three-way-comparison operator like this:
struct A {
float x;
auto operator<=>(A const& other) const{
return std::strong_order(x, other.x);
}
};
For this exmaple this is easy. But for larger structs/classes we are basically back to having to manually write comparisons that check member by member. Is there any way to achieve this comparison behaviour while still being able to default the spaceship operator? (without writing a wrapper class for float that offers strong order comparison)
tl;dr: To my understanding, set::set requires a strict weak ordering to work correctly. Still, I can construct a set using an element type that only offers a partial_ordering. This seems prone to causing bugs.
The example code is here, in case you're interested: https://godbolt.org/z/q4a95czTr
| Does std::set work correctly with a type that compares as std::partial_ordering? |
Wouldn't this be broken for any type defining a partial ordering?
No, not necessarily. I'm going to use float as the canonical example of a type with partial ordering, but the argument here applies to any partially ordered type.
std::set<float>, for instance, is not an inherently broken type. std::set<float>{1.f, 2.f, 3.f} will do exactly what you want, for instance. Indeed, it will do what you want for any floats you put into it... as long as they are not NaN.
There are really two approaches to this problem:
you could put it in the type system, requiring that <=> yields at least weak_ordering, thus rejecting std::set<float>
you could put it in the value system, and say it's undefined behavior if you have a partial ordering that compares as unordered. With <=>, if a <=> b is valid and yields a partial_ordering, you can assert that it's not unordered. That is, an operation is defined on a domain of values - not necessarily on every possible value in the type - and an algorithm is valid as long as the provided values are elements of the domain on which the operation is defined.
Rust does it the former way (which requires manually providing a comparison operation if you want to do something like sort a Vec<f32> - where that comparison probably just panics in the unordered case), and C++ has always done it the latter way - std::set<float> and sorting a std::vector<float> have always been valid in general, just with the precondition that NaN is not present in those containers (i.e. NaN is outside of the domain of the comparison).
I'm not sure that one approach is necessary better than the other. Rust's approach requires you to explicitly handle the unordered case, which is more tedious if you just don't have NaNs. In some sense, the C++ approach is more bug prone - since the unordered case won't be typically handled by simply aborting the program (although nothing stops you from writing an equivalently-buggy comparison in the Rust model).
|
76389516 | 76389696 | I'm trying to build a Sign In / Sign Up web server with PHP, which fills a mysql table.
The code is running kind of well, but when I tried to implement a control for the password to be the same, it seems like it skips the password match code and goes directly to the login form.
Here's the code:
<?php
require_once('config.php');
$email = $connessione->real_escape_string($_POST['email']);
$username = $connessione->real_escape_string($_POST['username']);
$password = $connessione->real_escape_string($_POST['password']);
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
// Controlla se l'email esiste già nel database
$query = "SELECT * FROM utenti WHERE email = '$email'";
$result = $connessione->query($query);
if ($result->num_rows > 0) {
echo "L'email esiste già nel database. Si prega di utilizzare un'altra email.";
} else {
// L'email non esiste nel database, procedi con la creazione dell'account
$passwordMatchError = '';
if(isset($_POST['password']) && isset($_POST['password1'])) {
$password = $_POST['password'];
$password1 = $_POST['password1'];
if($password === $password1) {
header("Location: login.html");
exit();
} else {
$passwordMatchError = 'Le password non corrispondono.';
}
}
$sql = "INSERT INTO utenti (email, username, password) VALUES ('$email', '$username', '$hashed_password')";
if ($connessione->query($sql) === true) {
// Registrazione avvenuta con successo, reindirizza l'utente alla pagina desiderata
header("Location: login.html");
exit();
} else {
echo "Errore durante la registrazione utente: " . $connessione->error;
}
}
$connessione->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div>
<form action="register.php" method="POST">
<h2>Registrati</h2>
<label for="email">Email</label>
<input type="text" name="email" id="email" placeholder="Inserisci la mail" required>
<label for="username">Username</label>
<input type="text" name="username" id="username" placeholder="Inserisci username" required>
<label for="password">Password</label>
<input type="password" name="password" id="password" placeholder="Inserisci la password" required>
<label for="password1">Conferma Password</label>
<input type="password" name="password1" id="password1" placeholder="Conferma password" required>
<input type="submit" value="Invia">
<?php if (isset($error)) : ?>
<p><?php echo $error; ?></p>
<?php endif; ?>
<p>Hai già un account? <a href="login.html">Accedi</a></p>
</form>
</div>
</body>
</html>
So far I tried to implement the register.php directly to the "index.php", but nothing worked. I was expecting the echo to show up when the user submits the form with two non-matching passwords, but when i click on submit it brings me directly to the login page, skipping the error. I think it brings the user directly to the login despite the password aren't matching or maybe it's skipping the pass control.
| PHP form not loading password match | What you're supposed to do to keep it efficient is to check if the passwords match first or not, then to check the existence of the email address, and from that point do your logic, so by that your code should look something like this:
if (isset($_POST['password']) && isset($_POST['password1'])) {
$password = $_POST['password'];
$password1 = $_POST['password1'];
if ($password === $password1) {
$query = "SELECT email ....";
$result = $connessione->query($query);
if ($result->num_rows > 0) {
echo "L'email ....";
} else {
$sql = "INSERT ....";
if ($connessione->query($sql) === true) {
....
}
}
}
}
other than that, important notes:
$password = $_POST['password']; overwrites your $password = $connessione->real_escape_string($_POST['password']);, name your variables wisely.
I highly recommend using PHP PDO to handle databases when you're working with databases, or MySQLi if you know what you're doing.
Revise your execution plan so you don't to run queries that might not be used because of a false condition.
|
76387495 | 76388317 | By design we can write to any node in the Cassandra replica set. For situation my replica set has 2 node. When I make a write operation to node A but the node is unavailable. Do I have catch exception then re-write to node B manually ?
On mongodb, their Driver have "Retry-able Writes" to auto write to another node if primary node is down. Does Cassandra have this feature ?
| resolve write problem when write to Cassandra replica set | When you write to Cassandra you specify the consistency level you wish to write wish - ranging from ANY which provides no guarantees, up to ALL which requests that all replicas in all DCs acknowledge back to the co-ordinator.
This write is sent to a single node - based on your load balancing policy - that node acts as the co-ordinator for the whole operation, and will return a single response of success / exception- your application does not have to itself individually send the write to multiple nodes, it just sends to 1 node (any node can be used) who co-ordinates the write to the replicas.
In a normal scenario of using local_quorum for a write with a very normal replication factor of 3 then as long as the co-ordinator has 2 of the 3 nodes providing acknowledgement of the write, the application will not get any exception - even if the 3rd node fails to write the data.
There is a retry policy available on the driver - which can allow for a retry in the event of a timeout, you should ensure though that the operation is idempotent when using this. (for example, appending an item to a list, retrying could result in the item being on the list twice on one of the replicas).
With your particular replication factor being 2 - you are currently in a position where you are lack consistency guarantees, or resilience.
one / local_one - only guarantees one of the nodes got the write. (Both are likely to get it but there is no guarantee provided)
quorum / local_quorum - requires both nodes acknowledge, so you have no ability to handle a node failure.
This is because the quorum of 2 is 2 - if you used 3 nodes with an RF=3, then local_quorum requires 2 of the 3, which would allow a node to be down while providing a stronger guarantee on consistency.
|
76391056 | 76391077 | I have a PropertyGroup like this:
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x86'">
<DefineConstants>$(DefineConstants)TRACE;X86</DefineConstants>
</PropertyGroup>
I want to know what the vertical bar (|) means when it is placed between parameters in the Condition attribute.
| What a vertical bar means in a PropertyGroup .csproj file | It doesn't mean anything - it's just a way of separating the configuration and platform.
Note that these aren't really parameters in a condition attribute - they're just property values which are replaced with the MSBuild property. | is unlikely to be part of a configuration or platform name, so it's a good choice as a separator.
You could have a condition of "'$(Configuration)/$(Platform)'=='Debug/x86'" just as easily, for example. | is just more conventional.
|
76389600 | 76389698 | I have a prototype cell with some labels and image views, all added thru Storyboard. I am trying to add a color background view behind these elements (sort of like a bubble view behind the text that is commonly used in messengers). Trying to add this bubble view through Storyboard became a nightmare because of constraints' conflicts. So I decided to add it programmatically right in the prototypeCell class:
let backgroundBubble = UIView()
override func awakeFromNib() {
super.awakeFromNib()
backgroundBubble.backgroundColor = .yellow
backgroundBubble.translatesAutoresizingMaskIntoConstraints = false
addSubview(backgroundBubble)
let constraints = [
backgroundBubble.topAnchor.constraint(equalTo: Label.topAnchor, constant: 0),
backgroundBubble.leadingAnchor.constraint(equalTo: Label.leadingAnchor, constant: 0),
backgroundBubble.bottomAnchor.constraint(equalTo: Label.bottomAnchor, constant: 0),
backgroundBubble.trailingAnchor.constraint(equalTo: Label.trailingAnchor, constant: 0)
]
NSLayoutConstraint.activate(constraints)
}
The problem is that now the bubble view is sitting in front of the content:
I tried to move it back with:
sendSubviewToBack(backgroundBubble)
but then the yellow bubbleView disappears altogether.
How do I move the bubbleView behind the content of the prototype cell?
| How do I move UIView to the back? | The content of a cell should basically always be added to its contentView. In this case, you may use contentView.insertSubview(backgroundBubble, at: 0) to add it as the first view in the hierarchy stack
|
76388105 | 76388318 | Calculate the most right non-zero digit of n factorial efficiently
I want to calculate the right most digit of a given number's factorial and print it. What I've done so far is:
import math
n = int(input())
fact = math.factorial(n)
print(str(fact).rstrip('0')[-1])
but I still get time limits and I look for faster solutions.
It's worth noting that I must use python to solve this problem.
Also, I shall point out that n is from 1 to 65536, the time limit is 0.5 seconds and I have 256 megabytes of memory.
| Efficient algorithm to calculate the most right non-zero digit of a number's factorial in Python | There is a neat recursive formula you can use: let D(n) be the last non-zero digit in n!
If n<10, use a lookup table
If the second last digit of n is odd, D(n) = 4 * D(n//5) * D(unit digit of n)
If the second last digit of n is even, D(n) = 6 * D(n//5) * D(Unit digit of n)
See this math stackexchange post for a proof.
Translating it into code:
def last_nonzero_factorial_digit(n):
lookup = [1, 1, 2, 6, 4, 2, 2, 4, 2, 8]
if n < 10:
return lookup[n]
if ((n // 10) % 10) % 2 == 0:
return (6 * last_nonzero_factorial_digit(n // 5) * lookup[n % 10]) % 10
else:
return (4 * last_nonzero_factorial_digit(n // 5) * lookup[n % 10]) % 10
On my laptop, this version runs ~14,000 times faster on a 5-digit number.
|
76390824 | 76391078 | I am using Cerberus to validate dataframes schema. Using this sample data and code below, the if-else statement should "data structure is valid", however it returns that the "data structure is not valid". Any insight would be appreciated.
import pandas as pd
from cerberus import Validator
df = pd.DataFrame({
'name': ['Alice', 'Bob', 'Charlie'],
'age': [25, 30, 35],
'city': ['New York', 'Paris', 'London']
})
data = df.to_dict()
schema = {
'name': {'type': 'string'},
'age': {'type': 'integer', 'min': 18},
'city': {'type': 'string'}
}
validator = Validator(schema)
is_valid = validator.validate(data)
if is_valid:
print("Data structure is valid!")
else:
print("Data structure is not valid.")
print(validator.errors)
Which results:
>>> Data structure is not valid.
>>> {'age': ['must be of integer type'], 'city': ['must be of string type'], 'name': ['must be of string type']}
| Python Cerberus - Validating Schema with this Example | It is failing because df.to_dict() returns dictionary with values ad dictionaries
data = df.to_dict()
print(data)
>>> {'name': {0: 'Alice', 1: 'Bob', 2: 'Charlie'}, 'age': {0: 25, 1: 30, 2: 35}, 'city': {0: 'New York', 1: 'Paris', 2: 'London'}}
If you want your schema to validate this data you need to change it to:
schema = {
"name": {"type": "dict", "valuesrules": {"type": "string"}},
"age": {"type": "dict", "valuesrules": {"type": "integer", "min": 18}},
"city": {"type": "dict", "valuesrules": {"type": "string"}},
}
|
76388981 | 76389717 | I am trying to scrape medium.com
I am using the following code:
from parsel import Selector
def get_trending(html):
selector = Selector(text=html)
text = selector.xpath("//*[@id='root']/div/div[4]/div[1]/div/div/div/div[2]/div/div[1]/div/div/div[2]/div[2]/a/div/h2")
# h2 = text.xpath("//h2/text()")
print(text)
response = requests.get("https://medium.com")
opponents = get_trending(response.text)
opponents
For some reason, it is giving an empty list as a result. I tried it with another h2 and I got the result I wanted. What might be the problem?
Here is the screenshot when I try the xpath in the inspect tool it is working as shown in the image below.
| WebScraping - Parsel: XPath in python | Here is a way to get those elements you're looking for using BeautifulSoup instead of Parsel -- you can adapt the code to Parsel if you are so inclined, and you can edit the class content as well to suit your usecase:
from bs4 import BeautifulSoup as bs
import requests
headers= {
'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36'
}
r = requests.get("https://medium.com/", headers=headers)
soup = bs(r.text, 'html.parser')
elements = soup.select('h2[class^="by j"]')
for x in elements:
print(x.text)
Result in terminal:
No One Really Tells You The Hardest Part Of Getting Older
A good day with Jeff
4 Secrets of Emotionally Stable People
Thought experiment in the National Library of Thailand
Unnatural Keys
Business Model Generation & Playing to Win
On the nature of elegance
It’s Time to Re-Design How We Think
Report from a Relationship
The Secret to Good Photography
A good day with Jeff
How I Turned My Company’s Docs into a Searchable Database with OpenAI
Thought experiment in the National Library of Thailand
What We’re Reading: Always Take a Peek at the Comments
A Contrarian Bet Against Generative AI: The Value of Being Uniquely Human
Why an Engineering Manager Should Not Review Code
BeautifulSoup documentation can be found here.
|
76387742 | 76388326 | I am trying to create a AWS Cogntio user pool using AWS Node js SDK in a lambda function. Our use case requires multi factor authentication and enabling authenticator apps for MFA. Looks like the cognito console UI provides an option to specify this but the API does not provide a way to enable authenticator apps for MFA.
Screenshot of Cognito user pool console UI showing option to enable Authenticator apps for MFA
Tried adding
"SoftwareTokenMfaConfiguration": {
"Enabled": true
}
field in the params to cognitoIdentityServiceProvider.createUserPool
API but the response indicates "Error creating User Pool:
UnexpectedParameter: Unexpected key 'SoftwareTokenMfaConfiguration'
found in params"
So my code snippet looks like below:
async function createCognitoUserPool(poolName) {
const cognitoIdentityServiceProvider =
new AWS.CognitoIdentityServiceProvider();
// Define the parameters for creating the user pool
const params = {
PoolName: poolName,
Policies: {
PasswordPolicy: {
MinimumLength: 8,
RequireUppercase: true,
RequireLowercase: true,
RequireNumbers: true,
RequireSymbols: true,
},
},
MfaConfiguration: "ON",
SoftwareTokenMfaConfiguration: {
Enabled: true,
},
AutoVerifiedAttributes: ["phone_number"],
SmsConfiguration: JSON.parse(
process.env.COGNITO_USER_POOL_SMS_CONFIGURATION
),
};
try {
// Call the CreateUserPool method
const response = await cognitoIdentityServiceProvider
.createUserPool(params)
.promise();
console.log("User Pool created successfully:", response.UserPool.Id);
return response.UserPool.Id;
} catch (error) {
console.error("Error creating User Pool:", error);
throw error;
}
}
Looking forward to find a solution for this. Thanks!
| How to enable authenticator MFA for cognitio user pool created using AWS Node js API? | You can use SetUserPoolMfaConfig method after creating the user pool.
From TOTP software token MFA page.
You can activate TOTP MFA for your user pool in the Amazon Cognito console, or you can use Amazon Cognito API operations. At the user pool level, you can call SetUserPoolMfaConfig to configure MFA and enable TOTP MFA.
Here are the links of API references from AWS documentation.
SetUserPoolMfaConfig
setUserPoolMfaConfig(params = {}, callback) ⇒ AWS.Request
|
76390765 | 76391096 | I have 2 different date fields, 1 when the case was created and the other when the case completed. I am trying to count total cases and total completions in say 2023.
Whenever I run my query and set the where field, both columns return the same figure.
SELECT COUNT(*) AS cases,
COUNT(IF(YEAR(tbl_lead.CompDate) = '2023', 1, NULL)) AS Completed,
tbl_lead.LeadSource
FROM tbl_lead
WHERE YEAR(tbl_lead.CompDate) = '2023'
GROUP BY tbl_lead.LeadSource
I guess what I'm trying to do is count all records for 2023 as cases, then count how many of those have completed in 2023. Is it impossible?
It should output as:
Cases
Completed
LeadSource
1000
500
Google
2000
700
Facebook
Whereas it currently outputs:
Cases
Completed
LeadSource
500
500
Google
700
700
Facebook
Thank you
| Count 2 different date fields in a single query | Your current query only refers to CompDate but in your question you refer to two different date columns. Is this what you are looking for:
SELECT SUM(CreateDate >= '2023-01-01' AND CreateDate < '2024-01-01') AS cases,
SUM(CompDate >= '2023-01-01' AND CompDate < '2024-01-01') AS Completed,
LeadSource
FROM tbl_lead
WHERE (CreateDate >= '2023-01-01' AND CreateDate < '2024-01-01')
OR (CompDate >= '2023-01-01' AND CompDate < '2024-01-01')
GROUP BY LeadSource
|
76389613 | 76389735 | I loop through a matrix and I would like to append a matrix row to another empty matrix if a specific condition is met. How do I do this without getting problems with the different indexes?
I had this code, but my dataset is very large, so I get problems in the implementation
for (i in 1:length(matrix1)) {
if ((substr(matrix1[i,1],6,7) == '02') == TRUE) {
for (j in 1:nrow(matrix2)) {
matrix2[j,] <- matrix1[i,]
}
}
}
Is there a more efficient solution?
dput(matrix1[1]) is c("271", "269", "274", "278", "293", "270", "274", "274", "275", "271", "2018-01-03_0445")
nrow(matrix1) is 400000
| R: Append matrix rows if condition is met | You can simply extract the rows satisfying your condition:
matrix2 <- matrix1[substr(matrix1[, 1], 6, 7) == '02', ]
|
76391004 | 76391129 | I'm trying to return links that have the word "attach" in a list using Python on a web page. But every method I use to find that word in the link gives almost the same error.
This is my code and the error is received from line 16:
from bs4 import BeautifulSoup
# pip install requests
import requests
def list_image_links(url):
# Send a GET request to the URL
response = requests.get(url)
soup = BeautifulSoup(response.content, "html.parser")
image_links = []
for image_links in soup.find_all('a'):
href = image_links.get('href')
#if attach is in href
word = 'attach'
if word in href:
image_links.append(href)
print(image_links)
return image_links
list_image_links('https://forum.ubuntu.ir/index.php?topic=211.0')
Error:
Traceback (most recent call last):
File "d:\...\main.py", line 22, in <module>
list_image_links('https://forum.ubuntu.ir/index.php?topic=211.0')
File "d:\...\main.py", line 16, in list_image_links
if word in href:
^^^^^^^^^^^^
TypeError: argument of type 'NoneType' is not iterable
| Error finding a string in another string in Python | In my perspective, the error you're encountering is due to the fact that some of the href values returned by link.get('href') may be None, and you cannot iterate over a None value. To avoid this error, you can add a condition to check if href is not None before checking if the word is in it. Here's the modified code:
from bs4 import BeautifulSoup
import requests
def list_image_links(url):
response = requests.get(url)
soup = BeautifulSoup(response.content, "html.parser")
image_links = []
for image_links in soup.find_all('a'):
href = image_links.get('href')
word = 'attach'
if href and word in href:
image_links.append(href)
# rest of the code...
The only change I made was adding an additional condition to the if clause, specifically if href and word in href:. I think this modification will resolve the issues.
|
76387594 | 76388332 | EDIT - Found that sorting is quick, real issue is performance of rendering huge list, so already answered
pls explain to me, why this does nothing:
I have array of thousands of items, there is a button for sorting them by some prop (changes "sortBy" prop. Sorting items takes almost 2 seconds, at least that how long after the click does the list change. During computing (until new list displayed) i want to display some "Loading" element. Im not aware, byt maybe Vue has some app-wide state to tell something is being recomputed?
<div v-if="loading">Wait pliz</div>
<div @click="sortBy='ctg'">SortByCtg</div>
<div v-for="item in sortedRows">{{item.ctg}} , {{item.name}} .... </div>
and the computed prop fn:
data: function(){
return {
'sortby': 'name',
'sortbyDir': 1,
'loading': false,
'rows': [ {'name':'abc','ctg':'def'}, ...]
}
},
computed: {
sortedRows: function(){
this.loading = true; // <<< should show element
var sortby = this.sortby;
var sortbyDir = this.sortbyDir;
var sorted = this.rows;
sorted = this.rows.sort(function(a, b) {
return sortbyDir * a[sortby].localeCompare(b[sortby]);
});
this.loading = false; // <<< hide element
return sorted;
}
},
...
but the "loading" element never shows. May it be sort is quick, and what is taking the time is the nodes generation itself? Then can i anyhow show the loader? Maybe somehow use next tick? I tried but with no result.
| Vue - show loader while computed property being computed | Sorting is quick (few miliseconds),
what really takes time is rendering the long list
|
76389468 | 76389744 | i have such data example
mydata=structure(list(month_id = c(201206L, 201206L, 201207L, 201207L,
201306L, 201306L, 201307L, 201307L, 201406L, 201406L, 201407L,
201407L, 201506L, 201506L, 201507L, 201507L, 201606L, 201606L,
201607L, 201607L, 201706L, 201706L, 201707L, 201707L), MDM_Key = c(1L,
2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L,
2L, 1L, 2L, 1L, 2L, 1L, 2L), sale_count = c(6978517L, 13957034L,
6148636L, 12297272L, 6147466L, 12294932L, 6050044L, 12100088L,
8127548L, 16255096L, 3341936L, 6683872L, 8995701L, 17991402L,
6803563L, 13607126L, 7098546L, 14197092L, 7855146L, 15710292L,
5575453L, 11150906L, 7543770L, 15087540L)), class = "data.frame", row.names = c(NA,
-24L))
I need for each group (mdm_key) to get the difference between the months (07-06) by sale_count Variable. The data contains histories by year. e.g. 06(june) and 07(jule) monthes for 2012,
06 and 07 for 2013 and so on...
For each year and each mdm_key I need to subtract the sale_count from month 7 to month 6.
So that the desired result for each year and each group mdm_key looks something like this
year MDM_Key sale_count
1 2012 1 -829881
2 2013 1 -97422
3 2014 1 -4785612
4 2015 1 -2192138
5 2016 1 756600
6 2017 1 1968317
7 2012 2 -1659762
8 2013 2 -194844
9 2014 2 -9571224
10 2015 2 -4384276
11 2016 2 1513200
12 2017 2 3936634
What is the easiest way to do such a subtraction?
Thanks for your any help.
| How to subtract values between months for each group and each year separately in R | Does this work?
library(tidyverse)
mydata %>%
# Filter on months 6 and 7
filter(str_sub(month_id, -2) %in% c("07", "06")) %>%
# Sort by Key + yearmonth
arrange(MDM_Key, month_id) %>%
# Group by Key
group_by(MDM_Key) %>%
# Calculate difference between sales
mutate(sale_diff = sale_count - lag(sale_count)) %>%
# Return unique values for each Key + year
filter(str_sub(month_id, -2) == "07") %>%
mutate(year = as.integer(str_sub(month_id, 1, 4))) %>%
select(year, MDM_Key, sale_count = sale_diff)
# A tibble: 12 x 3
# Groups: MDM_Key [2]
year MDM_Key sale_count
<int> <int> <int>
1 2012 1 -829881
2 2013 1 -97422
3 2014 1 -4785612
4 2015 1 -2192138
5 2016 1 756600
6 2017 1 1968317
7 2012 2 -1659762
8 2013 2 -194844
9 2014 2 -9571224
10 2015 2 -4384276
11 2016 2 1513200
12 2017 2 3936634
|
76391017 | 76391136 | I have a data frame with a column that contains string and digit,
Prod_nbr| prod_name
5 Natural chip companyseasalt175g
66 cC Nacho cheese 172g
61 Smiths Crinkle cut chips chicken135g
My desired output is
Prod_nbr|pack|prod_name
5 175g Natural chip....
66 172g cC Nacho cheese..
61 135g Smiths Crinkle...
I tried the code below but I didn't get my desired output, I got
df['pack'] = df['prod_name'].str.extract(r'\d+\s*(\w{,5})\b').fillna('')[0]
| How can I split a column in pandas | I would make a custom function to solve the parsing of the field, then apply it by row to the whole DataFrame. I prefer this way because most of the time you will find some unexpected string in the data, and using a function helps you with tweaking the output when needed.
Here is a quick example.
def parse(row):
s = row.prod_name
matches = re.findall('\d+g', s)
if matches:
if len(matches) == 1:
return matches[0] #if you have a single match
else:
return 'parsing error' #if you have multiple unexpected matches
return np.nan #no matches
df['pack'] = df.apply(parse, axis=1)
|
76389471 | 76389757 | I have a reactive form with two fields.First is custom input using ControlValueAccessor, and last is just regular HTML input.
Problem is, after performing form.reset(), the value of custom input is retained event its value in reactive form is null already.
As you can see in image, the first time I input and clear the values, it is working well.
But, as second time and onwards, the input value is STILL retained in custom input component. While, the normal HTML input is cleared and working well regardless of how many times I click Clear Input. Can you help me, please? Did I miss to put something?
Files:
app.component.ts/html: where the form lives
custom-input.component.ts/html: custom input component
Here is the form:
ts file
import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
})
export class AppComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
firstName: [{ value: '', disabled: false }],
lastName: [{ value: '', disabled: false }],
});
}
clearInput() {
this.form.reset();
}
}
html file:
<form [formGroup]="form">
<app-custom-input formControlName="firstName"></app-custom-input>
<input formControlName="lastName" placeholder="Last name" />
<button (click)="clearInput()">Clear Input</button>
</form>
<br />
<pre>{{ form.value | json }}</pre>
Here is the custom input file:
ts file:
import { Component, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Component({
selector: 'app-custom-input',
templateUrl: './custom-input.component.html',
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CustomInputComponent),
multi: true,
},
],
})
export class CustomInputComponent implements ControlValueAccessor {
value: string;
changed: (value: any) => void;
touched: () => void;
isDisabled: boolean;
writeValue(value: string): void {
this.value = value;
}
registerOnChange(fn: any): void {
this.changed = fn;
}
registerOnTouched(fn: any): void {
this.touched = fn;
}
setDisabledState(isDisabled: boolean): void {
this.isDisabled = isDisabled;
}
onChange(event: Event): void {
const value: string = (<HTMLInputElement>event.target).value;
this.changed(value);
}
}
html file:
<input
placeholder="First name"
[disabled]="isDisabled"
[value]="value"
(input)="onChange($event)"
(blur)="touched()"
/>
Full working code is here
| Angular retaining input value after form reset | Ok, you doing things well, but, you have to research a little bit deeper about this problem. If you go through HTML specification, you may find that the value attribute for the input html element is just an initial value. And that's why you get only first change if you push the reset button (actually you assign value there and writeValue method invokes).
So the solutions are several, the simplest and relative to your code style is to get the reference to the input and assign value manually:
custom-input.component.html
<input
placeholder="First name"
[disabled]="isDisabled"
(input)="onChange($event)"
(blur)="touched()"
#inputRef
/>
custom-input.component.ts
export class CustomInputComponent implements ControlValueAccessor {
@ViewChild('inputRef')
inputRef: ElementRef<HTMLInputElement>;
changed: (value: any) => void;
touched: () => void;
isDisabled: boolean;
writeValue(value: string): void {
if (this.inputRef) {
this.inputRef.nativeElement.value = value;
}
}
...
Another solution is to use ngModel and then it can work with value property binded to the input.
|
76388239 | 76388358 | class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> ans = new ArrayList<>();
for(int i=0;i<=nums.length-3;i++){
if(i==0 || nums[i]!=nums[i-1]){
int L=i+1;
int R = nums.length-1;
int target = 0-(nums[i]);
while(L<R){
if(nums[L]+nums[R]==target){
List<Integer> temp = new ArrayList<>();
temp.add(nums[i]);
temp.add(nums[L]);
temp.add(nums[R]);
ans.add(temp);
while(L<nums.length-1 && nums[L]==nums[L+1]) L++;
while(R>0 && nums[R]==nums[R-1]) R--;
L++;
R--;
}else if(nums[L]+nums[R]<target){
L+=1;
}else{
R+=1;
}
}
}
}
return ans;
}
# }
trying to solve the 3 sum problem of leetcode with 2 pointers approach . I am getting java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 6 at
if(nums[L]+nums[R]==target){
| Why does my 2 pointers approach to solve the 3 sum problem on LeetCode throw an index out of bounds error? | A error in the condition for increasing the R pointer is probably what is generating the ArrayIndexOutOfBoundsException in your code. R-=1 should be used instead of R+=1 to move the pointer to the left.
The updated code is as follows:
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> ans = new ArrayList<>();
for (int i = 0; i <= nums.length - 3; i++) {
if (i == 0 || nums[i] != nums[i - 1]) {
int L = i + 1;
int R = nums.length - 1;
int target = 0 - nums[i];
while (L < R) {
if (nums[L] + nums[R] == target) {
List<Integer> temp = new ArrayList<>();
temp.add(nums[i]);
temp.add(nums[L]);
temp.add(nums[R]);
ans.add(temp);
while (L < nums.length - 1 && nums[L] == nums[L + 1]) L++;
while (R > 0 && nums[R] == nums[R - 1]) R--;
L++;
R--;
} else if (nums[L] + nums[R] < target) {
L += 1;
} else {
R -= 1; // Fix the typo here
}
}
}
}
return ans;
}
}
|
76391053 | 76391162 | Folks, I need some help in understanding what's happening, I do not see how to pass an option to g++ compiler in a makefile. If you can just try to reproduce my stuff and get me some info, it would be valuable (for me).
Makefile content:
MYCPPFLAGS := what a surprise
%.o: %.cpp %.h
g++ $(MYCPPFLAGS) -c $< -o $@
dumpy:
echo $(MYCPPFLAGS)
It's not that kind of magic, isn't it???
Now I have a c++11 file named dessiner.cpp, if you need it I'll post it, but let's skip it for the moment. Please have a look at what I get in the terminal:
grenx08{lc177705}hw-m2-cpp-07-dessiner: make dumpy
echo what a surprise
what a surprise
grenx08{lc177705}hw-m2-cpp-07-dessiner: make dessiner.o
g++ -c -o dessiner.o dessiner.cpp
dessiner.cpp:18:13: warning: override controls (override/final) only available with -std=c++11 or -std=gnu++11 [enabled by default]
[...
a series of warnings/ errors because I did not use std=c++11 option]
make: *** [dessiner.o] Error 1
So my question is : why can't I see anything about "what a surprise" in the g++ command-line, but just four blank spaces???? Is make smarter than me (LoL, of course!!!) and erasing stupid options passed to g++??? The real issue is that in this case, I cannot even give the good options...
Please find hereby the sware versions, quite old stuff due to a constrained working environment. Any hint appreciated.
grenx08{lc177705}hw-m2-cpp-07-dessiner: make -v
GNU Make 3.82
Built for x86_64-redhat-linux-gnu
Copyright (C) 2010 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
grenx08{lc177705}hw-m2-cpp-07-dessiner: g++ --version
g++ (GCC) 4.8.5 20150623 (Red Hat 4.8.5-44)
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Edit 1:
grenx08{lc177705}hw-m2-cpp-07-dessiner: make -d dessiner.o
GNU Make 3.82
Built for x86_64-redhat-linux-gnu
[ tons of output ]
No need to remake target `dessiner.cpp'.
Finished prerequisites of target file `dessiner.o'.
Must remake target `dessiner.o'.
Invoking builtin recipe to update target `dessiner.o'.
g++ -c -o dessiner.o dessiner.cpp
[ other irrelevant output ]
grenx08{lc177705}hw-m2-cpp-07-dessiner: make -r dessiner.o
make: *** No rule to make target `dessiner.o'. Stop.
So it looks as my rule definition has a flaw? I have no .h file...
| g++ Flag variable not seen by make | This recipe:
%.o: %.cpp %.h
g++ $(MYCPPFLAGS) -c $< -o $@
tells make "hey make, if you're trying to build a target that matches the pattern %.o, and if you have prerequisites that match the patterns %.cpp and %.h, then you can use this recipe to build the target".
Note carefully: ALL the prerequisites MUST exist, or there must be rules telling make how to build them, otherwise this rule does not match.
In your case, you have a file dessiner.cpp but you do not have a file dessiner.h, and so make cannot create both the prerequisites, and so your rule doesn't match and make ignores it.
Then make looks in its built-in set of rules and it sees a %.o : %.cpp pattern rule there, and since that prerequisite exists, it matches and make runs that recipe. That recipe doesn't know anything about your variable MYCPPFLAGS so it's not used.
|
76389248 | 76389777 | It's probably simple, but I could not figure out how to fix it.
I use Bootstrap5.
The full code is here :
https://www.codeply.com/p/BywuhLNUXy
Seems codeply has some problems...
So I put it also on jsfiddle
https://jsfiddle.net/paul_z/y7a6dnkf/1/
Mainly it's contact directory page.
The code structure is
<div class="container">
<div class="row gy-5">
<div class="col-lg-6">
<div class="card m-b-30">
<div class="card-body py-5">
<div class="row">
<div class="col-lg-4 text-center">
<img src="/static/logo.png" alt="logo" >
</div>
<div class="col-lg-8">
<h5 class="card-text mb-0"><i class="fa-solid fa-person"></i> user 1</h5>
<p class="card-text">CDD IT Informatique</p>
<hr class="dropdown-divider">
<p class="card-text"><i class="fa-sharp fa-solid fa-building"></i> ###</p>
<p class="card-text"><i class="fa-solid fa-envelope"></i> mail</p>
<p class="card-text"><i class="fa-solid fa-phone"></i> phone</p>
</div>
</div>
</div>
</div>
</div>
...
On large screens it's shown two cards by column.
The problem is that cards sometimes different height.
For example for user 2 his role change : "Enseignant Chercheur Astrophysique Hautes Energies" instead "CDD IT Informatique" so this line take two lines instead of one line. And so the card for user 2 has height different to others cards.
How could I fix it ?
I don't know the cards size, so I could not fix it implicitly (and in any case it's probably not a good idea).
P.S.: I have also the same problem if logos have different sizes. Despite playing with img-fluid, widht, max-widht, max-height etc some logos change the height of card. But I think at first I have to fix the simple height problem.
| Same height of columns for bootstrap | The col elements already have the same height - Bootstrap v5's grid implementation based on flexbox already sees to that.
All you need to do is make the cards take 100% height of their parent:
.card { height: 100%; }
|
76389727 | 76389822 | On a google sheet, I have a sidebar form allowing user to add infos in another sheet.
I have to give an ID to each line so when a user add one, generate a new id.
example :
the sidebar form has two inputs : criterion number (int) and criterion (text). when a user add these inputs, I want to put them in a sheet with 3 columns : A = ID, B = criterion number and C = criterion.
To generate the ID, I created a creeID() function on the server side (this function checks the last ID in the sheet and generate the next ID, works well when tested) and I have to call it when the user add a line ("ajouter" button) in order to get a tab with this format [ID, criterion number, criterion] and to push this tab in the sheet with appendRow()
I thought I could use google script run with .withSuccessHandler() like said here and I tried something based on @Tanaike's help and this video.
Everything seems to work fine except that google.script.run.withSuccessHandler(data => {alert("preuve ajoutée")}).creeID() returns null
here is my html file :
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<style>
...
</style>
</head>
<body>
<p>Indicateur</p>
<input type="number" name="indicateur" id="indic" value="" min = "1" max = "32">
<p>Preuve</p>
<input type="text" name="preuve" id="preuve">
<br>
<input type="button" value="Ajouter" onclick="ajouter()">
<span class="annuler" onclick="google.script.host.close()">Annuler</span>
<script>
function ajouter() {
const inputs = document.querySelectorAll('#indic, #preuve');
let tab = [google.script.run.withSuccessHandler(data => {alert("preuve ajoutée")}).creeID()];
// Récupération des valeurs
for (const input of inputs) {
tab.push(input.value);
}
// Si tous les champs sont vides
if (tab.join('') == '') {
alert('Le formulaire est vide !');
return;
}
// Vider les champs
inputs.forEach(input => input.value = '');
// Envoi dans la feuille
google.script.run.ajouterLigne(tab);
}
</script>
</body>
</html>
and the javascript code :
function ajouterLigne(tab) {
const PREUVES = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("PREUVES");
console.log(tab)
PREUVES.appendRow(tab);
}
function creeID() {
const SHEET = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("PREUVES");
let lastRow = SHEET.getLastRow();
let lastIdRange = SHEET.getRange(lastRow, 1);
let lastId = lastIdRange.getValue();
let newId;
if (lastId == "ID") {
newId = 1;
} else {
newId = lastId + 1;
};
return(newId)
}
| google.script.run.function() returning null | In the case of your script, google.script.run.creeID() returns no value. I think that this is the reason for your current issue. From maybe I should use .withSuccessHandler() like said here but I don't know how., how about using withSuccessHandler() as follows?
In this case, please modify ajouter() of your Javascript as follows.
Modified script:
function ajouter() {
const inputs = document.querySelectorAll('input[type="text"]');
google.script.run.withSuccessHandler(tab => {
tab = [tab];
for (const input of inputs) {
tab.push(input.value);
}
if (tab.join('') == '') {
alert('Le formulaire est vide !');
return;
}
inputs.forEach(input => input.value = '');
google.script.run.ajouterLigne(tab);
}).creeID();
}
In this modification, when a button is clicked, a value of tab is retrieved and the values of tab and the inputted values are appended to the Spreadsheet.
Reference:
withSuccessHandler(function)
|
76388314 | 76388360 | I am following a tutorial
when he runs the code it gives ("Paul', 29, 1.75) but when I run it it gives me None
I tried
# -----Part 2------
# name,age,height
persons = [
("Alice", 25, 1.6),
("Brian", 35, 1.8),
("Paul", 29, 1.75),
("Martin", 32, 1.7)
]
def get_infos(name, l):
for i in l:
if i[0] == name:
return i
return None
infos = get_infos("Paul", persons)
print(infos)
and got:
None
but when he runed it he got:
('Paul', 29, 1.75)
| Why does my Python function return 'None' instead of ('Paul', 29, 1.75)? | It's an identation problem, always in the first iteration will return None, try by identing the return None one less tab, like:
def get_infos(name, l):
for i in l:
if i[0] == name:
return i
return None
|
76390825 | 76391171 | My data set has states as a column but no region column to group the states by. I would like to group the states into standard census bureau regions to get the count of employee IDs by region:
Select COUNT(DISTINCT Empl_ID) AS Employee_Count,
STATE
FROM Employee_Table
GROUP BY STATE
I tried exporting the query and then sorting in Excel but the dataset is too large for Excel.
| How to group states into regions when there is no region table | Create a table based on the data provided in the image:
create table region_state (region varchar(30), state varchar(30));
insert into region_state values
('Northen Region', 'New Jersey'),
('Northen Region', 'New York'),
('Midwest Region', 'Illinois')
...;
Now we can use a join query to get the region for each employee state as the following:
Select COUNT(DISTINCT E.Empl_ID) AS Employee_Count,
R.region
FROM Employee_Table E JOIN region_state R
ON E.state = R.state
GROUP BY R.region
If there are no duplicates in the Empl_ID column (and that is the typical case, i.e. Empl_ID is the primary key of the table) you would use COUNT(E.Empl_ID), with no need for DISTINCT.
|
76389271 | 76389823 | I want to round BigDecimal decimal part according to the following rules:
1710.10 becomes 1710.10
1710.11 becomes 1710.15
1710.15 becomes 1710.15
1710.16 becomes 1710.20
I tried this way new BigDecimal("1710.11").setScale(2, RoundingMode.HALF_UP)), expecting to get 1710.15 but I get 1710.11. I also tried with Apache Math Utils and Decimal Format but no way to achieve this.
| Round decimals up to multiples of 5 with BigDecimal | Your misunderstanding
First of all setting the scale on a BigDecimal only returns a BigDecimal with a different value if your current BigDecimal has a higher scale than you specified.
For example
new BigDecimal("1710.113").setScale(2, RoundingMode.HALF_UP)
returns a new BigDecimal equal to new BigDecimal("1710.11")
However, if you already have a scale of 2 or lower in this example, the new BigDecimal stays the same (read: equal).
HALF_UP simply means that a BigDecimal ending on a 5 will result in the higher value, e.g.
new BigDecimal("1710.115").setScale(2, RoundingMode.HALF_UP)
returns a result equal to new BigDecimal("1710.12")
Now to your question
Since your way of "rounding" doesn't actually change the scale, I doubt there is an already existing function you could use. However, doing it by hand is actually quite simple:
public class QuickMathz {
public static void main(String[] args) {
System.out.println(roundToNext5(new BigDecimal("1710.10"), 2));
System.out.println(roundToNext5(new BigDecimal("1710.11"), 2));
System.out.println(roundToNext5(new BigDecimal("1710.15"), 2));
System.out.println(roundToNext5(new BigDecimal("1710.16"), 2));
System.out.println(roundToNext5(new BigDecimal("1710.1135"), 2));
System.out.println(roundToNext5(new BigDecimal("1710.1635"), 2));
System.out.println(roundToNext5(new BigDecimal("1710.1675"), 2));
System.out.println();
System.out.println(roundToNext5(new BigDecimal("1710.10"), 3));
System.out.println(roundToNext5(new BigDecimal("1710.11"), 3));
System.out.println(roundToNext5(new BigDecimal("1710.15"), 3));
System.out.println(roundToNext5(new BigDecimal("1710.16"), 3));
System.out.println(roundToNext5(new BigDecimal("1710.1135"), 3));
System.out.println(roundToNext5(new BigDecimal("1710.1635"), 3));
System.out.println(roundToNext5(new BigDecimal("1710.1675"), 3));
}
public static BigDecimal roundToNext5(BigDecimal bigDecimal, int scale) {
// Get the last digit we need to decide if we have to round to 0, 5 or 10
int lastDigit = bigDecimal
.movePointRight(scale)
.remainder(BigDecimal.TEN).intValue();
// Setting the Scale to scale - 1 to remove one more digit than we need
// and then increase the scale to what we want
BigDecimal result = bigDecimal
.setScale(scale - 1, RoundingMode.DOWN)
.setScale(scale, RoundingMode.UNNECESSARY);
if (lastDigit == 0) {
// Last digit is a 0 upscaling adds a 0
return result;
} else if (lastDigit <= 5) {
// rounding up to 5
return result.add(new BigDecimal("5").movePointLeft(scale));
} else {
// rounding up to 10
return result.add(new BigDecimal("1").movePointLeft(scale - 1));
}
}
}
This class yields the output of
1710.10
1710.15
1710.15
1710.20
1710.15
1710.20
1710.20
1710.100
1710.110
1710.150
1710.160
1710.115
1710.165
1710.170
(It's neither optimized nor checked for negative values, so don't use in critical environments)
|
76389621 | 76389825 | I am working with dynamic list which add and delete items in the list. but when i delete a specific index with removeAt() method it always delete the last item, below is all code
import 'package:bizzsmart_web/constants/constants.dart';
import 'package:bizzsmart_web/model/expense_item_model.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class TestPage extends StatefulWidget {
const TestPage({Key? key}) : super(key: key);
@override
State<TestPage> createState() => _TestPageState();
}
class _TestPageState extends State<TestPage> {
List<ExpenseItemModel> expenses =
List.generate(1, (index) => ExpenseItemModel());
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
sbh(150),
Expanded(
child: ListView.builder(
itemCount: expenses.length,
itemBuilder: (c, i) {
return Column(
children: [
Row(
children: [
IconButton(
onPressed: () {
if (i == expenses.length - 1 ||
(expenses.length == 1)) return;
expenses.removeAt(i);
setState(() {});
},
icon: const Icon(CupertinoIcons.delete),
),
Expanded(
child: TextField(
onChanged: (val) {
if (expenses.length - 1 == i) {
expenses.add(ExpenseItemModel());
}
setState(() {});
},
decoration: InputDecoration(
border: border,
enabledBorder: border,
focusedBorder: border,
),
),
),
sbw(50),
],
),
sbh(10),
],
);
},
),
),
],
),
);
}
final border = OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
);
}
and Dart pad link : https://dartpad.dev/?id=9f87f484c1dc201b4d0c10d504eb7d1b
Somebody please help.
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.
| List is not updating properly after deleting an item in flutter | The problem is that you don't keep track on which TextField corresponds with which expense. To solve it you need to define controllers that you can give the TextFields. Like this for example:
class _TestPageState extends State<TestPage> {
List<ExpenseItemModel> expenses = [ExpenseItemModel()];
List<TextEditingController> controllers = [TextEditingController()];
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
SizedBox(height: 150),
Expanded(
child: ListView.builder(
itemCount: expenses.length,
itemBuilder: (c, i) {
return Column(
children: [
Row(
children: [
IconButton(
onPressed: () {
if (i == expenses.length - 1 ||
(expenses.length == 1)) return;
expenses.removeAt(i);
controllers.removeAt(i);
setState(() {});
},
icon: Icon(CupertinoIcons.delete),
),
Expanded(
child: TextField(
controller: controllers[i],
onChanged: (val) {
if (expenses.length - 1 == i) {
expenses.add(ExpenseItemModel());
controllers.add(TextEditingController());
}
setState(() {});
},
decoration: InputDecoration(
border: border,
enabledBorder: border,
focusedBorder: border,
),
),
),
SizedBox(width: 50),
],
),
SizedBox(height: 10),
],
);
},
),
),
],
),
);
}
final border = OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
);
}
Note I also changed the way you initialize expenses it a more concise way.
Instead of having two lists like this you might even want to consider making the TextEditingController part of your ExpenseItemModel and then do something like controller: expenses[i].controller,
|
76391151 | 76391228 | How program to join 2 different tables based on which one has the highest number of rows, with tidyverse? Now, the total_number_views_ndinstict has only 8 but in the future this may have more rows than the second total_number_views_unique_na which currently has 10 rows. I need both columns in the joined table.
Here is the first table:
> total_number_views_ndinstict
# A tibble: 8 × 2
app_name n_distinct_users
<chr> <int>
1 animals_to_groups 2
2 cage_randomiser 5
3 combo_cor 1
4 crispr_screen_viz 21
5 dep_map_bem 4
6 growth_rate_explorer 3
7 moprospector 2
8 translatability_single_gene 17
And the second table is
> total_number_views_unique_na
# A tibble: 10 × 2
app_name users_na
<chr> <int>
1 animals_to_groups 21
2 cage_randomiser 14
3 combo_cor 14
4 crispr_screen_viz 1
5 dep_map_bem 0
6 dtp_browser_prod 6
7 flat 81
8 growth_rate_explorer 48
9 moprospector 0
10 translatability_single_gene 2
Can someone help?
| how program to join 2 different tables based on which one has the highest number of rows, with tidyverse? | A full join will keep theh values of both tables
library(dplyr)
full_join(total_number_views_ndinstict, total_number_views_unique_na)
|
76388303 | 76388370 | I am displaying a selectInput in my shiny app and it is getting its choices from a dataframe (which is coming from a table in the database).
this table (dataframe) has primary key and title in it. I want to show my users the title, but when they choose an option, I want to get the Id of the selected option to use in my code.
I managed to get the selected "value" but I couldn't find how to get the "id" from the selected option.
below is a simple example of how my code is looking with test objects:
library(DT)
library(tidyverse)
library(shiny)
test_id <- c(1, 2, 3)
test_title <- c("a", "b", "c")
test_df <- data.frame(test_id, test_title)
test_df <- column_to_rownames(test_df, var = "test_id")
ui <- fluidPage(
selectInput("test", "test", choices = test_df),
textOutput("selectedItem")
)
server <- function(input, output, session) {
observeEvent(input$test, {
output$selectedItem <- renderText(input$test)
})
}
shinyApp(ui, server)
does anyone have a solution to get the "id" of the selected option?
I have tried this
output$selectedItem <- renderText(input$test)
but it is returning the value and not the Id
| How can I get the primary key of a selected option from a dataframe-based selectInput in Shiny? | You could pass a named vector or list to the choices argument.
From the docs (?selectInput):
If elements of the list are named, then that name — rather than the value — is displayed to the user.
library(tidyverse)
library(shiny)
test_id <- c(1, 2, 3)
test_title <- c("a", "b", "c")
test_df <- data.frame(test_id, test_title)
choices <- setNames(test_df$test_id, test_df$test_title)
ui <- fluidPage(
selectInput("test", "test", choices = choices),
textOutput("selectedItem")
)
server <- function(input, output, session) {
observeEvent(input$test, {
output$selectedItem <- renderText(input$test)
})
}
shinyApp(ui, server)
#>
#> Listening on http://127.0.0.1:5936
|
76389806 | 76389878 | I'm getting this error back though this same format seems to work in examples.
const response = await axios.get('http://localhost:5000/get-tasks')
const dataObject = response.data
const arrayOfKeys = Object.keys(dataObject)
const arrayOfData = Object.keys(dataObject).map((key) => dataObject[key])
console.log(arrayOfKeys)
console.log(arrayOfData)
}, [])```
| I'm getting an error: Effect callbacks are synchronous to prevent race conditions. I'm having trouble formatting it in the way it wants | The useEffect function arg can't be asynchronous, but you can call an async function inside it.
useEffect(() => {
async function getTasks() {
const response = await axios.get('http://localhost:5000/get-tasks')
const dataObject = response.data
const arrayOfKeys = Object.keys(dataObject)
const arrayOfData = Object.keys(dataObject).map((key) => dataObject[key])
console.log(arrayOfKeys)
console.log(arrayOfData)
};
getTasks();
}, []);
|
76391180 | 76391248 | I'm trying to setup a simple server using IntelliJ Community, Spring Boot and PostgreSQL.
I was following an online tutorial and downloaded the code from this github as an initial template. It should be a template generated by this website: https://start.spring.io/.
Bellow is the error log. How do I fix it?
2023-06-02T11:30:49.064-03:00 WARN 12340 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Unable to obtain connection from database: FATAL: password authentication failed for user "fernandakipper"
----------------------------------------------------------------------------------------------------------
SQL State : 28P01
Error Code : 0
Message : FATAL: password authentication failed for user "fernandakipper"
2023-06-02T11:30:49.071-03:00 INFO 12340 --- [ restartedMain] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2023-06-02T11:30:49.095-03:00 INFO 12340 --- [ restartedMain] .s.b.a.l.ConditionEvaluationReportLogger :
Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.
2023-06-02T11:30:49.140-03:00 ERROR 12340 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Unable to obtain connection from database: FATAL: password authentication failed for user "fernandakipper"
----------------------------------------------------------------------------------------------------------
SQL State : 28P01
Error Code : 0
Message : FATAL: password authentication failed for user "fernandakipper"
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1770) ~[spring-beans-6.0.9.jar:6.0.9]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:598) ~[spring-beans-6.0.9.jar:6.0.9]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:520) ~[spring-beans-6.0.9.jar:6.0.9]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:326) ~[spring-beans-6.0.9.jar:6.0.9]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.0.9.jar:6.0.9]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:324) ~[spring-beans-6.0.9.jar:6.0.9]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-6.0.9.jar:6.0.9]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:313) ~[spring-beans-6.0.9.jar:6.0.9]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-6.0.9.jar:6.0.9]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1156) ~[spring-context-6.0.9.jar:6.0.9]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:931) ~[spring-context-6.0.9.jar:6.0.9]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:608) ~[spring-context-6.0.9.jar:6.0.9]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:146) ~[spring-boot-3.1.0.jar:3.1.0]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:733) ~[spring-boot-3.1.0.jar:3.1.0]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:435) ~[spring-boot-3.1.0.jar:3.1.0]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:311) ~[spring-boot-3.1.0.jar:3.1.0]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1305) ~[spring-boot-3.1.0.jar:3.1.0]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1294) ~[spring-boot-3.1.0.jar:3.1.0]
at com.example.crud.CrudApplication.main(CrudApplication.java:10) ~[classes/:na]
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:578) ~[na:na]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-3.1.0.jar:3.1.0]
Caused by: org.flywaydb.core.internal.exception.FlywaySqlException: Unable to obtain connection from database: FATAL: password authentication failed for user "fernandakipper"
----------------------------------------------------------------------------------------------------------
SQL State : 28P01
Error Code : 0
Message : FATAL: password authentication failed for user "fernandakipper"
| How to fix this postgresql error `FATAL: password authentication failed for user ? | You have to install postgresql in your local and change the properties as per your db configuration. What they had provided is dummy. You have to put the actuals to make it work as expected
|
76388093 | 76388374 | I have a query "change the number of publications on artificial intelligence over time." Can you help me change this query not only about artificial intelligence, but also about subclasses of artificial intelligence?
SELECT ?year (COUNT(DISTINCT ?item) AS ?count)
WHERE {
?item wdt:P31 wd:Q13442814 ;
wdt:P921 wd:Q11660 ;
wdt:P577 ?date .
BIND(YEAR(?date) AS ?year)
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
GROUP BY ?year
ORDER BY ?year
| Change this SPARQL query | You have just to replace wdt:P921 with wdt:P921/wdt:P279* (see here for the new query).
wdt:P921/wdt:P279* is called property path. Such expressions are used for concatenating more properties in a single path which must comply with a certain structure. In this case, we are saying that the object of wdt:P921 can be the subject of wdt:P279 (* stands for "zero or more times") and the final object of such optional (chain of) wdt:P279 must be wd:Q11660.
Check out SPARQL 1.1 Query Language § 9 Property Paths for deepening this topic.
|
76391217 | 76391290 | data = pd.read_csv("MLs_Unit_per_day.csv",index_col='Date')
X1 X2 X3 X4 X5 X6
Date
01/01/2023 13 0 20 5 24 14
02/01/2023 13 0 20 5 24 15
03/01/2023 11 0 20 6 24 15
04/01/2023 12 0 20 6 22 16
05/01/2023 11 0 20 6 22 16
... ... ... ... ... ... ...
29/05/2023 13 1 23 6 22 17
30/05/2023 13 1 23 6 22 18
31/05/2023 13 1 23 7 23 18
01/06/2023 12 1 23 7 24 19
02/06/2023 13 0 23 8 24 19
I'm trying to group by month ans Sum X1, X2, etc for the hole month. how can I do?
thank you
I tried before without making Date as index with this
data.groupby(data['Date'].dt.strftime('%B'))['RO1'].sum().sort_values()
but it show me wrong time format and then wrong months
| Group table by month | You need to convert the date to datetime, then create a new column for month and finally use groupby
data = pd.read_csv("MLs_Unit_per_day.csv")
data['Date'] = pd.to_datetime(data['Date'], format='%d/%m/%Y')
# Create a separate column for year and month
data['YearMonth'] = data['Date'].dt.to_period('M')
monthly_data = data.groupby('YearMonth').sum()
print(monthly_data)
|
76388339 | 76388399 | I have a data.table
> dput(data.summary)
structure(list(summary_type = c("0", "1", "2"), count = structure(list(
62234441L, 5119L, 821770L), .internal.selfref = <pointer: 0x557538f028c0>)), row.names = c(NA,
-3L), class = c("data.table", "data.frame"), .internal.selfref = <pointer: 0x557538f028c0>)
data.summary
summary_type count
1: 0 62234441
2: 1 5119
3: 2 821770
Its a data.table with 3 row, I want to sort it by count
data.summary[order(count)]
But after this, there are only have 1 row in data.table
data.summary[order(count)]
summary_type count
1: 0 62234441
| R data.table lost rows after order | For some reason, your count column is a list.
library(data.table)
df <- structure(list(summary_type = c("0", "1", "2"), count = structure(list(
62234441L, 5119L, 821770L))), row.names = c(NA, -3L), class = c("data.table", "data.frame"))
df[count]
#Error in `[.data.table`(df, count, ) :
# count is not found in calling scope but it is a column of type list.
Use unlist:
df[order(unlist(count))]
# summary_type count
# 1: 1 5119
# 2: 2 821770
# 3: 0 62234441
|
76389918 | 76389919 | My MAUI app runs fine on the iOS Simulator in Debug mode, but when I run it on an iPad in Release mode, I get the following cryptic error when opening a certain screen:
System.Reflection.TargetInvocationException: Arg_TargetInvocationException
---> System.InvalidProgramException
at Microsoft.Maui.Controls.Internals.TypedBinding`2[[OIL.ISA.ViewModels.SettingsViewModel, OIL.ISA, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null],[System.String, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ApplyCore(Object sourceObject, BindableObject target, BindableProperty property, Boolean fromTarget)
at Microsoft.Maui.Controls.Internals.TypedBinding`2[[OIL.ISA.ViewModels.SettingsViewModel, OIL.ISA, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null],[System.String, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].Apply(Object context, BindableObject bindObj, BindableProperty targetProperty, Boolean fromBindingContextChanged)
at Microsoft.Maui.Controls.BindableObject.ApplyBindings(Boolean skipBindingContext, Boolean fromBindingContextChanged)
at Microsoft.Maui.Controls.BindableObject.SetInheritedBindingContext(BindableObject bindable, Object value)
at Microsoft.Maui.Controls.Element.SetChildInheritedBindingContext(Element child, Object context)
at Microsoft.Maui.Controls.Element.<OnBindingContextChanged>b__82_0(BindableObject child, Object bc)
at Microsoft.Maui.Controls.BindableObjectExtensions.PropagateBindingContext[Element](BindableObject self, IEnumerable`1 children, Action`2 setChildBindingContext)
at Microsoft.Maui.Controls.Element.OnBindingContextChanged()
at Microsoft.Maui.Controls.VisualElement.OnBindingContextChanged()
at Microsoft.Maui.Controls.View.OnBindingContextChanged()
at Microsoft.Maui.Controls.BindableObject.SetInheritedBindingContext(BindableObject bindable, Object value)
at Microsoft.Maui.Controls.Element.SetChildInheritedBindingContext(Element child, Object context)
at Microsoft.Maui.Controls.Element.<OnBindingContextChanged>b__82_0(BindableObject child, Object bc)
at Microsoft.Maui.Controls.BindableObjectExtensions.PropagateBindingContext[Element](BindableObject self, IEnumerable`1 children, Action`2 setChildBindingContext)
at Microsoft.Maui.Controls.Element.OnBindingContextChanged()
at Microsoft.Maui.Controls.VisualElement.OnBindingContextChanged()
at Microsoft.Maui.Controls.View.OnBindingContextChanged()
at Microsoft.Maui.Controls.BindableObject.SetInheritedBindingContext(BindableObject bindable, Object value)
at Microsoft.Maui.Controls.Element.SetChildInheritedBindingContext(Element child, Object context)
at Microsoft.Maui.Controls.TemplatedPage.SetChildInheritedBindingContext(Element child, Object context)
at Microsoft.Maui.Controls.Element.<OnBindingContextChanged>b__82_0(BindableObject child, Object bc)
at Microsoft.Maui.Controls.BindableObjectExtensions.PropagateBindingContext[Element](BindableObject self, IEnumerable`1 children, Action`2 setChildBindingContext)
at Microsoft.Maui.Controls.Element.OnBindingContextChanged()
at Microsoft.Maui.Controls.VisualElement.OnBindingContextChanged()
at Microsoft.Maui.Controls.Page.OnBindingContextChanged()
at Microsoft.Maui.Controls.ContentPage.OnBindingContextChanged()
at Microsoft.Maui.Controls.BindableObject.BindingContextPropertyChanged(BindableObject bindable, Object oldvalue, Object newvalue)
at Microsoft.Maui.Controls.BindableObject.SetValueActual(BindableProperty property, BindablePropertyContext context, Object value, Boolean currentlyApplying, SetValueFlags attributes, Boolean silent)
at Microsoft.Maui.Controls.BindableObject.SetValueCore(BindableProperty property, Object value, SetValueFlags attributes, SetValuePrivateFlags privateAttributes)
at Microsoft.Maui.Controls.BindableObject.SetValue(BindableProperty property, Object value, Boolean fromStyle, Boolean checkAccess)
at Microsoft.Maui.Controls.BindableObject.SetValue(BindableProperty property, Object value)
at Microsoft.Maui.Controls.BindableObject.set_BindingContext(Object value)
at OIL.ISA.Views.SettingsPage..ctor()
at System.Reflection.RuntimeConstructorInfo.InternalInvoke(Object , Object[] , Boolean )
Exception_EndOfInnerExceptionStack
at ObjCRuntime.Runtime.ThrowException(IntPtr )
at UIKit.UIApplication.UIApplicationMain(Int32 , String[] , IntPtr , IntPtr )
at UIKit.UIApplication.Main(String[] , Type , Type )
at OIL.ISA.Platforms.iOS.Program.Main(String[] args)
Unhandled managed exception: Arg_TargetInvocationException (System.Reflection.TargetInvocationException)
at ObjCRuntime.Runtime.ThrowException(IntPtr )
at UIKit.UIApplication.UIApplicationMain(Int32 , String[] , IntPtr , IntPtr )
at UIKit.UIApplication.Main(String[] , Type , Type )
at OIL.ISA.Platforms.iOS.Program.Main(String[] args)
(System.InvalidProgramException)
at Microsoft.Maui.Controls.Internals.TypedBinding`2[[OIL.ISA.ViewModels.SettingsViewModel, OIL.ISA, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null],[System.String, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ApplyCore(Object sourceObject, BindableObject target, BindableProperty property, Boolean fromTarget)
at Microsoft.Maui.Controls.Internals.TypedBinding`2[[OIL.ISA.ViewModels.SettingsViewModel, OIL.ISA, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null],[System.String, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].<…>
Searching for MAUI and InvalidProgramException does not give meaningful results. What's the cause of this exception?
As requested, here are some debugging details. The view model is like this:
public class SettingsViewModel : MainMenuPageViewModel {
public SettingsViewModel(ViewModelServices services, IPushNotificationsService pushNotificationsService, IDatabaseUploader databaseUploader, ISecureStorage secureStorage) : base(services) {
_pushNotificationsService = pushNotificationsService;
_databaseUploader = databaseUploader;
_databaseUploader.OnProgressChanged += OnDatabaseUploadProgressChanged;
_secureStorage = secureStorage;
Title = BaseApp.Settings;
PushNotificationsEnabled = pushNotificationsService.DeviceToken != null;
PushNotificationsEnabledMessage = PushNotificationsEnabled ? BaseApp.PushNotificationsEnabled : BaseApp.PushNotificationsNotEnabled;
Logout = new Command(DoLogout);
SendDatabase = new Command(UploadDatabase);
ShowPushNotificationDetails = new Command(ShowNotificationDetails);
using var context = new Context();
UserInformation = BaseApp.LoggedInAs + " " + LocalSettings.GetUsername(context);
UpdateSettingsInformation();
Settings.OnRefresh += (sender, e) => UpdateSettingsInformation();
}
private void UpdateSettingsInformation() {
StoreInformation = Settings.Store == null ? "" : Settings.Store.Number + " - " + Settings.Store.Name;
OnPropertyChanged(nameof(StoreInformation));
}
private void OnDatabaseUploadProgressChanged(object sender, ProgressChangedEventArgs e) {
Progress = e.ProgressPercentage / 100f;
}
private readonly IPushNotificationsService _pushNotificationsService;
private readonly IDatabaseUploader _databaseUploader;
private readonly ISecureStorage _secureStorage;
public string UserInformation { get; }
public string StoreInformation { get; private set; }
public bool PushNotificationsEnabled { get; }
public string PushNotificationsEnabledMessage { get; }
public string AppVersion => AppInfo.VersionString;
public ICommand Logout { get; }
public ICommand SendDatabase { get; }
public ICommand ShowPushNotificationDetails { get; }
...
}
and the page itself
<?xml version="1.0" encoding="UTF-8" ?>
<ContentPage
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:controls="clr-namespace:OIL.ISA.Controls"
xmlns:vm="clr-namespace:OIL.ISA.ViewModels"
xmlns:r="clr-namespace:OIL.ISA.Resources"
x:DataType="vm:SettingsViewModel"
x:Class="OIL.ISA.Views.SettingsPage"
Title="{Binding Title}"
Shell.NavBarIsVisible="{Binding NavBarIsVisible}">
<ContentPage.Content>
<AbsoluteLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
<Image AbsoluteLayout.LayoutFlags="All" AbsoluteLayout.LayoutBounds="0,0,1,1"
Source="background.jpg" Aspect="AspectFill" />
<StackLayout AbsoluteLayout.LayoutFlags="PositionProportional" AbsoluteLayout.LayoutBounds=".5,0" WidthRequest="320"
BackgroundColor="#D0FFFFFF" Spacing="16" Padding="16" Margin="0,16">
<Label Text="{Binding UserInformation}" HorizontalOptions="Center" />
<Label Text="{Binding StoreInformation}" HorizontalOptions="Center" />
<Button Style="{StaticResource SettingsButton}"
Text="{x:Static r:BaseApp.LogoutButton}"
Command="{Binding Logout}" />
<Button Style="{StaticResource SettingsButton}"
Text="{x:Static r:BaseApp.SendDatabaseButton}"
Command="{Binding SendDatabase}" />
<StackLayout Orientation="Horizontal">
<StackLayout.GestureRecognizers>
<TapGestureRecognizer Command="{Binding ShowPushNotificationDetails}" />
</StackLayout.GestureRecognizers>
<CheckBox IsChecked="{Binding PushNotificationsEnabled}" VerticalOptions="Center" IsEnabled="False" />
<Label Text="{Binding PushNotificationsEnabledMessage}" VerticalOptions="Center" />
</StackLayout>
<Label Text="{Binding Path=AppVersion, StringFormat={x:Static r:BaseApp.Version}}"
HorizontalOptions="Center" />
</StackLayout>
<controls:BlockingActivityIndicator
AbsoluteLayout.LayoutFlags="All" AbsoluteLayout.LayoutBounds="0,0,1,1"
IsVisible="{Binding IsBusy}"
Message="{Binding BusyMessage}"
HasProgress="{Binding HasProgress}"
Progress="{Binding Progress}" />
</AbsoluteLayout>
</ContentPage.Content>
</ContentPage>
(but as you can see, I already found the answer, I just need to document it somewhere in case someone else runs into it. Which, believe it or not, happened to myself, two months later, in another view model in the application. This is now the third hit in Google, I hope it can be useful this way)
| InvalidProgramException in TypedBinding when running on iPad | It turned out that my colleague used Resharper to analyze the code, and it had detected that one of the ViewModel properties:
public string AppVersion => AppInfo.VersionString;
could be changed into a static property:
public static string AppVersion => AppInfo.VersionString;
This did not cause any problems on Android or in the iOS Simulator, but was discovered only much later when testing a distribution build on an iPad. Making it an instance property again fixed the error.
|
76388166 | 76388426 | I am trying to run a playbook through AWX where I want to create a mariadb user with permissions. The playbook works nicely when run from ansible on my local machine. However, when I try to run the job on AWX, I get the following error :
"module_stdout": "Traceback (most recent call last):\r\n File "/home/ansible/.ansible/tmp/ansible-tmp-1685691063.0199862-220-69171919718447/AnsiballZ_mysql_user.py", line 107, in \r\n _ansiballz_main()\r\n File "/home/ansible/.ansible/tmp/ansible-tmp-1685691063.0199862-220-69171919718447/AnsiballZ_mysql_user.py", line 99, in _ansiballz_main\r\n invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\r\n File "/home/ansible/.ansible/tmp/ansible-tmp-1685691063.0199862-220-69171919718447/AnsiballZ_mysql_user.py", line 48, in invoke_module\r\n run_name='main', alter_sys=True)\r\n File "/usr/lib/python3.5/runpy.py", line 205, in run_module\r\n return _run_module_code(code, init_globals, run_name, mod_spec)\r\n File "/usr/lib/python3.5/runpy.py", line 96, in _run_module_code\r\n mod_name, mod_spec, pkg_name, script_name)\r\n File "/usr/lib/python3.5/runpy.py", line 85, in _run_code\r\n exec(code, run_globals)\r\n File "/tmp/ansible_community.mysql.mysql_user_payload_r3e02o87/ansible_community.mysql.mysql_user_payload.zip/ansible_collections/community/mysql/plugins/modules/mysql_user.py", line 352, in \r\n File "", line 969, in _find_and_load\r\n File "", line 958, in _find_and_load_unlocked\r\n File "", line 664, in _load_unlocked\r\n File "", line 634, in _load_backward_compatible\r\n File "/tmp/ansible_community.mysql.mysql_user_payload_r3e02o87/ansible_community.mysql.mysql_user_payload.zip/ansible_collections/community/mysql/plugins/module_utils/mysql.py", line 22, in \r\n File "/usr/local/lib/python3.5/dist-packages/pymysql/init.py", line 59, in \r\n from . import connections # noqa: E402\r\n File "/usr/local/lib/python3.5/dist-packages/pymysql/connections.py", line 206\r\n ):\r\n ^\r\nSyntaxError: invalid syntax\r\n"
Here's the task for creating the user :
- name : Create mariadb user
community.mysql.mysql_user:
login_user: root
login_password: "{{ root_password }}"
name: user
password: "{{ mariadb_user_pw }}"
priv: "*.*:PROCESS,SELECT,CREATE,CREATE TABLESPACE,INSERT"
state: present
| Invalid Syntax on community.mysql.mysql_user with Ansible AWX | Ensure the hosts have the correct package installed.
Include this in your playbook:
- name: ensure mysql package for the mysql api is installed
pip:
name: pymysql
executable: pip3
--
you should check your awx container.
either by logging in to the container itself, and check stuff manually, or you can do this w ansible as well.
- shell: locate ansible-galaxy
delegate_to: localhost
register: check_galaxy
- debug:
msg: "{{ check_galaxy.stdout }}"
delegate_to: localhost
Then, once you have the output, simply check the installed roles and it versions
- shell: ansible-galaxy collection list
delegate_to: localhost
register: check_collection
- debug:
msg: "{{ check_collection }}"
delegate_to: localhost
|
76390844 | 76391301 | Does it make sense to create your own class that implements the UserDetailsService interface? In many examples, I see how the UserDetailsService is embedded in the security configuration class, and not the class that implements it. What's the difference?
And why, when I enter the wrong username and password, I don't get the error message that I registered in PersonDetailsService? "Bad credentials" is coming out. I'm a beginner and just started learning spring security
@Configuration
@EnableWebSecurity
public class SecurityConfig {
private final PersonDetailsService personDetailsService;
@Autowired
public SecurityConfig(PersonDetailsService personDetailsService) {
this.personDetailsService = personDetailsService;
}
@Autowired
void configure(AuthenticationManagerBuilder builder) throws Exception {
builder.userDetailsService(personDetailsService);
}
@Bean
public PasswordEncoder getPasswordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
}
@Service
public class PersonDetailsService implements UserDetailsService {
private final PeopleRepository peopleRepository;
@Autowired
public PersonDetailsService(PeopleRepository peopleRepository) {
this.peopleRepository = peopleRepository;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Optional<Person> person = peopleRepository.findByUsername(username);
if (person.isEmpty())
throw new UsernameNotFoundException("User not found");
return new PersonDetails(person.get());
}
}
| The difference between UserDetailsService and the class that implements it | For your first question you spring security can authenticate multiple ways such as in memory and DB . in UserdetailsService and loadUserByUsername method you can customize how to authenticate users . and if you want DB mode you have multiple tables is DB and you can tell spring for finding username and password which table and columns must be check . for your second question put break point on your if statement and check what is person found . I think if it doesn't return username you have to use this if :
if(person.get()==null)
throw new UsernameNotFoundException("User not found");
|
76389703 | 76389923 | I try to store users inside collection in Firestore as documents and want to make every User ID is same as Document ID..
I tried but it still gives me another ID for the user:
Future<void> userSetupDone() async {
CollectionReference users = FirebaseFirestore.instance.collection('Users');
final docUser = FirebaseFirestore.instance.collection('Users').doc();
FirebaseAuth auth = FirebaseAuth.instance;
String? uid = docUser.id;
// String? uid = auth.currentUser?.uid.toString();
String? email = auth.currentUser?.email.toString();
String? phone = auth.currentUser?.phoneNumber.toString();
String? displayName = auth.currentUser?.displayName.toString();
users.add({'Uid': uid, "Email": email, "Phone": phone, "Name": displayName});
return;
}
| User Document ID is the same as User ID in Firestore | You have to update uid immediately after adding data to the database. Because you can not get id before adding that data from the Firestore Database.
You will get it by following code:
Future<void> userSetupDone() async {
CollectionReference users = FirebaseFirestore.instance.collection('Users');
final docUser = FirebaseFirestore.instance.collection('Users').doc();
FirebaseAuth auth = FirebaseAuth.instance;
String? email = auth.currentUser?.email.toString();
String? phone = auth.currentUser?.phoneNumber.toString();
String? displayName = auth.currentUser?.displayName.toString();
DocumentReference reference= await users.add({'Uid': '', "Email": email, "Phone": phone, "Name": displayName});
await reference.update({"Uid": reference.id});
return;
}
|
76381567 | 76388484 | I try to use Testcontainers (v1.18.0) for tests in a Quarkus (v2.16.4.Final, java: Amazon Corretto 17) application. When I start it up I get the following stack trace:
2023-06-01 13:11:10,326 INFO [org.tes.uti.ImageNameSubstitutor] (main) Image name substitution will be performed by: DefaultImageNameSubstitutor (composite of 'ConfigurationFileImageNameSubstitutor' and 'PrefixingImageNameSubstitutor')
2023-06-01 13:11:10,502 INFO [org.tes.doc.DockerClientProviderStrategy] (pool-3-thread-1) Loaded org.testcontainers.dockerclient.NpipeSocketClientProviderStrategy from ~/.testcontainers.properties, will try it first
2023-06-01 13:11:10,599 INFO [org.tes.doc.DockerMachineClientProviderStrategy] (pool-3-thread-1) docker-machine executable was not found on PATH ([C:\Python311\Scripts\, C:\Python311\, C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\wbin, C:\WINDOWS\system32, C:\WINDOWS, C:\WINDOWS\System32\Wbem, C:\WINDOWS\System32\WindowsPowerShell\v1.0\, C:\WINDOWS\System32\OpenSSH\, C:\ProgramData\chocolatey\bin, C:\Program Files\Azure Data Studio\bin, C:\Program Files\Microsoft\Azure Functions Core Tools\, C:\Program Files\PuTTY\, C:\Program Files\TortoiseGit\bin, C:\Program Files\Java\jdk17.0.4_8\bin, C:\Program Files\Java\scripts, C:\Program Files\nodejs\, C:\Program Files\dotnet\, C:\Program Files\TortoiseSVN\bin, C:\Program Files\Git\cmd, C:\Program Files\Maven\apache-maven-3.8.6\bin, , C:\Program Files\Docker\Docker\resources\bin, C:\Users\***\AppData\Local\Microsoft\WindowsApps, C:\Program Files\Azure Data Studio\bin, C:\Users\***\AppData\Local\Programs\Microsoft VS Code\bin, C:\Users\***\AppData\Roaming\npm, C:\Program Files\Java\jdk11.0.16_8\bin, C:\Users\***\.dotnet\tools, C:\Users\***\AppData\Local\JetBrains\Toolbox\scripts, C:\Users\***\.azure-kubelogin, C:\Users\***\AppData\Local\Microsoft\WindowsApps, C:\Program Files\Docker\Docker\resources\bin])
2023-06-01 13:11:10,601 ERROR [org.tes.doc.DockerClientProviderStrategy] (pool-3-thread-1) Could not find a valid Docker environment. Please check configuration. Attempted configurations were:
NpipeSocketClientProviderStrategy: failed with exception NoClassDefFoundError (com/github/dockerjava/api/command/LoadImageAsyncCmd). Root cause ClassNotFoundException (com.github.dockerjava.api.command.LoadImageAsyncCmd)As no valid configuration was found, execution cannot continue.
See https://www.testcontainers.org/on_failure.html for more details.
java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at io.quarkus.test.junit.QuarkusTestExtension.throwBootFailureException(QuarkusTestExtension.java:625)
at io.quarkus.test.junit.QuarkusTestExtension.interceptTestClassConstructor(QuarkusTestExtension.java:696)
at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.lambda$invoke$0(InterceptingExecutableInvoker.java:93)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
at org.junit.jupiter.api.extension.InvocationInterceptor.interceptTestClassConstructor(InvocationInterceptor.java:73)
at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.lambda$invoke$0(InterceptingExecutableInvoker.java:93)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.invoke(InterceptingExecutableInvoker.java:92)
at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.invoke(InterceptingExecutableInvoker.java:62)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeTestClassConstructor(ClassBasedTestDescriptor.java:363)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.instantiateTestClass(ClassBasedTestDescriptor.java:310)
at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.instantiateTestClass(ClassTestDescriptor.java:79)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.instantiateAndPostProcessTestInstance(ClassBasedTestDescriptor.java:286)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$4(ClassBasedTestDescriptor.java:278)
at java.base/java.util.Optional.orElseGet(Optional.java:364)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$5(ClassBasedTestDescriptor.java:277)
at org.junit.jupiter.engine.execution.TestInstancesProvider.getTestInstances(TestInstancesProvider.java:31)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$prepare$0(TestMethodTestDescriptor.java:105)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:104)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:68)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$prepare$2(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.prepare(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:90)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:147)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:127)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:90)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:55)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:102)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:54)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:57)
at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:232)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:55)
Caused by: java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at io.quarkus.test.junit.QuarkusTestExtension.doJavaStart(QuarkusTestExtension.java:237)
at io.quarkus.test.junit.QuarkusTestExtension.ensureStarted(QuarkusTestExtension.java:592)
at io.quarkus.test.junit.QuarkusTestExtension.beforeAll(QuarkusTestExtension.java:640)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeBeforeAllCallbacks$12(ClassBasedTestDescriptor.java:395)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeBeforeAllCallbacks(ClassBasedTestDescriptor.java:395)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.before(ClassBasedTestDescriptor.java:211)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.before(ClassBasedTestDescriptor.java:84)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:148)
... 36 more
Caused by: java.util.concurrent.CompletionException: java.lang.RuntimeException: Unable to start Quarkus test resource class com.***.locref.DatabaseResource
at java.base/java.util.concurrent.CompletableFuture.encodeThrowable(CompletableFuture.java:315)
at java.base/java.util.concurrent.CompletableFuture.completeThrowable(CompletableFuture.java:320)
at java.base/java.util.concurrent.CompletableFuture$AsyncRun.run(CompletableFuture.java:1807)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
at java.base/java.lang.Thread.run(Thread.java:833)
Caused by: java.lang.RuntimeException: Unable to start Quarkus test resource class com.***.locref.DatabaseResource
at io.quarkus.test.common.TestResourceManager$TestResourceEntryRunnable.run(TestResourceManager.java:487)
at java.base/java.util.concurrent.CompletableFuture$AsyncRun.run(CompletableFuture.java:1804)
... 3 more
Caused by: java.lang.IllegalStateException: Could not find a valid Docker environment. Please see logs and check configuration
at org.testcontainers.dockerclient.DockerClientProviderStrategy.lambda$getFirstValidStrategy$7(DockerClientProviderStrategy.java:256)
at java.base/java.util.Optional.orElseThrow(Optional.java:403)
at org.testcontainers.dockerclient.DockerClientProviderStrategy.getFirstValidStrategy(DockerClientProviderStrategy.java:247)
at org.testcontainers.DockerClientFactory.getOrInitializeStrategy(DockerClientFactory.java:150)
at org.testcontainers.DockerClientFactory.client(DockerClientFactory.java:186)
at org.testcontainers.DockerClientFactory$1.getDockerClient(DockerClientFactory.java:104)
at com.github.dockerjava.api.DockerClientDelegate.authConfig(DockerClientDelegate.java:108)
at org.testcontainers.containers.GenericContainer.start(GenericContainer.java:321)
at com.***.locref.DatabaseResource.start(DatabaseResource.java:28)
at io.quarkus.test.common.TestResourceManager$TestResourceEntryRunnable.run(TestResourceManager.java:481)
... 4 more
I have a class that implements QuarkusTestResourceLifecycleManager and starts a PostgreSQLContainer. I add it to a Test class annotated with @QuarkusTest and @QuarkusTestResource.
I used a very similar setup in a plain Java application without any problems. Problems only arise when Quarkus appears in the loop. I researched all exceptions related to the docker runtime and the NpipeSocketClientProviderStrategy but was not able to find a solution.
| How can I resolve the 'Could not find a valid Docker environment' error when using Testcontainers with Quarkus? | The versions of Quarkus and Testcontainers were incompatible. Resolving the version of Testcontainers via quarkus-bom in maven dependencyManagement resulted in 1.17.6 which works as expected.
|
76391249 | 76391358 | When using the default VScode formatter for c++. I want to keep format on save but I don't want the array to be changed this drastically.
It changes an array from this
const int level[] =
{
0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 0, 0, 0, 0,
1, 1, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3,
0, 1, 0, 0, 2, 0, 3, 3, 3, 0, 1, 1, 1, 0, 0, 0,
0, 1, 1, 0, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 0, 0,
0, 0, 1, 0, 3, 0, 2, 2, 0, 0, 1, 1, 1, 1, 2, 0,
2, 0, 1, 0, 3, 0, 2, 2, 2, 0, 1, 1, 1, 1, 1, 1,
0, 0, 1, 0, 3, 2, 2, 2, 0, 0, 0, 0, 1, 1, 1, 1,
};
to this
const int level[] = {
0,
0,
0,
0,
0,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
1,
1,
1,
1,
1,
1,
...
};
I want to keep format on save but I don't want the array to be changed this drastically.
| Is there a way to maintain C++ array formatting when using VScode's default formatter upon saving? | Not sure if you are trying to keep using the default formatting engine for some reason, I can't find an option to change this behavior using the default, but this behavior is not present when setting the option C_Cpp:Formatting (Extensions > C/C++ > Formatting > C_Cpp: Formatting) to vcFormat. If you just want format on save to not elongate your arrays Id use that engine option.
|
76389050 | 76389929 | Consider the following dataset
mydata<-data.frame(id = c("R007", "R008", "R008", "R009", "R009"),
statenumber= c(1, 2, 3, 4, 5),
startdate = c(20080101, 20080101, 20120301,20120101, 20121001),
enddate = c(20121201, 20120301, 20121201, 20121001, 20121201))
#if necessary we can write the dates as dates
mydata$startdate<-as.Date(as.character(mydata$startdate), "%Y%m%d")
mydata$enddate<-as.Date(as.character(mydata$enddate), "%Y%m%d")
The explanation of the dataset is as follows. A person with id number R007 lives during 2008 and 2012 at the same address. Person R008 lives during 2008 and 2012 at two addresses (state number). So for the years 2008-2011, he lives at address 2, and for the year 2012 he lives at address 3. Person R009 is only available in the file since 2012. During the first year of 2012 he lives at address 4 and in the last two months he lives at address 5.
Now I want to rearrange this dataset such that I have one address line per person per year. I would like to do this by making use of a reference month (say June). In other words, if a person lives in June at a particular address, I assign that address to him for the entire year. The dataset would then look as follows
endresult<-data.frame(id = c("R007", "R007","R007","R007","R007",
"R008", "R008", "R008", "R008","R008", "R009"),
statenumber = c(1,1,1,1,1,2,2,2,2,3,4),
year = c(2008, 2009, 2010, 2011, 2012,
2008,2009,2010,2011,2012, 2012))
Does anyone know how to get to this endresult dataset? I appreciate any help.
| Cleaning data in R by using a reference date | Two basic approaches: (1) do a yearly sequence, conditioning on whether the start is before and if the end is after June (06), used in the base R approach; (2) do a monthly sequence, conditioning (group-filtering) each year on whether "06" is in one of the months. They both work, which you choose depends on comfort/preference.
base R
Since this example uses "sequence by year", I'll use the fact that POSIXlt (notice the l, as opposed to the more common POSIXct) is really a list with elements for year, month, etc:
dput(as.POSIXlt(Sys.time()))
# structure(list(sec = 21.7977600097656, min = 30L, hour = 8L,
# mday = 2L, mon = 5L, year = 123L, wday = 5L, yday = 152L,
# isdst = 1L, zone = "EDT", gmtoff = -14400L), class = c("POSIXlt",
# "POSIXt"), tzone = c("", "EST", "EDT"))
With that, we can easily $-index the list and compare the month as a value. NOTE: ?POSIXlt shows that mon is ‘mon’ 0-11: months after the first of the year, meaning that June is 5 in 0-based months. (Ergo the use of 5 below.)
fun <- function(sd, ed) {
sdlt <- as.POSIXlt(sd)
edlt <- as.POSIXlt(ed)
if (sdlt$mon > 5) sdlt$year <- sdlt$year+1
if (edlt$mon < 5) edlt$year <- edlt$year-1
if (sdlt <= edlt) unique(format(seq.Date(as.Date(sdlt), as.Date(edlt), by = "year"), format="%Y"))
}
years <- Map(fun, mydata$startdate, mydata$enddate)
str(years)
# List of 5
# $ : chr [1:5] "2008" "2009" "2010" "2011" ...
# $ : chr [1:4] "2008" "2009" "2010" "2011"
# $ : chr "2012"
# $ : chr "2012"
# $ : NULL
out <- data.frame(
id = rep(mydata$id, lengths(years)),
statenumber = rep(mydata$statenumber, lengths(years)),
year = unlist(years))
out
# id statenumber year
# 1 R007 1 2008
# 2 R007 1 2009
# 3 R007 1 2010
# 4 R007 1 2011
# 5 R007 1 2012
# 6 R008 2 2008
# 7 R008 2 2009
# 8 R008 2 2010
# 9 R008 2 2011
# 10 R008 3 2012
# 11 R009 4 2012
If there's a chance to have duplicates (repeated states for an id that gap within the same year), then you can use unique(out).
Map just "zips" the data together. The individual calls to fun unrolled would look like this:
list(
fun(mydata$startdate[1], mydata$enddate[1]),
fun(mydata$startdate[2], mydata$enddate[2]),
fun(mydata$startdate[3], mydata$enddate[3]),
fun(mydata$startdate[4], mydata$enddate[4]),
fun(mydata$startdate[5], mydata$enddate[5])
)
The inclusion of ed on the end of c(seq.Date(..), ed) is to guard against the fact that seq may not include the year of the enddate. In this case, it ensures that R008 in state 2 sees 2012.
dplyr
In this (and the data.table) section, we'll use the monthly sequence instead, using format="%m" as the month. Dissimilar from POSIXlt above (June is 5), reading ?%strptime for the %-codes defines %m as ‘%m’ Month as decimal number (01-12), so June is back to "06".
library(dplyr)
mydata %>%
rowwise() %>%
summarize(
id, statenumber,
dates = seq(startdate, enddate, by = "month"),
year = format(dates, format = "%Y")) %>%
group_by(id, statenumber, year) %>%
filter(any(format(dates, format = "%m") == "06")) %>%
distinct(id, statenumber, year) %>%
ungroup()
# # A tibble: 11 × 3
# id statenumber year
# <chr> <dbl> <chr>
# 1 R007 1 2008
# 2 R007 1 2009
# 3 R007 1 2010
# 4 R007 1 2011
# 5 R007 1 2012
# 6 R008 2 2008
# 7 R008 2 2009
# 8 R008 2 2010
# 9 R008 2 2011
# 10 R008 3 2012
# 11 R009 4 2012
I generally try to avoid rowwise when able, but this problem does need to be executed one row at a time (which is effectively what Map is doing in the base R solution above).
data.table
library(data.table)
as.data.table(mydata)[, .(id, statenumber, dates = seq(startdate, enddate, by = "month")), by = .(seq(nrow(mydata)))
][, year := format(dates, format="%Y")
][, .SD[any(format(dates, format="%m") == "06"),], by = .(id, statenumber, year)
][, c("seq", "dates") := NULL
][, unique(.SD)]
# id statenumber year
# <char> <num> <char>
# 1: R007 1 2008
# 2: R007 1 2009
# 3: R007 1 2010
# 4: R007 1 2011
# 5: R007 1 2012
# 6: R008 2 2008
# 7: R008 2 2009
# 8: R008 2 2010
# 9: R008 2 2011
# 10: R008 3 2012
# 11: R009 4 2012
|
76388250 | 76388539 | So to summarize what i want:
Let's say i have
A B
1 "Tommy" "1,2,3"
2 "Berry" "3,4,5"
3 "Hank" "1,4,5"
4
5
6 "1"
7 "5"
I would like B6 to show "Tommy Hank" and B7 to show "Berry Hank"
If have managed to create this formula;
=IF(ISERROR(MATCH($A6,SPLIT(B1, "," , 1,1),0)),"",A1)
This formula will give me back the value "Tommy" but not Hank.
I want to list all corresponding A values for every B cell that contains the value "1".
I tried some things with arrayformula like =IF(ISERROR(MATCH($A6,SPLIT(B1:B3, "," , 1,1),0)),"",A1:A3) but i don't really understand what i'm doing here.
| Repeat a formula in google sheet within a single cell using different values | I was going to suggest
=ArrayFormula(
textjoin(" ",,
query(
{A$1:A$3,","&B$1:B$3&","},
"select Col1
where Col2 contains'"&","&A6&","&"'"
)
)
)
|
76391142 | 76391393 | I'm new using Riverpod and its providers. I have 2 almost identical futureProviders but one of them does not return data to UI even though API returns data.
Here is UI part
class ProductDetailSimilarProductsWidget extends ConsumerWidget {
const ProductDetailSimilarProductsWidget(this.product, {super.key});
final ProductDetailModel product;
@override
Widget build(BuildContext context, WidgetRef ref) {
var value = ref.watch(getSimilarProductsFutureProvider([product.Id, product.KategoriId]));
return Container(
height: MediaQuery.of(context).size.height * 0.5,
width: MediaQuery.of(context).size.width,
child: value.when(
data: (data) {
print("data length:${data.length}");
return ListView.builder(
itemCount: data.length,
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) {
return Padding(
padding: EdgeInsets.only(left: AppTheme.mediumPadding, right: AppTheme.mediumPadding),
child: ProductGridContainerWidget(product: data[index]),
);
},
);
},
error: (err, trace) {
return Text(err.toString());
},
loading: () => AppTheme.spinkit,
),
);
}
}
Here is futureProvider object
final getSimilarProductsFutureProvider = FutureProvider.family<List<Products>, List<dynamic>>((ref, value) async {
var result = await ProductDetailData().getSimilarProducts(productId: value[0], categoryId: value[1]);
print("result: ${result.length}");
return result;
});
Finally, the method does API call
var service = ApiService();
var sharedPreferencesManager = SharedPreferencesManager();
await sharedPreferencesManager.init();
var langId = await sharedPreferencesManager.getLanguageId();
var countryId = await sharedPreferencesManager.getCountryId();
var result =
await service.getRequest(subUrl: "${ApiRoutes.getSimilarProducts}?productId=$productId&langId=$langId&countryId=$countryId&categoryId=$categoryId");
List<Products> products = [];
var elements = json.decode(result.body);
await Future.forEach(elements, (element) => products.add(Products.fromMap(element as Map<String, dynamic>)));
return products;
Inside provider object, result.length variable prints 10 and it is expected. But inside the UI part, widget stucks on loading part and does not print data.length variable.
Is there something wrong in my codes? Also API works fine and successfully returns data.
| FutureProvider does not return data to UI | Your mistake is probably using the list as an argument for .family.
Ideally, the parameter should either be a primitive (bool/int/double/String), a constant (providers), or an immutable object that overrides == and hashCode.
Try using Records or create an immutable object with the two required fields.
|
76389061 | 76389938 | I am trying to create a function that applies random values to a range of parameters that are used in another function where the random sequence does not repeat.
The reason: used for random hyper parameter tuning and to cut down on processing by not repeating sequence.
Example Code:
num_evals = 2500
parameters = {
'n_parameter_1': range(2,100),
'n_parameter_2': range(1,20),
'n_parameter_3': range(2,150),
}
for i in range(num_evals):
n_parameter_1 = random.choice(parameters['n_parameter_1'])
n_parameter_2 = random.choice(parameters['n_parameter_2'])
n_parameter_3 = random.choice(parameters['n_parameter_3'])
The results then get populated to a file with the random parameters used to generate.
I need help with the second bit.
As this function runs over time, you start getting sequences that look like this:
n_parameter_1 = 54, n_parameter_2 = 15, n_parameter_3 = 120
n_parameter_1 = 10, n_parameter_2 = 12, n_parameter_3 = 89
n_parameter_1 = 54, n_parameter_2 = 15, n_parameter_3 = 120
I want to avoid the last sequence by either capturing the sequences in a list or dataframe etc. (already saving the sequences) that the function checks and then generates a new/different sequence if there is a duplicate sequence in the list.
Thanks for the help in advance.
| Non-Repeating Random Numbers for Multiple Variables | You can store sequences in a set and then check if a sequence is already in the set.
num_evals = 2500
i = 0
parameters = {
'n_parameter_1': range(2,100),
'n_parameter_2': range(1,20),
'n_parameter_3': range(2,150),
}
sequences = set()
while i < num_evals:
n_parameter_1 = random.choice(parameters['n_parameter_1'])
n_parameter_2 = random.choice(parameters['n_parameter_2'])
n_parameter_3 = random.choice(parameters['n_parameter_3'])
sequence = (n_parameter_1, n_parameter_2, n_parameter_3)
if sequence not in sequences:
sequences.add(sequence)
i += 1
The for loop has been changed to a while loop to allow for the conditional increment.
|
76389663 | 76389956 | I have an Excel file (which can optionally be loaded into a database, and into an array of arrays of course) with values such as:
A
B
C
NULL
NULL
zxy
xyz
xzy
NULL
xyz
xzy
xyy
yzy
yyx
yxy
NULL
NULL
xyx
xyz
NULL
yxx
and so on.
There are thousands of values.
Is there any known algorithm to come up with all possible combinations of rows where values are not "NULL"?
For example for the table above the result would be:
A
B
C
Number of occurrences
NULL
NULL
*
2
*
*
NULL
1
*
*
*
2
*
NULL
*
1
I feel like it is a typical task, but cannot find the algorithm anywhere. Would appreciate your help a lot.
| Algorithm to list all combinations from a table where data is present or NULL | If you are tempted to use pandas :
#pip install pandas
import pandas as pd
df = pd.read_excel("file.xlsx")
out = (
df.replace(".+", "*", regex=True).fillna("NULL")
.groupby(list(df), group_keys=False, sort=False)
.size().reset_index(name="Number of occurrences")
)
Output :
print(out)
A B C Number of occurrences
0 NULL NULL * 2
1 * * NULL 1
2 * * * 2
3 * NULL * 1
|
76388396 | 76388560 | My am calling POST on an API. The response has
{
"id" : "1234”,
---
}
I have following regular expression extractor:
However in the DELETE HTTP Request on API/${id}, I am getting API/NOT FOUND.
Please suggest whats the issue with my regular expression ?
| Unable to extract id from json response in jmeter | JSON is not a regular language hence using regular expressions for it is not the best idea
Consider using JSON Extractor instead, the relevant JSONPath expression is just id
Demo:
|
76391063 | 76391398 | I am struggling with ESLint not being able to load in IntelliJ 2023.1 on Ubuntu 22.04.
It seems like there are several syntax errors in the libraries, but I just could not belive that.
What could I do?
Best regards
Peter
PS: error in detail:
If I correct this specific one (yes, I should not overwrite libraries, especially when I'm not an expert on that stuff), a new syntax error comes again.
| ESLint error: Failed to load 'eslint-plugin-jsdoc' in IntelliJ on Ubuntu - troubleshooting tips? | What Node.js version do you have? Looks like it doesn't support the nullish coalescing operator; please make sure that the interpreter set up in Settings | Languages & Frameworks | Node.js is v. 14 or higher, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing#browser_compatibility
|
76384879 | 76389984 | No access to localhost sites anymore.
I have IIS 6.0 running on a Windows 7 64 bit PC where I work on local websites.
I have 4 sites that were working until yesterday and now give me a 404 error when I try to access. I have tried IE, Chrome, Brave and Firefox.
One of the sites I'm working on for our karate club is a login for weekend courses where the member's card is checked by a webcam in a box to allow them to log in. It was working (they all were), but I needed this site to be HTTPS as the javascripts for the camera must be downloaded using this protocol. The location of the course may not have internet access so these must be loaded from the localhost site.
I was messing about trying creating self signed certificates for localhost which I managed to do, but i could not get the site to work using https. I then removed the certificates but the sites would not then access normally (http).
I cleared the cache of each browser and have reset IIS and restarted the pc. I also went through and disabled the world wide services, restarted the PC and restarted WWS.
Nothing has helped.
Any advice/pointers would be a great help.
Thanks in Advance,
Andy
| Can't access localhost sites anymore | I solved the problem myself by doing a system restore to the point just before i installed the IIS toolkit. My sites are now back to working using http again.
I'm guessing that it was something in the toolkit that caused the problem.
Thanks for the advice anyway.
Regards,
Andy
|
76388415 | 76388571 | How can I access complete state in redux?
const { createStore } = require("redux");
const initialState = {
posts: [
{ id: 1, title: "Post one" },
{ id: 2, title: "Post two" },
],
};
My Posts Reducer
const PostsReducer = (state = initialState, action) => {
switch (action.type) {
case "add_post":
return {
...state,
posts: [...state.posts, action.payload],
};
case "delete_post":
return {
...state,
posts: state.posts.filter((post) => post.id !== action.payload),
};
case "get_all_posts":
return state.posts;
default:
return state;
}
};
const store = createStore(PostsReducer);
My Action Creators:
const GetAllPosts = () => {
return {
type: "get_all_posts",
};
};
const AddPost = (payload) => {
return { type: "add_post", payload };
};
const removePost = (payload) => {
return { type: "delete_post", payload };
};
Accessing Store data:
store.subscribe(() => {
const data = store.getState();
console.log(data.posts);
});
store.dispatch(GetAllPosts());
While I am console logging data.posts it returns undefined.
I am accessing using subscriber method:
store.subscribe(() => {
const data = store.getState();
console.log(data.posts);
});
store.dispatch(GetAllPosts());
Note:
I am Using Redux(4.2.1)
By using GetAllPosts(), I am able to access data, but I cannot get data.posts in console.
| Why is data.posts undefined when accessing using subscriber method in redux? | The get_all_posts case is returning the state.posts array directly instead of setting a state object with a posts property.
case "get_all_posts":
return state.posts; // <-- just the posts array
Update get_all_posts case to return the correct state invariant, likely the initial state value with all the posts included.
Example:
const initialState = {
posts: [
{ id: 1, title: "Post one" },
{ id: 2, title: "Post two" },
],
};
const PostsReducer = (state = initialState, action) => {
switch (action.type) {
case "add_post":
return {
...state,
posts: [...state.posts, action.payload],
};
case "delete_post":
return {
...state,
posts: state.posts.filter((post) => post.id !== action.payload),
};
case "get_all_posts":
return { ...initialState };
default:
return state;
}
};
|
76390677 | 76391409 | I have deployed reactjs project on hostinger where i open any new tab or refresh the page it give error 404
i have used latest version of react router dom
Index.js
<Browserrouter>
<App/>
<Browserrouter/>
App.js
<Routes>
<Route path="/" element={<Home/>}/>
<Route path="/about-us" element={<Aboutus/>}/>
<Route path="/contact-us" element={<Contactus/>}/>
<Route path="/career" element={<Career/>}/>
<Route path="/work" element={<Work/>}/>
<Route path="/services" element={<ServicesMain/>}/>
<Routes/>
| Why does my reactjs project on hostinger give a 404 error when opening a new tab or refreshing the page? | The issue is not with the React but your hosting config. You need to add rewrite rules by adding .htaccess file inside your 'public' folder with the following code.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule . /index.html [L]
</IfModule>
|
76389787 | 76389989 | I'm writing custom logging for the bash:
#!/usr/bin/env bash
set -e +x
SCRIPT_LOG_NAME='[MYSCRIPT]'
SCRIPT_LOG_DATETIME_FORMAT="+%Y-%m-%d %H:%M:%S"
SCRIPT_LOG_LEVEL_INFO='INFO'
SCRIPT_LOG_PATTERN="${SCRIPT_LOG_NAME} $(date "${SCRIPT_LOG_DATETIME_FORMAT}") $1 : $2"
log_general() {
...
}
log_info() {
log_general "$SCRIPT_LOG_LEVEL_INFO" "$1"
}
And I want to pass variables $SCRIPT_LOG_LEVEL_INFO and "$1" as parameters to the function log_general(). And use this parameters in the $SCRIPT_LOG_PATTERN to achive output:
[MYSCRIPT] 2023-01-01 10:10:10 INFO : Something logged
I tried something like:
log_general() {
echo -e "$SCRIPT_LOG_PATTERN" "$1" "$2"
}
Or
SCRIPT_LOG_LEVEL=''
SCRIPT_LOG_PATTERN="${SCRIPT_LOG_NAME} $(date "${SCRIPT_LOG_DATETIME_FORMAT}") ${SCRIPT_LOG_LEVEL} : "
log_general() {
SCRIPT_LOG_LEVEL=$SCRIPT_LOG_LEVEL_INFO
echo -e "${SCRIPT_LOG_PATTERN}${1}"
}
log_info() {
log_general "$1"
}
But I could not achieve the desired result. Can you help me, please?
| Passing variables to a variable in bash | If you'd like to use ${SCRIPT_LOG_PATTERN} as a global variable and later on substitute the ${1} and ${2} you would have to escape the $ sign and then evaluate the string later on in log_general.
This would look something like this:
#!/bin/bash
set -e +x
SCRIPT_LOG_NAME='[MYSCRIPT]'
SCRIPT_LOG_DATETIME_FORMAT="+%Y-%m-%d %H:%M:%S"
SCRIPT_LOG_LEVEL_INFO='INFO'
SCRIPT_LOG_PATTERN="${SCRIPT_LOG_NAME} $(date "${SCRIPT_LOG_DATETIME_FORMAT}") \$1 : \$2"
log_general() {
eval echo "${SCRIPT_LOG_PATTERN}"
}
log_info() {
log_general "${SCRIPT_LOG_LEVEL_INFO}" "${1}"
}
Usage:
$ source logging_test.sh
$ log_info "my custom message"
[MYSCRIPT] 2023-06-02 14:03:27 INFO : my custom message
I'd also recommend escaping the date command since otherwise the date will be parsed once, here is what I mean:
$ log_info "asdads"; sleep 5; log_info "asdsad"
[MYSCRIPT] 2023-06-02 14:06:28 INFO : asdads
[MYSCRIPT] 2023-06-02 14:06:28 INFO : asdsad
As you can see the time does not change even with 5 seconds of sleep.
To fix this escape the date as well like this:
SCRIPT_LOG_PATTERN="${SCRIPT_LOG_NAME} \$(date '${SCRIPT_LOG_DATETIME_FORMAT}') \$1 : \$2"
Output now:
$ log_info "asdads"; sleep 5; log_info "asdsad"
[MYSCRIPT] 2023-06-02 14:09:19 INFO : asdads
[MYSCRIPT] 2023-06-02 14:09:25 INFO : asdsad
|
76388237 | 76388580 | There are some situations where it's better to keep a hidden component in DOM. In Vue there the v-show in addition to the v-if. But in Angular I didn't find an equivalent? So the best solution is to use s.th. like [ngStyle]="{ 'display': showMe ? 'block' : 'none' }"?
EDIT: I also could set the hidden attribute, which should have a very similar effect, e.g. [hidden]="!showMe".
Is there actually a reason why Vue.js did include v-show instead of simply using :hidden?
| Is there an equivalent of Vue's `v-show` in Angular so that the component is hidden, but still in DOM? | v-show is simply sugar syntax for adding style="display: none". While I'm not aware of anything like that built into angular, it's trivial to build your own directive that will achieve the same result (code not tested):
@Directive({
selector: 'appHidden',
})
class HiddenDirective {
@Input('appHidden')
isHidden: boolean = false;
@HostBinding('style.display')
get displayStyle() {
return this.isHidden ? 'none' : undefined;
}
}
Usage:
<div [appHidden]="shouldBeHidden"></div>
|
76390978 | 76391418 | I want to add 2 values for my custom constraint validator because I have 2 feature flags:
@JsonProperty(value = "name")
@BlockedWithoutEnabledFeatureFlag(feature = FeatureFlag.AAA, values = {"aaa", "bbb"})
@BlockedWithoutEnabledFeatureFlag(feature = FeatureFlag.BBB, values = {"ccc", "ddd"})
private String parameter;
where:
@Constraint(validatedBy = {BlockedWithoutEnabledFeatureFlagValidator.class})
@Target({FIELD, PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@ReportAsSingleViolation
public @interface BlockedWithoutEnabledFeatureFlag {
String message() default "{validation.constraints.BlockedWithoutEnabledFeatureFlag.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
FeatureFlag feature();
String[] values() default {};
}
and implementation:
public class BlockedWithoutEnabledFeatureFlagValidator implements ConstraintValidator<BlockedWithoutEnabledFeatureFlag, Object> {
private final FeatureFlagService featureFlagService;
private List<String> blocked;
private FeatureFlag feature;
@Override
public void initialize(BlockedWithoutEnabledFeatureFlag constraintAnnotation) {
blocked = Arrays.asList(constraintAnnotation.values());
feature = constraintAnnotation.feature();
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
But now I get compilation error "Duplicate annotation". How to do that?
| Spring Boot custom constraint validator with multiple values | You should make your BlockedWithoutEnabledFeatureFlag repeatable. To do this:
Create a new "top-level" annotation:
@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface RepeatableBlockedWithoutEnabledFeatureFlag {
BlockedWithoutEnabledFeatureFlag[] value();
}
Add @Repeatable to your BlockedWithoutEnabledFeatureFlag annotation
...
@Repeatable(RepeatableBlockedWithoutEnabledFeatureFlag.class)
public @interface BlockedWithoutEnabledFeatureFlag {
...
Then you should be able to add more than one @BlockedWithoutEnabledFeatureFlag annotation.
|
76388242 | 76388621 | Even though there's multiple similar questions here on StackOverflow, I haven't been able to solve this, please bear with me:
In an Angular 16 application I have a functionality to batch rename hundreds of users. Thus, I have an array of RenameUser objects, each one having an async method .executeRename() performing an API call to rename a user. To not overwhelm the API, these should be triggered with a 200ms delay between them. Once all users have been renamed, I would like to run other tasks.
Summarized: Trigger a bunch of async operations with a 200ms delay between them, do something when all are complete.
I have managed to delay the calls, and I do not care how long a single call takes to finish, but I need to know when all tasks have finished.
This is the solution I came up with, I would run the triggerRenameProcess() method to start the process.
async triggerRenameProcess(users: RenameUser[]) {
try {
await this.renameUsersWithDelay(users, 200);
console.log('All users renamed');
} catch (error) {
console.error('Exception while renaming users: ', error);
}
}
renameUsersWithDelay(users: RenameUser[], delay: number): Promise<void> {
return new Promise<void>((resolve) => {
let currentIndex = 0;
const executeNext = () => {
if (currentIndex < users.length) {
const user = users[currentIndex];
user.executeRename().then(() => {
currentIndex++;
setTimeout(executeNext, delay);
});
} else {
resolve();
}
};
});
}
I kind of understand what the problem is, the renameUsersWithDelay() returns a Promise that can be awaited, but that will happen once all requests have been triggered - it is not waiting for the longest running one to complete. I can make it wait for every single one and run them sequentially, but that's not what it is supposed to do...
I did some research and found this question or this one, but they seem not to address the same issue - and frankly, I am not too familiar with JavaScript - I feel more at home in .NET where I just would use something like .WaitAll() (and probably use a more sophisticated throttling pattern), but I'm not sure how to achieve the same thing in TypeScript.
| Typescript/Angular: Wait for sequentially delayed async tasks to be completed | Whenever you've got an asynchronous data flow manipulation that isn't trivial, you can assume that observables will help you a lot.
Here's the feature you're trying to achieve with observables:
function renameUsersWithDelay(
users: RenameUser[],
delayMs: number = 200
): Observable<any> {
const usersWithDelay = users.map((user, i) =>
of(user).pipe(delay(delayMs * i), switchMap(executeRename))
);
return forkJoin(usersWithDelay);
}
Here's how it works:
we loop on the users array with a map to create a new array out of it
for each user, we put the user into an observable using of
we then apply a delay relative to the index we're at so they're all shifted
once the delay resolves, we use a switchMap to make make the http call, which will effectively subscribe to the observable returned by executeRename
because observables are cold by nature, nothing that we just created here is triggered yet. Which is fantastic because it lets you build up all your instructions without triggering them straight away
finally, we use forkJoin to subscribe to each observables that we just created
I've created a live demo with mocked data so you can see it behaves as expected.
I wanted to give you exactly what you asked for, which is what I did so far. But my advice would be to go for a different approach where you still don't DDOS your backend while being more efficient, by having a limited pool of running calls. For example you could say, up until there's nothing left to proceed, I want to have 3 ongoing rename calls and as soon as 1 finishes in that current pool, another one is taken from the queue and ran straight away. This is IMO more efficient.
Here's how you could implemented this:
const renameUsersWithDelay = (users: RenameUser[]): Observable<any> =>
from(users.map((user) => of(user).pipe(switchMap(executeRename)))).pipe(
mergeAll(3)
);
Live demo
|
76389697 | 76390000 | I am trying to scan a text from an Ocr and clean it, I got a character that is divided to few lines, however I would like to have the text in similar to the way it is in the image
the code :
heraclitus<-"greek.png"
library(tidyverse)
library(tesseract)
library(magick)
image_greek<-image_read(heraclitus)
image_greek<-image_greek %>% image_scale("600") %>%
image_crop("600x400+220+150") %>%
image_convert(type = 'Grayscale') %>%
image_contrast(sharpen = 1) %>%
image_write(format="jpg")
heraclitus_sentences<-magick::image_read(image_greek)%>%
ocr() %>% str_split("\n")
As you can see from the output, I have white spaces and sentences that are divided to two lines. I would like to have it in a vector or a list, that each element will be a sentence
| clean data in r from image | You need to split on \n\n (not \n) then replace the middle \n values:
magick::image_read(image_greek) %>%
ocr() %>%
str_split("\n\n") %>%
unlist() %>%
str_replace_all("\n", " ")
Output:
[1] "© Much learning does not teach understanding."
[2] "© The road up and the road down is one and the same."
[3] "© Our envy always lasts longer than the happiness of those we envy."
[4] "© No man ever steps in the same river twice, for it's not the same river and he's not the same man. "
|
76388633 | 76388649 | In VB.NET i would like to create a list of string from the values of two given lists of string.
E.g.
Dim varNames As New List(Of String)({"var1", "var2"})
Dim varValues As New List(Of String)({"value1", "value2"})
Dim finalList As List(Of String) = .....
'Output should be:
'finalList(0) -> "[var1] = 'value1'"
'finalList(1) -> "[var2] = 'value2'"
I would like to do this in on line of code using LINQ. (I know how to do this using for loops)
| Join values of two string lists to new string list and add characters in VB.NET using LINQ | Use Zip to "concat" two lists via index:
Dim finalList As List(Of String) = varNames.
Zip(varValues, Function(s1, s2) $"[{s1}] = '{s2}'").
ToList()
|
76388555 | 76388668 | I'm trying desing and implement database model in python from a json file but my python code seems like is not inserting data into table and i'm not sure where is the problem in my code
import json
import psycopg2
class Policy:
def __init__(self, type, name, rule_exists):
self.type = type
self.name = name
self.rule_exists = rule_exists
# load json data from the file
with open("demo_data.json", 'r') as file:
policy_data = json.load(file)
first_level = policy_data["uniconfig-topology:configuration"]
second_level = first_level["Cisco-IOS-XR-infra-policymgr-cfg:policy-manager"]
third_level = second_level["policy-maps"]
forth_level = third_level["policy-map"]
table_of_policies = []
for item in forth_level:
if "policy-map" in item:
# forth_level = item
type = forth_level['type']
name = forth_level['name']
rule_exists = 'policy-map-rule' in forth_level
policy_map = Policy(type, name, rule_exists)
table_of_policies.append(policy_map)
#print(forth_level)
conn = psycopg2.connect(
host="localhost",
database="postgres",
user="postgres",
password="postgres",
port="5432"
)
cursor = conn.cursor()
cursor.execute("DROP TABLE IF EXISTS policy_map")
cursor.execute('''create table policy_map
( type VARCHAR(255),
name VARCHAR(255),
rule_exists BOOLEAN)
''')
for policy_map in table_of_policies:
insert_data = "INSERT INTO policy_map (type, name, rule_exists) VALUES (%s, %s, %s)"
cursor.execute(insert_data, (policy_map.type,
policy_map.name, policy_map.rule_exists))
conn.commit()
I tried several different approach for dict in json file to be sure im on right level of dict but it never append any data to my list. Would like to know whats wrong with my code
| Why is my Python code not inserting data into PostgreSQL database from a JSON file? | type is a built-in python function that returns the type of a variable. Overwriting it might cause your code to work unexpectedly.
You can check the documentation , avoid using build-in function names for variables.
Regarding table column naming you can refer to this question.
Apart from these you're looping over forth_level but not using the item:
type = forth_level['type']
name = forth_level['name']
I would expect this code to continue like:
if "policy-map" in item:
type = item['type']
name = item['name']
rule_exists = 'policy-map-rule' in item
policy_map = Policy(type, name, rule_exists)
table_of_policies.append(policy_map)
But without seeing the JSON I cannot tell for sure.
|
76391208 | 76391517 | this is my [tag:doctor.write_medical.blade.php]. i try to get patient name from patient database that i created in migration file and fill in some form so that i can save the medical records with patient_id as foreign key. but when i try to open the page, it shows Undefined variable $patients. i dont know why it become like this it shows error at
@foreach($patients as $patient)
<!DOCTYPE html>
<html lang="en">
<head>
@include('doctor.css')
</head>
<body>
<header>
<div class="topbar">
<div class="container">
<div class="row">
<div class="col-sm-8 text-sm">
<div class="site-info">
<a href="#"><span class="mai-call text-primary"></span> 0105739057</a>
<span class="divider">|</span>
<a href="#"><span class="mai-mail text-primary"></span> afiqaqil@gmail.com</a>
</div>
</div>
<div class="col-sm-4 text-right text-sm">
<div class="social-mini-button">
<a href="#"><span class="mai-logo-facebook-f"></span></a>
<a href="#"><span class="mai-logo-twitter"></span></a>
<a href="#"><span class="mai-logo-dribbble"></span></a>
<a href="#"><span class="mai-logo-instagram"></span></a>
</div>
</div>
</div> <!-- .row -->
</div> <!-- .container -->
</div> <!-- .topbar -->
<nav class="navbar navbar-expand-lg navbar-light shadow-sm">
<div class="container">
<a class="navbar-brand" href="#"><span class="text-primary">MyHealthCare</span>System</a>
<div class="collapse navbar-collapse" id="navbarSupport">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="#">Request Access</a>
</li>
<li class="nav-item active">
<a class="nav-link" href="index.html">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="about.html">About Us</a>
</li>
<li class="nav-item">
<a class="nav-link" href="contact.html">Contact</a>
</li>
@if(Route::has('login'))
@auth
<x-app-layout>
</x-app-layout>
@else
<li class="nav-item">
<a class="btn btn-primary ml-lg-3" href="{{route('login')}}">Login</a>
</li>
<li class="nav-item">
<a class="btn btn-primary ml-lg-3" href="{{route('register')}}">Register</a>
</li>
@endauth
@endif
</ul>
</div> <!-- .navbar-collapse -->
</div> <!-- .container -->
</nav>
</header>
<div class="container-fluid page-body-wrapper">
<div class="row">
<div class="col-md-2">
<div class="sidebar-sticky">
<ul class="nav flex-column">
<li class="nav-item active">
<a class="nav-link" href="{{route('doctor.home')}}">
<i class="mdi mdi-account-search"></i>
Add Patient
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ route('write_medical') }}">
<i class="mdi mdi-download"></i>
Write Medical Description
</a>
</li>
<li class="nav-item menu-items">
<a class="nav-link" data-toggle="collapse" href="#doctors" aria-expanded="false" aria-controls="doctors">
<span class="menu-icon">
<i class="mdi mdi-doctor"></i>
</span>
<span class="menu-title">View Patients</span>
<i class="menu-arrow"></i>
</a>
<div class="collapse" id="doctors">
<ul class="nav flex-column sub-menu">
<li class="nav-item">
<a class="nav-link" href="{{ route('patient_1') }}">Patient 1</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ route('add_doctor_view') }}">Patient 2</a>
</li>
</ul>
</div>
</li>
<li class="nav-item">
<a class="nav-link" href="#">
<i class="mdi mdi-chat"></i>
Chat with Patients
</a>
</li>
</ul>
</div>
</div>
<div class="col-md-10">
<div class="content-wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="form-container">
@if (session('success'))
<div class="alert alert-success">
{{ session('success') }}
</div>
@endif
<form action="{{ route('save_medical') }}" method="POST">
@csrf
<div class="form-group">
<label for="patient">Patient</label>
<select class="form-control" id="patients" name="patients" required>
@foreach($patients as $patient)
<option value="{{ $patient->patient_id }}">{{ $patient->patient_name }}</option>
@endforeach
</select>
</div>
<div class="form-group">
<label for="date">Date</label>
<input type="text" class="form-control" id="date" value="{{ date('Y-m-d') }}" readonly>
</div>
<div class="form-group">
<label for="symptoms">Symptoms</label>
<textarea class="form-control" id="symptoms" name="symptoms" rows="4" required></textarea>
</div>
<div class="form-group">
<label for="treatment">Simplified Treatment</label>
<textarea class="form-control" id="treatment" name="treatment" rows="4" required></textarea>
</div>
<div class="form-group">
<label for="medication">Medication</label>
<textarea class="form-control" id="medication" name="medication" rows="4" required></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<footer class="page-footer">
<div class="container">
<div class="row px-md-3">
<div class="col-sm-6 col-lg-3 py-3">
<h5>Company</h5>
<ul class="footer-menu">
<li><a href="#">About Us</a></li>
<li><a href="#">Career</a></li>
<li><a href="#">Editorial Team</a></li>
<li><a href="#">Protection</a></li>
</ul>
</div>
<div class="col-sm-6 col-lg-3 py-3">
<h5>More</h5>
<ul class="footer-menu">
<li><a href="#">Terms & Condition</a></li>
<li><a href="#">Privacy</a></li>
<li><a href="#">Advertise</a></li>
<li><a href="#">Join as Doctors</a></li>
</ul>
</div>
<div class="col-sm-6 col-lg-3 py-3">
<h5>Our partner</h5>
<ul class="footer-menu">
<li><a href="#">One-Fitness</a></li>
<li><a href="#">One-Drugs</a></li>
<li><a href="#">One-Live</a></li>
</ul>
</div>
<div class="col-sm-6 col-lg-3 py-3">
<h5>Contact</h5>
<p class="footer-link mt-2">351 Willow Street Franklin, MA 02038</p>
<a href="#" class="footer-link">701-573-7582</a>
<a href="#" class="footer-link">healthcare@temporary.net</a>
<h5 class="mt-3">Social Media</h5>
<div class="footer-sosmed mt-3">
<a href="#" target="_blank"><span class="mai-logo-facebook-f"></span></a>
<a href="#" target="_blank"><span class="mai-logo-twitter"></span></a>
<a href="#" target="_blank"><span class="mai-logo-google-plus-g"></span></a>
<a href="#" target="_blank"><span class="mai-logo-instagram"></span></a>
<a href="#" target="_blank"><span class="mai-logo-linkedin"></span></a>
</div>
</div>
</div>
<hr>
<p id="copyright">Copyright © 2020 <a href="https://macodeid.com/" target="_blank">MACode ID</a>. All right reserved</p>
</div>
</footer>
@include('doctor.script')
</body>
</html>
this is my route web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\AdminController;
use App\Http\Controllers\RegisterController;
use App\Http\Controllers\Admin\DataRequestorController;
use App\Http\Controllers\DoctorController;
use App\Http\Controllers\PatientController;
use App\Http\Controllers\AccessRequestController;
use App\Http\Controllers\WriteMedicalController;
Route::get('access-request/create', [AccessRequestController::class, 'create'])->name('access-request.create');
Route::post('access-request', [AccessRequestController::class, 'store'])->name('access-request.store');
Route::get('/get-doctors-count', [DoctorController::class, 'getDoctorsCount'])->name('get_doctors_count');
Route::post('/add-patient', [PatientController::class, 'addPatient'])->name('add.patient');
Route::get('/write-medical', [WriteMedicalController::class, 'writeMedical'])->name('write_medical');
Route::post('/save-medical', [WriteMedicalController::class, 'saveMedical'])->name('save_medical');
Route::get('/admin/data-requestors/{requestor}/accept', [DataRequestorController::class, 'accept'])->name('admin.data-requestors.accept');
Route::get('/admin/data-requestors/{requestor}/decline', [DataRequestorController::class, 'decline'])->name('admin.data-requestors.decline');
Route::get('/admin/data-requestors/{requestor}', [DataRequestorController::class, 'show'])->name('admin.data-requestors.show');
Route::get('/admin/data-requestors', [DataRequestorController::class, 'index'])->name('admin.data-requestors.index');
Route::get('/', [HomeController::class, 'index']);
Route::get('/home', [HomeController::class, 'redirect'])->name('home.redirect');
Route::get('/doctor/home', [HomeController::class, 'doctorHome'])->name('doctor.home');
Route::get('/user/home', [HomeController::class, 'userHome'])->name('user.home');
Route::middleware([
'auth:sanctum',
config('jetstream.auth_session'),
'verified'
])->group(function () {
Route::get('/dashboard', function () {
return view('dashboard');
})->name('dashboard');
});
Route::get('/write-medical', function () {
return view('doctor.write_medical');
})->name('write_medical');
Route::get('/patient_1', function () {
return view('doctor.patient_1');
})->name('patient_1');
Route::get('/add_doctor_view', [AdminController::class, 'addview'])->name('add_doctor_view');
Route::post('/register_doctor', [AdminController::class, 'registerDoctor'])->name('register.doctor');
Route::get('/viewDoctors', [AdminController::class, 'viewDoctors'])->name('viewDoctors');
Route::delete('/delete_doctor/{doctor}', [AdminController::class, 'deleteDoctor'])->name('admin.doctors.delete');
and this is my writemedicalcontroller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\MedicalDescription;
use App\Models\Patient;
use App\Models\Doctor;
class WriteMedicalController extends Controller
{
public function writeMedical()
{
$patients = Patient::all();
return view('doctor.write_medical', compact('patients'));
}
public function saveMedical(Request $request)
{
$validatedData = $request->validate([
'patient' => 'required|exists:patients,patient_id',
'symptoms' => 'required',
'treatment' => 'required',
'medication' => 'required',
]);
$medicalDescription = new MedicalDescription();
$medicalDescription->patient_id = $validatedData['patient'];
$medicalDescription->date = date('Y-m-d');
$medicalDescription->symptoms = $validatedData['symptoms'];
$medicalDescription->treatment = $validatedData['treatment'];
$medicalDescription->medication = $validatedData['medication'];
$medicalDescription->save();
return redirect()->back()->with('success', 'Medical description saved successfully.');
}
}
this is my medicaldescription model
| Undefined variable $patients | Your route web.php file has two definitions of the route /write-medical, so Laravel is using the last definition:
Route::get('/write-medical', function () {
return view('doctor.write_medical');
})->name('write_medical');
Remove that and I think it will work as you expect because your first definition is calling the controller WriteMedicalController::writeMedical as you expect.
|
76388273 | 76388683 | I am new to Karate framework and have written the following working code to run few sample API tests.
Feature: Sample API Tests
Background:
* def request_headers = {apikey: "#(apikey)", Content-Type: 'application/json'}
* configure headers = request_headers
Scenario: Create Customer
* def requestPayload = read('classpath:payload/customerdetails.json')
* def RandomDataGenerator = Java.type('utils.RandomDataGenerator')
Given url testurl+'/customers'
And request requestPayload
* requestPayload.firstName = RandomDataGenerator.generateRandomFirstName()
* requestPayload.lastName = RandomDataGenerator.generateRandomLastName()
* requestPayload.mobileNumber = RandomDataGenerator.generateRandomMobileNumber()
* requestPayload.emailAddress = RandomDataGenerator.generateRandomEmailAddress()
When method post
Then status 200
And def customerId = response.id
# Create An Account for the customer
* def createAccountPayload = read('classpath:payload/accountdetails.json')
Given url testurl+'/accounts/createCreditAccount'
And request createAccountPayload
* createAccountPayload.customerId = customerId
When method post
Then status 200
And def accountId = response.id
# Perform a Transaction
* def debitTransactionPayload = read('classpath:payload/transaction.json')
Given url testurl+'/accounts/createDebitTransaction'
And request debitTransactionPayload
* debitTransactionPayload.accountId = accountId
When method post
Then status 200
Now I want to run a test where I would:
Create 100 customers (and in turn 100 accounts).
Do 500 transactions (5 transactions each for a given customer).
How do I achieve this?
I tried using repeat and looping options, but I believe I am missing something basic. Can someone please help ?
| Repeating and looping API calls in Karate framework | Here is a Karate test that uses a JS function as a data-source to create 10 JSON payloads. You should be easily able to modify this to do what you want:
Feature:
@setup
Scenario:
* def generator =
"""
function(i){
if (i == 10) return null;
return { name: `cat${i}`, age: i };
}
"""
Scenario Outline:
* print __row
Examples:
| karate.setup().generator |
How this works is explained here: https://github.com/karatelabs/karate#json-function-data-source
Also refer: https://stackoverflow.com/a/75394445/143475
|
76389982 | 76390015 | I'm encountering an issue when making a POST request to the /api/notes/addnote endpoint. The server responds with a 404 Not Found error. I have checked the server-side code and verified that the endpoint is correctly defined. Here are the details of my setup:
Server-side:
Framework/Language: Express.js
Code snippet handling the /api/notes/addnote endpoint:
router.post('/addnote', fetchUser, [
body('tittle', 'Tittle cannot be blank').exists(),
body('description', 'Description must be atleast 5 characters').isLength({ min: 5 })
], async (req, res) => {
// If there are any errors in the validation of an express request, return status 400 and the errors
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
// Creating a new note in the database and saving it
const { tittle, description, tag } = req.body;
const note = await Notes.create({
tittle,
description,
tag,
user: req.id
});
// Sending the note as a response
res.json(note);
});
module.exports = router;
main.js file code:
const connectToMongo = require('./Db');
const express = require('express');
connectToMongo();
const app = express()
const port = 3000
app.use(express.json());
app.use('/api/notes/addnote', require('./Routes/notes'));
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
Client-side:
Code snippet for making the POST request:
The server is running and accessible at localhost:3000
I have successfully tested other endpoints on the same server, and they are working correctly.
I have confirmed the URL for the POST request: http://localhost:3000/api/notes/addnote.
I have already attempted the following troubleshooting steps:
Double-checked the server-side code and endpoint spelling.
Tested the POST request using different HTTP clients (e.g., Postman) with the same result.
Reviewed the server logs for any error messages related to the /api/notes/addnote endpoint.
Despite these efforts, I'm still receiving a 404 Not Found error. Any guidance or suggestions on how to resolve this issue would be greatly appreciated. Thank you!
| POST request to /api/notes/addnote endpoint returning 404 Not Found error | The URL while setting the Router to the appliction is the same as you have mentioned.
app.use('/api/notes', require('./Routes/notes'));
The problem here is:
app.use('/api/notes/addnote', require('./Routes/notes'));
router.post('/addnote');
Now the route works for /api/notes/addnote/addnote.
|
76389927 | 76390042 | I want to ask for the SEND_SMS and READ_SMS runtime permissions, if they are not given. This is my code:
private ActivityResultLauncher<String[]> mRequestPermissionsLauncher;
String[] PERMISSIONS = {
Manifest.permission.SEND_SMS,
Manifest.permission.READ_SMS
};
@Override
protected void onCreate(Bundle savedInstanceState) {
mRequestPermissionsLauncher = registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), result -> {
Log.d("DEBUG",result.toString());
});
if (!hasPermissions(this, PERMISSIONS)) {
if(shouldShowRequestPermissionRationale(Manifest.permission.SEND_SMS) || shouldShowRequestPermissionRationale(Manifest.permission.READ_SMS)){
new AlertDialog.Builder(this)
.setTitle("Permission Needed")
.setMessage("Please press OK to allow the permissions")
.setCancelable(false)
.setPositiveButton("OK", (dialog, which) -> mRequestPermissionsLauncher.launch(PERMISSIONS)).create().show();
}
else{
mRequestPermissionsLauncher.launch(PERMISSIONS);
}
}
}
public static boolean hasPermissions(Context context, String... permissions) {
if (context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
After I allow the permissions and debug the result, it keeps showing:
{android.permission.SEND_SMS=true, android.permission.READ_SMS=false}
Why is my READ_SMS permission false?
EDIT: Never mind, the issue is resolved. I forgot to declare the READ_SMS permission in the manifest file. Silly me :p
| Android RequestMultiplePermissions(): one of the permission's status is never true, even after allowing it | You can't and that's by design - to prevent abuse.
You're better of following the official guidelines.
The only way to request permissions again, is to navigate the user to app info, where the user has to manually allow it:
fun launchPermissionSettings(context: Context) {
Intent().apply {
action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
data = Uri.fromParts("package", context.packageName, null)
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)
addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS)
context.startActivity(this)
}
}
static void launchPermissionSettings(Context context) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.fromParts("package", context.getPackageName(), null));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
context.startActivity(intent);
}
You're also using a deprecated way of requesting permissions. Consider using ActivityResultContracts.RequestMultiplePermissions():
class MyFragment: Fragment() {
private lateinit var mRequestPermissionsLauncher: ActivityResultLauncher<Array<String>>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mRequestPermissionsLauncher = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { result: Map<String, Boolean> ->
//Handle result here
}
//Request permissions like this:
mRequestPermissionsLauncher.launch(arrayOf(
Manifest.permission.SEND_SMS,
Manifest.permission.READ_SMS,
))
}
}
class MyFragment extends Fragment {
private ActivityResultLauncher<String[]> mRequestPermissionsLauncher;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mRequestPermissionsLauncher = registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), result -> {
//Handle activity result here
});
//Request permissions like this:
String[] PERMISSIONS = {
Manifest.permission.SEND_SMS,
Manifest.permission.READ_SMS,
};
mRequestPermissionsLauncher.launch(PERMISSIONS);
}
}
|
76390997 | 76391529 | I am trying to submit a message to a Azure Service Bus Topic and it keeps complaining about
MassTransit.ConfigurationException: The message type Contracts.ClassName entity name was already evaluated: Contracts/ClassName
I have checked my registration and can't seem to figure out what is missing?
Here is my code for submitting a message to a Topic
var bus = Bus.Factory.CreateUsingAzureServiceBus(cfg =>
{
cfg.Message<ClassName>(x =>
{
x.SetEntityName("topicName");
});
});
try
{
await bus.Publish(new ClassName
{
Status = status,
User = user,
});
_logger.LogInformation($"Topic Message Sent Successfully.");
}
catch (Exception ex)
{
_logger.LogError($"Failed to Send Message!\n{ex.Message} to Topic");
}
Registration
services.AddMassTransit(x =>
{
x.AddConsumer<TestConsumer>();
x.UsingAzureServiceBus((ctx, cfg) =>
{
cfg.ClearMessageDeserializers();
cfg.UseRawJsonSerializer();
cfg.Host(_busConfiguration.ServiceBus.ConnectionString);
cfg.ReceiveEndpoint(_busConfiguration.ServiceBus.QueueName, ec =>
{
ec.ConfigureConsumeTopology = false;
ctx.ConfigureConsumer<TestConsumer>(ec);
});
});
});
| Not able to submit message to Azure service bus Topic using MassTransit | You should configure everything at once, the separate bus configuration is a really bad idea.
services.AddMassTransit(x =>
{
x.AddConsumer<TestConsumer>();
x.UsingAzureServiceBus((ctx, cfg) =>
{
cfg.Message<ClassName>(x =>
{
x.SetEntityName("topicName");
});
cfg.UseRawJsonSerializer(isDefault: true);
cfg.Host(_busConfiguration.ServiceBus.ConnectionString);
cfg.ReceiveEndpoint(_busConfiguration.ServiceBus.QueueName, ec =>
{
ec.ConfigureConsumeTopology = false;
ec.ConfigureConsumer<TestConsumer>(ctx);
});
});
});
|
76389933 | 76390050 | I would like to money patch a function without the requirement to initialize using pd.DataFrame.function = function
For example, if I have a dataframe df and I call df.unique() I do not have to run pd.DataFrame.unique = unique prior to running as this appears to be built in. Is there a way I can do the same for my own functions without the need to initialise every time?
| monkey patch without the need to intitalise | Patching an existing class, e.g. pd.DataFrame, so that all instances have a patched method is not trivial, IMO.
What about simply subclassing pd.DataFrame?
import pandas as pd
class MyDataFrame(pd.DataFrame):
def my_func(self):
print("yey")
df = MyDataFrame()
df.my_func()
# Outputs:
# yey
|
76388645 | 76388706 | I have the below code that populates a selectListItem with information from my database.
I am trying to sort this by name rather than by ID like how it is in the database.
I tried adding Vendors.OrderBy(x => x.VendorName); but it didn't seem to do anything at all, not sure if I have it in the wrong place or something.
public IList<Data.Vendor> Vendors { get; set; }
public void OnGet()
{
List<SelectListItem> test = new List<SelectListItem>();
Vendors = _context.Vendors.ToList();
foreach (var item in Vendors)
//foreach item In the vendors list
{
test.Add(new SelectListItem { Text = item.VendorName, Value = item.Id.ToString() });
//Add the current item i3n the loop to the selectListItem
}
ViewData["demo"] = test;
Vendors.OrderBy(x => x.VendorName);
}
This is the front end code:
@page
@model PurchaseOrdersModel
@{
ViewData["Title"] = "Home page";
}
<style>
body {
background-image: url("http://10.48.1.215/PORTAL/hero-range-1.jpg");
height: 100%;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
#myInput {
/*background-image: url('/css/searchicon.png'); /* Add a search icon to input */
/* background-position: 10px 12px; /* Position the search icon */
/* background-repeat: no-repeat; /* Do not repeat the icon image **/
width: 100%; /* Full-width */
font-size: 16px; /* Increase font-size */
/*padding: 12px 20px 12px 40px; /* Add some padding */
border: 1px solid #ddd; /* Add a grey border */
margin-bottom: 12px; /* Add some space below the input */
}
</style>
@*
<select asp-for="Files.VendorId.Value" asp-items="@((List<SelectListItem>)ViewData["demo"])"></select>*@
<h1 style="color: white">Purchase Orders</h1>
<p>
<a asp-page="Create" style="color:white">Create File</a>
</p>
<div class="row">
<div class="col-sm-12">
<div class="form-check-inline pull-right">
<label style="color:white">Search</label>
<input type="text" class="form-control" id="myInput" placeholder="Search Purchase Orders..." onkeyup="myFunction()" />
</div>
<select asp-items="@((List<SelectListItem>)ViewData["test"])" id="vendor" onchange="myFunctionThree()">
<option value="" disabled selected>Select a Vendor</option>
</select>
<input class="btn btn-light" value="Clear All Filters" onclick="history.go(0)" style="float: right">
<table class="table" style="background-color: white" id="myTable">
<thead>
<tr class="header">
<th>
PO No.
</th>
@* <th>
@Html.DisplayNameFor(model => model.Files[0].Date)
</th>
<th>
@Html.DisplayNameFor(model => model.Files[0].Value)
</th>*@
<th>
Haulier
</th>
<th>
Comments
</th>
<th>
Vendor
</th>
<th>
Upload
</th>
<th>
Date Uploaded
</th>
<th>Download</th>
<th>Delete Attachment</th>
<th>Notify</th>
<th>Sent</th>
<th>
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.Files)
{
if (item.FileType == "Purchase Order")
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Number)
</td>
@*<td>
@Html.DisplayFor(modelItem => item.FileType)
</td>*@
<td>
@Html.DisplayFor(modelItem => item.Haulier)
</td>
<td>
@Html.DisplayFor(modelItem => item.Comments)
</td>
<td>
@Html.DisplayFor(modeItem => item.Vendor.VendorName)
</td>
<td>
<a asp-page="Upload" asp-route-id="@item.Id">Upload File Attachment</a>
</td>
<td>
@Html.DisplayFor(modelItem => item.UploadDate)
</td>
<td>
@if (item.Attachment != null)
{
<form asp-page-handler="Download" method="post" asp-route-id="@item.Id">
<input type="submit" class="btn btn-dark" value="Download">
</form>
}
</td>
<td>
@if (item.Attachment != null)
{
<form asp-page-handler="Delete" method="post" asp-route-id="@item.Id">
<input type="submit" class="btn btn-danger" value="Delete Attachment">
</form>
}
</td>
<td>
@if (item.Attachment != null)
{
<form asp-page-handler="Email" method="post" asp-route-id="@item.Id">
<input type="submit" class="btn btn-danger" value="Notify Vendor">
</form>
}
</td>
<td>
@Html.DisplayFor(modelItem => item.EmailSent)
</td>
<td>
<a asp-page="/Admin/Details" asp-route-id="@item.Id">Details</a>
</td>
</tr>
}
}
</tbody>
</table>
</div>
</div>
<script>
//function for search bar
function myFunction() {
// Declare variables
var input, filter, table, tr, td, i, txtValue, dropdownValue, dropdownInput, dtd;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
dropdownInput = document.getElementById("vendor");
dropdownValue = dropdownInput.value.toUpperCase();
// Loop through all table rows, and hide those who don't match the search query
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
dtd = tr[i].getElementsByTagName("td")[3];
if (td) {
txtValue = td.textContent || td.innerText;
dropTxtValue = dtd.textContent || dtd.innerText;
if(dropdownValue == ""){
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
else{
if((txtValue.toUpperCase().indexOf(filter) > -1) && (dropTxtValue.toUpperCase().indexOf(dropdownValue) > -1)){
tr[i].style.display = "";
}else{
tr[i].style.display = "none";
}
}
}
}
}
//function for dropdown menu
function myFunctionThree()
{
// Declare variables
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("vendor");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
// Loop through all table rows, and hide those who don't match the search query
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[3];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
</script>
I want to sort it A-Z by Vendor Name instead of by the Vendor ID.
| Trying to sort a selectListItem alphabetically not by ID | OrderBy creates IEnumerable that "executes" when used in foreach or when .ToList() is invoked. Try this:
Vendors = _context.Vendors.OrderBy(x => x.VendorName).ToList();
|
76390761 | 76391534 | I'm trying to pass a value (year_value) from a parent component to a child component using services, whenever there is a change in the value (dropdown selection). Also I'm using Angular routing (<router-outlet>) for navigation to child component, since I will be adding more charts later which are separate components.
app.component.html
<mat-toolbar class="toolbar2">
<div>
<button mat-button (click)="getChartType('bar')" [routerLink]="'/bar-chart'" matTooltip="Bar Chart">
<img src="assets/images/column.svg">
</button>
</div>
<div>
<mat-form-field>
<mat-label>Select year</mat-label>
<mat-select placeholder="{{initialValue}}" (selectionChange)="selectByYear($event)"
[(ngModel)]="year_value">
<mat-option *ngFor="let year of years" [value]="year.value">
{{year.viewValue}}
</mat-option>
</mat-select>
</mat-form-field>
</div>
</mat-toolbar>
<mat-divider></mat-divider>
<div class="container-fluid">
<div class="col1"></div>
<div class="col2">
<div class="col2-row1 charts-area">
<router-outlet>
<div class="card" id="container"></div>
</router-outlet>
</div>
<div class="col2-row2"></div>
</div>
</div>
<mat-select> is the dropdown and when selecting a value, the selectByYear updates the year property.
app.component.ts
export class AppComponent implements OnInit {
constructor(private commonActions: CommonActionsService) {}
beData = this.commonActions.getData();
canvas: any;
ctx: any;
header: any;
xValues: string[] = [];
dataValues: any[] = [];
yValues: number[] = [];
year: string = '';
initialValue: any;
year_value;
years: any[] = [];
bgColors: string[] = [];
buttons = ['Status', 'Auditor', 'ISOScheme'];
numbers = ['Audits'];
chart_yfield: string[] = [];
chart_xfield: string[] = [];
chartType;
activity: any;
xData: any;
label: any;
options: any;
currentYear: any;
ngOnInit() {
this.selectYear();
this.year_value = 2022;
this.chart_xfield.push('Status');
this.chart_yfield.push('Audits');
const index: number = this.buttons.indexOf('Status');
if (index !== -1) {
this.buttons.splice(index, 1);
}
this.numbers = []
this.header = this.chart_xfield[0]
this.getChartType('bar');
}
selectYear() {
this.currentYear = 2022;
let earliestYear = this.currentYear - 5;
while (this.currentYear >= earliestYear) {
let dateOption = {
"viewValue": this.currentYear + ' ' + '-' + ' ' + (this.currentYear + 1),
"value": this.currentYear
};
this.years.push(dateOption);
this.currentYear -= 1;
}
this.initialValue = this.years[0].viewValue;
this.selectByYear(this.years[0]);
}
selectByYear(event) {
this.year = event.value;
this.getChartType(this.chartType);
this.commonActions.setYearValue(this.year);
}
getChartType(type: string) {
if (this.chart_yfield.length != 0 && this.header != '') {
if (!this.year) {
return;
}
this.chartType = type;
this.isHighChart = true;
this.dataValues = [];
this.xValues = [];
this.yValues = [];
this.lineData = [];
this.beData[this.year][this.header].forEach((entry) => {
this.dataValues.push([entry.name, entry.value]);
});
this.beData[this.year][this.header].forEach((entry) => {
this.xValues.push(entry.name);
});
this.beData[this.year][this.header].forEach((entry) => {
this.yValues.push(entry.value);
});
this.beData[this.year][this.header].forEach((entry) => {
this.bgColors.push(entry.color);
});
console.log(this.xValues, this.yValues, this.header, this.year);
}
}
}
So inside the selectByYear() I'm setting the year. After the value of year gets updated I'm updating the same in the CommonActionsService also.
common-actions.service.ts
export class CommonActionsService {
year_value: string;
constructor() { }
setYearValue(year: string) {
this.year_value = year;
}
getYearValue() {
return this.year_value;
}
}
Now in the bar-chart component, I call the get method. But nothing is displaying in the console.
bar-chart.component.ts
export class BarChartComponent implements OnInit {
year_value: string;
constructor(private commonActions: CommonActionsService) {}
ngOnInit() {
this.year_value = this.commonActions.getYearValue();
console.log("Year Value from Bar Chart: ", this.year_value);
}
}
I want to get the value of this.year inside the selectByYear() in app.component.ts, inside bar-chart.component.ts whenever the year updates.
Or is there any other way other than using services?
I'm adding my full code here - https://stackblitz.com/edit/stackblitz-starters-k2touo?file=src%2Fmain.ts , but I'm not able to compile it online.
| Pass a value to another component using Services when a change in value (dropdown selection) happens in the parent component - Angular | Using services is the right way to share information accross component if they're not parent-child.
Here it is a matter of concurrency: you are calling getYearValue before it has been setted in the other component (both event are being called OnInit, and maybe one component is being initialized before the other).
My suggestion is to use Subject and Observablein order to create streams so that they'll always be up to date.
Here there is a simple example of how you could structure it (I couldn't directly use your code since it was not compiling)
|
76389485 | 76390066 | What is the problem with the following code?
I am trying to print numbers in sequence. One Task is for printing odd numbers and the other task is for printing even numbers.
Could somebody help me how to introduce the synchronization, so that I can get sequenced numbers from 0-10?
Code :
using System.Threading.Tasks;
Task.Run(() =>{
var printNumbers = new PrintNumbers();
for(var i =0; i<10; i++)
{
if(i % 2 == 0)
Console.WriteLine(i);
}
})
Task.Run(() =>{
var printNumbers = new PrintNumbers();
for(var i =0; i<10; i++)
{
if(i % 2 != 0)
Console.WriteLine(i);
}
}
})
oddTask.Start();
evenTask.Start();
Task.WhenAll(new Task[] { oddTask, evenTask});
public class PrintNumbers
{
private static object seqNumbers = new object();
public void PrintOddNumber(int number)
{
lock(seqNumbers)
{
Console.WriteLine(number);
}
}
public void PrintEvenNumber(int number)
{
lock(seqNumbers)
{
Console.WriteLine(number);
}
}
}
Note: I am using Visual Studio Code.
| How to Print numbers in sequential manner using TPL multiple tasks |
What is the problem with the following code?
object seqNumbers = new object();
Task.Run((seqNumbers) =>{ // 1. Task.Run does not allow to pass arguments
for(var i =0; i<10; i++)
{
lock(seqNumbers) // 2. Using `lock` in here is problematic :
// you cannot enforce a toggle with a single one.
{
if(i % 2 == 0)
Console.WriteLine(i);
}
}
})
.Wait(); // 3. This will block until the Task is completed
Task.Run((seqNumbers) =>{
lock(seqNumbers)
{
for(var i =0; i<10; i++)
{
lock(seqNumbers)
{
if(i % 2 != 0)
Console.WriteLine(i);
}
}
}
})
.Wait();
So, you see: The locking here is actually futile, because both Tasks run in sequence to each other. If you want Tasks to run in parallel (potentially), you need to start both and then await both.
If you need sequential output without utilizing intermediate data storage of results, then you have to do something awkward like this:
using System;
using System.Threading;
using System.Threading.Tasks;
public class Program
{
public static async Task Main()
{
var oddsem = new SemaphoreSlim(1,1);
var evensem = new SemaphoreSlim(0,1);
await Task.WhenAll(
Task.Run(async () => {
for(int i = 0; i < 10; i++){
await oddsem.WaitAsync();
try{
if( i % 2 == 0 ) Console.WriteLine("A: {0}",i);
}
finally{evensem.Release();}
}
}),
Task.Run(async () => {
for(int i = 0; i < 10; i++){
await evensem.WaitAsync();
try{
if( i % 2 == 1 ) Console.WriteLine("B: {0}",i);
}
finally{oddsem.Release();}
}
})
);
}
}
Output:
A: 0
B: 1
A: 2
B: 3
A: 4
B: 5
A: 6
B: 7
A: 8
B: 9
See Fiddle.
Which defeats all the benefits of making this parallel in the first place.
|
76388235 | 76388723 | I've tried integrating Firebase multi-factor authentication to your web app and have followed their documentation:https://firebase.google.com/docs/auth/web/multi-factor
Everything works fine until i get to sms verification. After i get a code and instantly type it in i keep getting FirebaseError: Firebase: Error (auth/code-expired) and i can't figure out why. Keep in mind this is my firste time working with firebase.
Here is my code.(I Change the number to xxxxxxx on purpose for showing you my code). Thanks for your help and help in advanced
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
console.log('Sign in Success');
navigate("/Search");
})
.catch(function (error) {
if (error.code === 'auth/multi-factor-auth-required') {
console.log('MFA required');
const resolver = getMultiFactorResolver(auth, error);
const selectedIndex = 0;
if (resolver.hints[selectedIndex].factorId === PhoneMultiFactorGenerator.FACTOR_ID) {
console.log(resolver.hints[selectedIndex].factorId);
const phoneNumber = "XXXXXXXX";
console.log(resolver.session);
const phoneInfoOptions = {
multiFactorHint: resolver.hints[selectedIndex],
session: resolver.session
};
const phoneAuthProvider = new PhoneAuthProvider(auth);
console.log(phoneAuthProvider);
// Create recaptchaVerifier instance
const recaptchaVerifier = new RecaptchaVerifier(
"recaptcha-container",
{
size: "normal",
callback: function (response) {
// reCAPTCHA resolved, continue with phone verification
phoneAuthProvider.verifyPhoneNumber(phoneNumber, recaptchaVerifier, {
// Set the code expiration duration to 60 seconds
codeTime: 60000
})
.then(function (verificationId) {
// Ask user for the SMS verification code. Then:
const verificationCode = prompt("Enter the verification code");
const cred = PhoneAuthProvider.credential(verificationId, verificationCode);
console.log(cred)
const multiFactorAssertion = PhoneMultiFactorGenerator.assertion(cred);
// Complete sign-in.
return resolver.resolveSignIn(multiFactorAssertion);
})
.then(function (userCredential) {
navigate("/Search");
})
.catch(function (error) {
console.log(error)
});
},
"expired-callback": function () {
// Response expired. Ask user to solve reCAPTCHA again.
// ...
},
},
auth
);
recaptchaVerifier.render().then(function (widgetId) {
window.recaptchaWidgetId = widgetId;
});
}
}
});
| Multi-Factor Authentication : FirebaseError: Firebase: Error (auth/code-expired) | Try changing phoneInfoOptions to phoneNumber in:
phoneAuthProvider.verifyPhoneNumber(phoneInfoOptions, recaptchaVerifier, {
// Set the code expiration duration to 60 seconds
codeTime: 60000
})
|
76391385 | 76391547 | Consider the following code snippet:
#include <iostream>
#include <typeinfo>
template<typename T>
class TypePrinter{
public:
void print_type() {
std::cout << typeid(T).name() << std::endl;
}
}; // end class TypePrinter
class Base{
public:
TypePrinter<Base> createTypePrinter(){ // TODO replace "Base" with the class of the instance.
return TypePrinter<Base>();
}
}; // end Base
class Derived: public Base{
};
int main() {
// Create a derived instance and try to create a TypePrinter for it
Derived d;
auto tp = d.createTypePrinter();
tp.print_type(); // prints "4Base".
return 0;
} // end main
In the example above, I have
a class with a typename template parameter (TypePrinter) and
another class that instantiate it, using its type as a parameter (Base)
How can the code above be rewritten so that the inherited derived_instance.createTypePrinter() method can create a TypePrinter<Derived> rather than a TypePrinter<Base>?
In other words, what modifications could allow d.createTypePrinter().print_type() to print "Derived"?
| Is Compile-time Polymorphism in C++ Templates Possible? | As noted in the comments, this can be implemented with the Curiously Recurring Template Pattern.
#include <iostream>
#include <typeinfo>
template<typename T>
class TypePrinter{
public:
void print_type() {
std::cout << typeid(T).name() << std::endl;
}
}; // end class TypePrinter
template<typename T> // Base is now a template class.
// Subclasses set T to their type
class Base{
public:
TypePrinter<T> createTypePrinter(){
return TypePrinter<T>();
}
}; // end Base
class Derived: public Base<Derived>{
};
int main() {
// Create a derived instance and try to create a TypePrinter for it
Derived d;
auto tp = d.createTypePrinter();
tp.print_type(); // Now this prints "7Derived"
return 0;
} // end main
|
76388608 | 76388726 | We are currently looking at migrating existing Xamarin.Android and Xamarin.iOS applications to .NET 6 (we aren't at this stage going to use MAUI).
A big part of this process is understanding which NuGet packages we need to update or replace.
We're just trying to understand the difference between a package being compatible with a framework, and a framework being an additionally computed framework.
We can see for some of the packages we are using that net6.0-ios and net6.0-android are additionally computed frameworks rather than being compatible. What does this mean in terms of whether or not a net6.0-ios or net6.0-android app could consume the package?
| NuGet Compatible vs Computed Framework (Xamarin and .NET 6) | It really depends.
Lets say you are trying to consume a package that only targets netstandard1.0 or above. That package will be totally fine to consume.
However, if you are attempting to consume a package that has multiple targets, lets say
netstandard1.0
Xamarin.iOS
monoandroid13.0
That package will only partially work. The netstandard stuff will definitely work. monoandroid13.0 will most likely work. However, since there are breaking changes between Xamarin.iOS and net6.0-ios then that part won't work.
Most preferably, for packages that target a specific platform, that should at least be net6.0-android or net6.0-ios, otherwise you will encounter issues.
|
76391254 | 76391581 | In the MDN Docs it explains,
Important: Always return results, otherwise callbacks won't catch the result of a previous promise (with arrow functions, () => x is short for () => { return x; }). If the previous handler started a promise but did not return it, there's no way to track its settlement anymore, and the promise is said to be "floating".
With this little json file:
{
"ingredients": "flour,sugar,butter,chocolate"
}
const listOfIngredients = [];
console.clear();
function doSomething() {
fetch('http://127.0.0.1:4000/test.json')
.then((res) => res.json())
.then((data) => {
data.ingredients.split(',').forEach(i => listOfIngredients.push(i));
// doesn't return
})
.then((nothing) => {
console.log(nothing); // undefined, of course
console.log(listOfIngredients);
return "and coconut";
})
.then((something) => {
listOfIngredients.push(something);
console.log(listOfIngredients);
});
}
doSomething();
Result:
undefined
['flour', 'sugar', 'butter', 'chocolate']
['flour', 'sugar', 'butter', 'chocolate', 'and coconut']
So, I think that the result of the success callback, (data) => {...} is (said to be) "floating", but that since in this case, the promise returns immediately, the chained (nothing) => {...} and (something) => {...} callbacks succeed.
If I update the (nothing) callback to contain another fetch, that fetch does need to be returned ((nothing) => { return fetch... otherwise we get ['flour', 'sugar', 'butter', 'chocolate', undefined]. Makes sense.
So, in promise chains, do you only need to return from the callbacks for promise objects that handle asynchronous operations?
| Safety of using and approach to "floating" promises |
So, in promise chains, do you only need to return from the callbacks for promise objects that handle asynchronous operations?
You are correct. From the mdn doc you provided:
If the previous handler started a promise but did not return it, there's no way to track its settlement anymore, and the promise is said to be "floating".
Notice in this one:
.then((data) => {
data.ingredients.split(',').forEach(i => listOfIngredients.push(i));
// doesn't return
})
you aren't starting a promise so there is no issue.
Floating promises have nothing to do with returning the data but rather returning when the promise resolves you could do something like this for instance:
.then(async res => {
window.myGlobal = await res.json();
}).then(nothing => /* ... continue */ undefined);
even though we aren't returning the data directly the function provided only resolves when res.json() has finished so we don't have any hanging promises.
Incidentally your example does have a hanging promise: the doSomething function. the doSomething function should be returning the fetch call as in:
function doSomething() {
return fetch('http://127.0.0.1:4000/test.json')
/* ... */
}
Note that if you didn't want to return the fetch for some reason you could still avoid the hanging promise by using async/await like:
async function doSomething() {
await fetch('http://127.0.0.1:4000/test.json')
/* ... */
}
this is functionally equivalent to the following however:
function doSomething() {
return fetch('http://127.0.0.1:4000/test.json')
/* ... your existing .then chain goes here */
.then(() => undefined)
}
}
Also note that as mentioned in the comments you are probably doing something really bad if you are writing code this way (not returning the results of asyncronous operations but still wanting to do things after they complete)
|
76388587 | 76388739 | When I use a C# TextBox as an input box, I found it hard to quickly select a word by doubleclicking on then text, because it sometimes selects brackets and other characters.
For example, when I double click on var3, it selects and what I want is .
I tried adding doubleclick callback, but it seems be handled after default handler, and I don't know where user actually clicked, this also messes up the dragging operation after doubleclick to select multiple words.
Is there a easy way to redefine the separator chars for word selection?
| How to change the separator of a C# TextBox when I double click to select a word? | You can handle the DoubleClick event and modify the SelectionStart and SelectionLength properties accordingly. Trim the delimiters at the start and end:
private static readonly char[] Delimiters = { ' ', '(', ')', ',', ';', '.', '-', ':', '[', ']' }; // and so on...
private void textBox1_DoubleClick(object sender, EventArgs e)
{
TextBox txt = (TextBox)sender;
string selectedText = txt.SelectedText;
int selectStartOld = txt.SelectionStart;
int selectLengthOld = txt.SelectionLength;
int selectStartNew = selectStartOld;
int selectLengthNew = selectLengthOld;
bool inText = false;
for (int i = 0; i < selectedText.Length; i++)
{
if (!inText && Delimiters.Contains(selectedText[i]))
{
// TrimStart
selectStartNew++;
selectLengthNew--;
}
else if (inText && Delimiters.Contains(selectedText[i]))
{
// TrimEnd
selectLengthNew--;
}
else
{
inText = true;
}
}
txt.SelectionStart = selectStartNew;
txt.SelectionLength = selectLengthNew;
}
|
76389849 | 76390106 | What I have is two Pandas dataframes of coordinates in xyz-format. One of these contains points that should be masked in the other one, but the values are slightly offset from each other, meaning a direct match with drop_duplicates is not possible. My idea was to round the values to the nearest significant number, but this also does not always work, since if some values are rounded to different numbers, they won't match and won't be removed. For example, if one point lies at x = 149 and another at x = 151, rounding them to the nearest hundred gives different values. My code looks something like this:
import pandas as pd
import numpy as np
df_test_1 = pd.DataFrame(np.array([[123, 449, 756.102], [406, 523, 543.089], [140, 856, 657.24], [151, 242, 124.42]]), columns = ['x', 'y', 'z'])
df_test_2 = pd.DataFrame(np.array([[123, 451, 756.099], [404, 521, 543.090], [139, 859, 657.23], [633, 176, 875.76]]), columns = ['x', 'y', 'z'])
df_test_3 = pd.concat([df_test_1, df_test_2])
df_test_3['xr'] = df_test_3.x.round(-2)
df_test_3['yr'] = df_test_3.y.round(-2)
df_test_3['zr'] = df_test_3.z.round(1)
df_test_3 = df_test_3.drop_duplicates(subset=['xr', 'yr', 'zr'], keep=False)
What I want is to remove duplicates if the columns 'xr' and 'yr' are duplicates +-100 and 'zr' duplicates +-0.1. For example, if two coordinates are rounded to (100, 300, 756.2) and (200, 400, 756.1), they should be considered duplicates and should be removed. Any ideas are appreciated, thanks!
| Pandas drop_duplicates with a tolerance value for duplicates | You can numpy broadcasting:
# Convert to numpy
vals1 = df_test_1.values
vals2 = df_test_2.values
# Remove from df_test_1
arr1 = np.abs(vals1 - vals2[:, None])
msk1 = ~np.any(np.all(arr1 < [100, 100, 0.1], axis=2), axis=1)
# Remove from df_test_2
arr2 = np.abs(vals2 - vals1[:, None])
msk2 = ~np.any(np.all(arr1 < [100, 100, 0.1], axis=2), axis=1)
out = pd.concat([df_test_1[msk1], df_test_2[msk2]], ignore_index=True)
Output:
>>> out
x y z
0 151.0 242.0 124.42
1 633.0 176.0 875.76
Comment of @James
This removes left vs right and right vs left, but not duplicates within left vs left or right vs right.
In this case:
df_test_3 = pd.concat([df_test_1, df_test_2])
arr = df_test_3.values
msk = np.abs(arr - arr[:, None]) < [100, 100, 0.1]
out = df_test_3[np.sum(np.all(msk, axis=2), axis=1) == 1]
print(out)
# Output
x y z
3 151.0 242.0 124.42
3 633.0 176.0 875.76
|
76391597 | 76391645 | I thought the idea of .Net Core was that I did not have to install a Run-Time, it was included in the published code. However, when I run my App nothing happens. The Application Event Log says..."Message: You must install .NET to run this application." When I look for .NET Core Runtimes, I only find SDK's. Where are the run-times? What is the published "Runtimes" folder for?
| Publishing a .Net Core 6 Windows Application Will Not Run | .NET Core is just a smaller runtime, mostly split into separate libraries, but it certainly DOES require a runtime, just like normal .NET programs. At build time you could bundle it in the exe or you can depend on an external installed library, but ultimately it's still a dependency, much like with the real .NET Framework.
You can find the runtimes in the Microsoft website. Ror example, here is the .NET Core 6 runtimes download webpage, containing the SDKs, ASP libraries and the standalone runtime.
https://dotnet.microsoft.com/es-es/download/dotnet/6.0
|
76388686 | 76388767 | I am a beigner.And i dont know why the gender radio input is getting reset when i click anywhere on the screen below the rdio buttons section.Can anyone help me with this.This below is my code⬇️⬇️⬇️⬇️⬇️
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h2>Sign Up Form</h2>
<br><br>
<form method=GET action="./pages mine/thank you.html">
<input type="text" placeholder="First name"><br><br>
<input type="text" placeholder="Last name"><br><br>
<input type="email" placeholder="Last name"><br><br>
<input type="password" placeholder="Last name" minlength="5"><br><br>
<!--gender selection-->
<label><h3>Select Gender<h3></label><br>
<label for="male">male</label>
<input type="radio" value="male" id="male" name="gender" required/><br>
<label for="female">female</label>
<input type="radio" value="female" id="female" name="gender" required/><br>
<label for="other">other</label>
<input type="radio" value="other" id="other" name="gender" required/><br><br>
<!--when i click on the screen anywhr after this the gender selection is getting reset-->
<label for="nation">Country</label>
<select id="nation" >
<option value="india" name="nation">INDIA</option>
<option value="usa" name="nation">USA</option>
<option value="other" name="nation">OTHER</option>
</select><br><br>
<p>Write about yourself below</p><br>
<input type="textbox" placeholder="type here"><br>
<input type="submit" placeholder="Sign in">
</form>
</body>
</html>
i was trying the make radio buttons for gender selection but the selection is getting reset on click any where on the screen after the radio buttons section.
| getting a problem where the radio button selections are getting reset to the first radio option | There is a lot of things going wrong in this code.
But for your radio button issue, i think this is caused by <label><h3>Select Gender<h3></label><br>. Your <h3>node is not closed. It should be :
<h3>Select Gender</h3>
Also you don't need a labelaround that.
Here is a refactored version of your code :
https://jsfiddle.net/dzt8ja6n/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h2>Sign Up Form</h2>
<br><br>
<form method="GET" action="./pages mine/thank you.html">
<input type="text" placeholder="First name"><br><br>
<input type="text" placeholder="Last name"><br><br>
<input type="email" placeholder="Email"><br><br>
<input type="password" placeholder="Password" minlength="5"><br><br>
<!-- Gender selection -->
<label for="gender"><h3>Select Gender</h3></label><br>
<label for="male">Male</label>
<input type="radio" value="male" id="male" name="gender" required><br>
<label for="female">Female</label>
<input type="radio" value="female" id="female" name="gender" required><br>
<label for="other">Other</label>
<input type="radio" value="other" id="other" name="gender" required><br><br>
<label for="nation">Country</label>
<select id="nation" name="nation">
<option value="india">INDIA</option>
<option value="usa">USA</option>
<option value="other">OTHER</option>
</select><br><br>
<p>Write about yourself below</p><br>
<textarea placeholder="Type here"></textarea><br>
<input type="submit" value="Sign in">
</form>
</body>
</html>
|
76388597 | 76388771 | Code first.
<div data-a="a b" data-b="a b" id="test"></div>
<div data-a="a<b" data-b="a<b" id="test2"></div>
var test1= document.getElementById('test');
var test1_a= test.getAttribute('data-a');
var test1_b=test.getAttribute('data-b');
// data-a="a b" data-b="a b"
console.log('1:',test1_a===test1_b); // got false;
var test2= document.getElementById('test2');
var test2_a= test2.getAttribute('data-a');
var test2_b=test2.getAttribute('data-b');
// data-a="a<b" data-b="a<b"
console.log('2:',test2_a===test2_b); // got true;
Question: why and < are different in html attribute?
Online run able example.
https://codepen.io/qinbx/pen/eYPqBGQ
| issue when in html attribute | In your case, the problem comes from the data-a attribute, not the HTML Entities.
The 'space' character is different from the 'non-breaking space' character.
See this list of HTML entities and note that the space character can be written using its entity number  .
I updated your example using the 'non breaking space' character (alt + 255) :
var test1= document.getElementById('test');
var test1_a= test.getAttribute('data-a');
var test1_b=test.getAttribute('data-b');
console.log('1:',test1_a===test1_b);
var test2= document.getElementById('test2');
var test2_a= test2.getAttribute('data-a');
var test2_b=test2.getAttribute('data-b');
console.log('2:',test2_a===test2_b);
<!-- a space b -->
<div data-a="a b" data-b="a b" id="test"></div>
<!-- a non-breaking space b (alt + 255) -->
<div data-a="a b" data-b="a b" id="test2"></div>
|
76390067 | 76390118 | I have the following code for my textFormField:
Container(
alignment: Alignment.centerLeft,
height: media.height * 0.12,
decoration: txtFieldBoxDecoration,
child: TextFormField(
textAlignVertical: TextAlignVertical.center,
keyboardType: TextInputType.emailAddress,
style: const TextStyle(
color: Colors.white,
fontSize: 26,
),
decoration: InputDecoration(
border: InputBorder.none,
contentPadding: const EdgeInsets.only(top: 14),
prefixIcon: const Icon(
Icons.email,
color: Colors.white,
size: 28,
),
hintText: 'Insira seu E-mail',
hintStyle: GoogleFonts.openSans(
color: Colors.white54, fontSize: 26),
),
onChanged: (value) {},
),
),
And I'm getting the following result:
How do I align the prefix Icon and the hintText like this:
| How do I align prefixIcon with text on textFormField? | For align the prefix Icon and the hintText,
You have to remove below code from InputDecoration
contentPadding: const EdgeInsets.only(top: 14),
|
76391041 | 76391662 | I am trying to write a generic Makefile that can run multiple different unit tests based on a second term in the make command.
Basically I would like to write something like:
make test target1 # runs unit tests for target 1
make test target2 # runs unit tests for target 2
:
:
:
make test all # runs all unit tests
but I can't find any documentation on how to do this. What I have right now is:
.PHONY: clean test
test-target1:
pytest --cov-report term-missing --cov=a .\target1\
test-target2:
pytest --cov-report term-missing --cov=b .\target2\
test-all:
### I don't know what to put here ###
but this syntax requires you to use make test-target1 with the hyphen included.
EDIT:
Based on some really good advice I now have the updated Makefile:
a: # ...
pytest --cov-report term-missing --cov=a.\UnitTest\a
.PHONY: test
test : $(RUN_ARGS)
@echo "Running unittests for $(RUN_ARGS)..."
but running make test a returns
Running unittests for ...
make: 'a' is up to date.
and if I change a to a1 then make test a1 will run the actual unittests. Why is the a RUN_ARGS not allowed?
For reference, the structure of the code is:
src/a
src/b
src/UnitTest
src/UnitTest/a
src/UnitTest/b
| How to write a Makefile to test multiple Unittest targets? | Thanks to all the help I received, I was able to solve both parts of my question by creating the following Makefile:
all: a b c
a:
pytest --cov-report term-missing --cov=a .\UnitTest\a\
b:
pytest --cov-report term-missing --cov=b .\UnitTest\b\
c:
pytest --cov-report term-missing --cov=c .\UnitTest\c\
.PHONY: test a b c
test : $(RUN_ARGS)
@echo "Running unittests..."
|
76388755 | 76388787 | I need to get a timestamp out of multiple time-formats like:
df['date'] = [29.05.2023 01:00:00,
29.05.2023,
28.05.2023 23:00:00]
At 00:00:00 on every day the time is missing and only the date has been logged.
I need the timestamp to look like this:
df['date'] = [29.05.2023 01:00:00,
29.05.2023 00:00:00,
28.05.2023 23:00:00]
| pd.to_datetime with multiple format | Use to_datetime with dayfirst=True parameter, for final ouput DD.MM.YYYY HH:MM:SS use Series.dt.strftime:
df = pd.DataFrame({'date':['29.05.2023 01:00:00',
'29.05.2023',
'28.05.2023 23:00:00',
'4.10.2023']})
df['date'] = pd.to_datetime(df['date'], dayfirst=True).dt.strftime('%d.%m.%Y %H:%M:%S')
print (df)
date
0 29.05.2023 01:00:00
1 29.05.2023 00:00:00
2 28.05.2023 23:00:00
3 04.10.2023 00:00:00
|
76390099 | 76390137 | The behaviour of html_strip character filter looks different with the search query using "query_string" and "match" query.
Created index with "description" field using my_analyzer having html_strip char filter
{
"settings": {
"analysis": {
"analyzer": {
"my_analyzer": {
"tokenizer": "standard",
"char_filter": [
"html_strip"
]
}
}
}
},
"mappings": {
"properties": {
"description": {
"type": "text",
"analyzer": "my_analyzer"
}
}
}
}
Indexed as below with sample html content
PUT test_index/_doc/001
{
"description": "<html><body>Hello world</body></html>"
}
document created.
search using <html> :
GET /test_index/_search
{
"query": {
"query_string": {
"query": "<html>"
}
}
}
Expecting no hits as the html contents would be stripped out internally when using html_strip character filter as per the document (https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-htmlstrip-charfilter.html) but got the result,
result:
{
"took": 2,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 0.2876821,
"hits": [
{
"_index": "test_index",
"_type": "_doc",
"_id": "001",
"_score": 0.2876821,
"fields": {
"description": [
"<html><body>Hello world</body></html>"
]
}
}
]
}
}
Returns the record (ideally it should not).
Let's search using "match" query:
When match query is used it could not find a record when searched using <html> or <body>. whereas it returns record when searched using "Hello" which seems to be the right behaviour of html_strip char filter.
GET /test_index/_search
{
"query": {
"match": {
"description": "<html>"
}
},
"fields": [
"description"
],
"_source": false
}
Result:
{
"took": 2,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 0,
"relation": "eq"
},
"max_score": null,
"hits": []
}
}
the above query doesn't return any result and looks like the html_strip character filter is working fine with "match" query.
Any suggestions why html_strip character filter is not working as expected with "query_string" query and working with "match" query?
Am I missing anything here?
| The elasticsearch html_strip character filter doesn't work as expected with query_search query | You didn't define any field in your query. By default, it hits all fields include description, and description.keyword.
When you trying with match query you are defining the fields :).
Update query like the following
GET /test_html_strip/_search
{
"query": {
"query_string": {
"query": "<html>",
"fields": ["description"]
}
}
}
|
76391406 | 76391673 | I'm trying to get market data from bingx websocket API but once my connection stablished i recieve blob data and i dont know how can i read candlestick data from that blob response with javascript does any one know how can i extract data?
here is my Js code :
var ws = new WebSocket('wss://open-ws-swap.bingbon.pro/ws');
ws.onopen = (event) => {
const msg = {
id: "548",
reqType:"sub",
dataType: "market.kline.BTC-USDT.1min",
}
ws.send(JSON.stringify(msg));
console.log('connection stablished!')
}
// Listen for messages
ws.onmessage = function(event) {
console.log(event.data);
}
ws.onclose = function(event) {
console.log(event)
};
ws.onerror = function(error) {
console.log(error);
};
And here is the result in console:
I tried this answer bot not working:
text
| How to extract blob data from websocket response | From the docs ->
All response data from Websocket server are compressed into GZIP
format. Clients have to decompress them for further use
So using this information we can use DecompressionStream -> https://developer.mozilla.org/en-US/docs/Web/API/DecompressionStream to uncompress the data, and then use TextDecoder to convert that into to text, finally JSON.parse to convert into an object.
Finally you will want to watch for the Ping message, as the API will disconnect if you don't send a Pong.
eg.
var ws = new WebSocket('wss://open-ws-swap.bingbon.pro/ws');
async function decompressBlob(blob) {
const ds = new DecompressionStream("gzip");
const decompressedStream = blob.stream().pipeThrough(ds);
return await new Response(decompressedStream).blob();
}
ws.onopen = (event) => {
const msg = {
id: "548",
reqType:"sub",
dataType: "market.kline.BTC-USDT.1min",
}
ws.send(JSON.stringify(msg));
console.log('connection stablished!')
}
// Listen for messages
ws.onmessage = async function(event) {
const data = await decompressBlob(event.data);
const txt = new TextDecoder().decode(await data.arrayBuffer());
if (txt === 'Ping') {
//this keeps the api open
ws.send('Pong');
} else {
console.log(JSON.parse(txt));
}
}
ws.onclose = function(event) {
console.log(event)
};
ws.onerror = function(error) {
console.log(error);
};
|
76389592 | 76390142 | I need to run all the tests from the "spec/workers/**" folder, but I don't want to run the tests in a specific folder that is inside the "spec/workers/". I'm using the --pattern flags to say what I want and --exclude--pattern to say what I don't want to run. and it still does what is described in --exclude-pattern.
Eg:
bundle exec rspec --pattern "spec/workers/**/*_spec.rb" --exclude-pattern "spec/workers/study_workers/*_spec.rb"
| Rspec confused when I run the tests on the rspec with the --pattern and --exclude-patternn flags | This is not a bug but expected behavior.
When there are two filters defined, one to include a specific files and another to exclude the same specific files, then excluding pattern has a lower priority and therefore the file is included.
Please see the discussion in this GitHub issue.
|
76388276 | 76388832 | There is a datatable in a page in Flutter, I want to zoom in and out of this table or page with two fingers. Can anyone offer a solution ?
My main goal here is just to zoom in and out. Is there a widget for this? I couldn't find a way, what can I do? Can you help me ?
There is a video in the link
I have specified all my table codes below. You can review and have details
here are my codes
ListView(children: <Widget>[
SizedBox(
width: double.infinity,
child: Padding(
padding: EdgeInsets.fromLTRB(size.width * 0.03,
size.width * 0.1, size.width * 0.03, size.width * 0.00),
child: TextField(
cursorColor: BaseData.vadenHomeSiyah,
controller: txtPaletNo,
// focusNode: unitCodeCtrlFocusNode,
textAlign: TextAlign.center,
decoration: InputDecoration(
focusedBorder: OutlineInputBorder(
borderSide: const BorderSide(
color: Color.fromARGB(255, 0, 0, 0), width: 2.0),
borderRadius: BorderRadius.circular(25.0),
),
border: UnderlineInputBorder(),
labelText: 'Palet No',
labelStyle: TextStyle(
color: Colors.black, fontSize: size.width * 0.05),
filled: true,
isDense: true,
fillColor: Colors.white.withOpacity(0.2)),
//işlemler
onSubmitted: (value) {
setState(() {
paletRaporYuklendimi = true;
});
seciliPaletRaporGetir();
},
onChanged: (text) {},
),
// TextField(
// controller: searchController,
// decoration: const InputDecoration(
// hintText: 'Ara...',
// border: OutlineInputBorder(),
// ),
// onChanged: _onSearchTextChanged,
// ),
),
),
Padding(
padding: EdgeInsets.fromLTRB(size.width * 0.00,
size.width * 0.08, size.width * 0.00, size.width * 0.00),
child: SizedBox(
width: MediaQuery.of(context).size.width,
child: FittedBox(
child: paletRaporYuklendimi
? Center(
child: Padding(
padding: EdgeInsets.all(size.width * 0.2),
child: const CircularProgressIndicator(
color: Colors.black,
),
),
)
: DataTable(
dataRowHeight: size.width * 0.4,
columns: const <DataColumn>[
DataColumn(
label: Text(
'Palet No',
style: TextStyle(
fontWeight: FontWeight.w900,
fontSize: 30),
),
),
DataColumn(
label: Text(
'Paket No',
style: TextStyle(
fontWeight: FontWeight.w900,
fontSize: 30),
),
),
DataColumn(
label: Text(
'Tarih',
style: TextStyle(
fontWeight: FontWeight.w900,
fontSize: 30),
),
),
DataColumn(
label: Text(
'Hareket Tip',
style: TextStyle(
fontWeight: FontWeight.w900,
fontSize: 30),
),
),
DataColumn(
label: Text(
'Hücre Kodu',
style: TextStyle(
fontWeight: FontWeight.w900,
fontSize: 30),
),
),
DataColumn(
label: Text(
'Hareket Turu',
style: TextStyle(
fontWeight: FontWeight.w900,
fontSize: 30),
),
),
DataColumn(
label: Text(
'Cari Isim',
style: TextStyle(
fontWeight: FontWeight.w900,
fontSize: 30),
),
),
],
rows: List.generate(filterList.length, (index) {
final item = filterList[index];
return DataRow(
cells: [
DataCell(Text(
item.PALETNO ?? "",
style: const TextStyle(
fontWeight: FontWeight.w900,
fontSize: 30),
)),
DataCell(Text(
item.PAKETNO.toString(),
style: const TextStyle(
fontWeight: FontWeight.w900,
fontSize: 30),
)),
DataCell(Text(
item.TARIH ?? "",
style: const TextStyle(
fontWeight: FontWeight.w900,
fontSize: 30),
)),
DataCell(item.HAREKETTIPI == "G"
? Text(
item.HAREKETTIPI ?? "",
style: const TextStyle(
fontWeight: FontWeight.w900,
fontSize: 30,
color: Colors.green),
)
: Text(
item.HAREKETTIPI ?? "",
style: const TextStyle(
fontWeight: FontWeight.w900,
fontSize: 30,
color: Colors.red),
)),
DataCell(Text(
item.HUCREKODU ?? "",
style: const TextStyle(
fontWeight: FontWeight.w900,
fontSize: 30),
)),
DataCell(Text(
item.HAREKETTURU ?? "",
style: const TextStyle(
fontWeight: FontWeight.w900,
fontSize: 30),
)),
DataCell(Text(
item.CARIISIM ?? "",
style: const TextStyle(
fontWeight: FontWeight.w900,`your text`
fontSize: 30),
)),
],
);
}),
),
),
),
),
if (filterList.length > 0)
Padding(
padding: EdgeInsets.all(size.width * 0.03),
child: Text(
"Listelenen Kayıt Sayısı: " +
filterList.length.toString(),
textAlign: TextAlign.right,style: TextStyle(color: Colors.green,fontWeight: FontWeight.bold),
),
)
else
Text("")
]),
| How can I make flutter 2 finger zoom? | Use InteractiveViewer and wrap the widget you want to zoom in or out, you can specify the max and min zoom with fields minScale and maxScale, and, what is also very nice, you can use a TransformationController, like this one below, for example, and apply it to your InteractiveViewer Widget and enable also zooming in and out by controls:
final zoomTransformationController = TransformationController();
void _zoomIn(){
zoomTransformationController.value.scale(2);
}
void _zoomOut(){
zoomTransformationController.value.scale(0.9);
}
class InteractiveViewerExampleApp extends StatelessWidget {
const InteractiveViewerExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: const InteractiveViewerExample(),
),
);
}
}
class InteractiveViewerExample extends StatelessWidget {
const InteractiveViewerExample({super.key});
@override
Widget build(BuildContext context) {
return Center(
child: InteractiveViewer(
boundaryMargin: const EdgeInsets.all(20.0),
minScale: 0.1,
maxScale: 2,
transformationController: zoomTransformationController,
child: Container(
...
),
),
);
}
}
|
76391704 | 76391757 | Any idea why snowflake to_timestamp is converting February month to January?
SELECT to_timestamp(to_char('2022-02-02 08:01:29 AM'),'YYYY-MM-DD HH12:MM:SS AM');
-- 2022-01-02 08:00:29.000
| to_timesamp converting month to different month | MM represent month when you convert to char , you should use MI for minute in snowflake, I assume the issue comes from there :
SELECT to_timestamp(to_char('2022-02-02 08:01:29 AM','YYYY-MM-DD HH12:MI:SS AM'));
|
76389885 | 76390146 | I've the following very simple Vue 3 component:
<template lang="pug">
b-modal(v-model="dshow")
template(v-slot:default) test
</template>
<script>
export default {
props: {
show: {
type: Boolean,
default: false
}
},
data() {
return {
dshow: false
}
},
watch: {
show: function () {
this.dshow = this.show
},
dshow: function () {
this.$emit('update:show', this.dshow)
}
}
}
</script>
In my parent component, I'm using this as following:
import demo from 'mymodal.vue'
<template lang="pug">
button.btn.btn-primary.hstack.gap-2(@click="showModal= true") Show Modal!
demo(:show.sync="showModal")
</template>
<script>
export default {
components: {
demo
},
data() {
return {
showModal: false
}
}
}
</script>
Now, when I click on my button in the parent, the modal appears and when I close / hide the dialog, the callback for my watched variable dshow is also called. But unfortunately, my parent component isn't informed about the update. So when I click on my button next time, nothing happens, because the showModal hasn't been updated. this.$emit('update:show', this.dshow) is emitted, but the parent value isn't updated.
Any idea on this? I run completely out of ideas on this :-(
| Parent variable in Vue 3 not updated when using update-emit on prop | In Vue 3, the .sync modifier has been removed in favor of arguments to v-model (see migration guide)
So
:show.sync="showModal"
now has to be
v-model:show="showModal"
|
76388667 | 76388836 | I'm trying to connect to http in my .net MAUI app and I disabled the Apple Transport Security (ATS) following Microsoft documentation (from here) by adding below configuration in the info.plist file:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsLocalNetworking</key>
<true/>
</dict>
However, I'm still getting below error message when attempting to communicate with the API using http:
[0:] An error occurred: 'Error Domain=NSURLErrorDomain Code=-1022 "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection." UserInfo={NSLocalizedDescription=The resource could not be loaded because the App Transport Security policy requires the use of a secure connection., NSErrorFailingURLStringKey=http://restapi.adequateshop.com/api/Tourist, NSErrorFailingURLKey=http://restapi.adequateshop.com/api/Tourist, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask <27DB8D6A-2EB6-41FE-953E-6FA2BFDBEDDC>.<1>"
), _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <27DB8D6A-2EB6-41FE-953E-6FA2BFDBEDDC>.<1>, NSUnderlyingError=0x280b9b330 {Error Domain=kCFErrorDomainCFNetwork Code=-1022 "(null)"}}'. Callstack: ''
Any idea how to resolve this? Thank you in advance.
| Enable clear-text local traffic on iOS not working in .NET MAUI | The key that is specified in that documentation page only works for local addresses like IP addresses or addresses that end in .local as you can see in the Apple documentation.
From your error message it seems that you are trying to reach a regular web address. In that case the key you need is: NSAllowsArbitraryLoads so that it opts out of ATS altogether.
Your full entry will then look like this:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
However, I would not recommend doing this. Please try to get your endpoints on HTTPS. It should not be expensive anymore nowadays and this way your users and you will be at risk.
If you really can't add HTTPS, try to limit the unsafe connections made for your app to a single domain. How that is done can be found here in the Apple documentation.
Basically, your info.plist entry should now look something like this:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<false/>
<key>NSExceptionDomains</key>
<dict>
<key>adequateshop.com</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
</dict>
But again, I would recommend fixing the server to be secure above all.
|
76391598 | 76391769 | I have a json file that has over 1000 records in it all similar to the one below:
[{"id":0,"occupation":"teacher","county":"Santa Rosa","grade":"3rd","workID":"147767"},
I want to extract all the records that have a certain occupation, in this case I want to return the records where the occupations are teacher.
This is what I have tried:
specified_occ = {}
for o in data:
specified_occ[o["occupation"]] = o
specOcc = (specified_occ['teacher'])
but it only returns the first instance rather than all of them that match.
My dataset has 50 records where the occupation is 'teacher' I want every record returned.
| How to extract specific records from a JSON file that all have the same value in a specified field with python? | You can use a list comprehension to filter over your data and only select the needed elements. In general a list comprehension looks like this
filtered_list = [element for element in original_list if element == requirement]
Here you only select the elements from the original list if the elements match some requirement.
For this specific problem you would use
filtered_data = [person for person in data if person['occupation'] == 'teacher']
This is syntactically equivalent to
speccified_o = []
for o in data:
if o['occupation'] == 'teacher':
speccified_o.append(o)
|
76389800 | 76390151 | index is going out of bound it's not triggering while(i<str.length()) break; i tried to implement this line differently
string delStr(string s, int sIdx, int nChar) {
string ans = "";
int i = 0;
int n = s.length()-1;
while(n--){
if(i==sIdx){
i += nChar;
}
if(n<0) break;
ans.push_back(s[i]);
i++;
}
}
Trying to implement string erase method.
| Why is my C++ string erase-remove-idiom implementation causing an infinite loop with conditional statements? | You should be sure to post a minimal, reproducible example when you ask a question. This will help people provide an answer.
If I understand the function correctly, I believe it is supposed to return a new std::string with the characters from sIdx to sIdx + nChar removed. If that is the case, there is a logic error that I can't quite follow. You can compare the posted code to the sample below and maybe that will help you correct it.
In the sample code, I show two different solutions. The first uses the standard library algorithms and the second just iterates over the characters similar to the posted code. The advantage of using the algorithms is that they are well-tested for correctness, have efficient implementations, and serve as a common language among developers.
Sample Code
#include <iostream>
using std::cout, std::endl;
std::string delete_substr(const std::string& str, int sIdx, int nChar) {
std::string answer;
std::copy(str.begin(), str.begin() + sIdx, std::back_inserter(answer));
std::copy(str.begin() + sIdx + nChar, str.end(), std::back_inserter(answer));
return answer;
}
std::string delStr(const std::string& str, int sIdx, int nChar) {
std::string answer;
int i{};
while (i < str.size()) {
if (i == sIdx)
i += nChar;
else
answer.push_back(str[i++]);
}
return answer;
}
int main(int argc, const char *argv[]) {
std::string s0 = "abcdefghi";
cout << delete_substr(s0, 3, 3) << endl;
cout << delStr(s0, 3, 3) << endl;
return 0;
}
Output
abcghi
abcghi
|
76387893 | 76388837 | I was trying to achieve parallel testing using cucumber with Junit. When I am trying to run the feature file parallely the runner file generated is importing from cucumber.api instead of io.cucumber. I want to know why it is dynamically taking from cucumber.api and also how can i fix that.Dynamic generated runner file
Tried Adding latest version of cucumber and junit but didint worked
| How to fix dynamically generated runner files importing from 'cucumber.api' in Cucumber/Junit parallel testing? | You're using a more modern version of Cucumber then the code generator you're using was written for.
You don't need the code generator anymore because Cucumber supports parallel execution now.
You can use the cucumber-java-skeleton to get started. The cucumber-junit-platform-engine docs should explain everything else.
|
76390027 | 76390173 | How can I subtract the system date from the created task date in SQL ORACLE to get the difference in days, hours, minutes?
I tried this code but i get wrong values:
TO_CHAR(TO_DATE('1970-01-01 00:00:00','yyyy-mm-dd hh24:mi:ss') + (sysdate - a.CREATE_DATE_PL ), 'dd:hh24:mi:ss') AS TT_LIFETIME
My results is below (the report has been generated 02.06 14:05
enter image description here
| SQL ORACLE, How to subtract sysdate? | Difference of two DATE datatype values is number of days between them, so you have to do some arithmetic to extract days/hours/minutes, or - another option - to try extract with numtodsinterval.
For example:
SQL> WITH
2 test (create_date_pl)
3 AS
4 (SELECT TO_DATE ('01.06.2023 08:10', 'dd.mm.yyyy hh24:mi') FROM DUAL)
5 SELECT SYSDATE,
6 create_date_pl,
7 --
8 SYSDATE - create_date_pl diff,
9 NUMTODSINTERVAL (SYSDATE - create_date_pl, 'day') c1,
10 EXTRACT (DAY FROM NUMTODSINTERVAL (SYSDATE - create_date_pl, 'day')) cd,
11 EXTRACT (HOUR FROM NUMTODSINTERVAL (SYSDATE - create_date_pl, 'day')) ch,
12 EXTRACT (MINUTE FROM NUMTODSINTERVAL (SYSDATE - create_date_pl, 'day')) cm
13 FROM test;
SYSDATE CREATE_DATE_PL DIFF C1 CD CH CM
---------------- ---------------- ---------- ---------------------------------------- ---------- ---------- ----------
02.06.2023 14:29 01.06.2023 08:10 1,26333333 +000000001 06:19:12.000000000 1 6 19
SQL>
When I ran that code, it was 2th of June 2023 at 14:29. Date to be subtracted was 1st of June 2023 (yesterday) at 08:10.
diff represents number of days between those two values
c1 is what numtodsinterval returns
cd, ch and cm contain extracted number of days/hours/minutes, i.e. difference is 1 day, 6 hours and 19 minutes
|
76391760 | 76391774 | I am a Java guy learning Angular.
I have a service and I would like to have injected that service into my object. This doc explains well how to do it in a normal case. As I understand the concept, in the example we use constructor dependency injection.
But in my case, this is not possible because I am extending a class that has its own constructor with 3 parameters and I am not allowed to modify the parent constructor. So I can not add a 4th parameter to my constructor to have injected the service.
This code does not work because the last constructor param is invalid.
my code:
export class ChildComponent extends ParentComponent {
constructor(readonly service1: Service1,
readonly service2: Service2,
el?: ElementRef | null,
readonly service3: Service3) { <-- invalid param
super(service1, service2, el);
}
What is the alternative dependency injection if the constructor injection is not an option?
| dependency injection in Angular when extending a class | Instead of injecting the service through the constructor, you can declare a property in your child component and annotate it with the @Inject decorator to specify the service you want to inject.
|
76388653 | 76388845 | After migrating to spring boot 3 ,
extends ResourceServerConfigurerAdapter is deprecrated.
Hence , unable to use the overrriden method
@Override
public void configure(ResourceServerSecurityConfigurer config) {
config.tokenServices(tokenServices());
}
I am able to replace this with
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeHttpRequests(auth->auth.
requestMatchers(whitelistedEndPoints()).permitAll()
.anyRequest()
.anonymous())
.httpBasic().disable();
return http.build();
}
I have an existing code to get jwt token from OAuth as
public String getJwtTokenFromAuth() {
OAuth2Authentication auth =(OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
OAuth2AuthenticationDetails oauth2AuthenticationDetails = (OAuth2AuthenticationDetails) auth.getDetails();
return oauth2AuthenticationDetails.getTokenValue();
}
However,
OAuth2Authentication and OAuth2AuthenticationDetails are not available
How can i replace this code/functionality with new spring security module of spring boot 3.
Below is the pom dependencies , please suggest if i need to add/remove any ?
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-resource-server</artifactId>
</dependency>
| Spring Security with Spring Boot 3 - Get JWT token from Security Context Holder | Spring Security OAuth2 is deprecated and removed for a while. The replacement is built in Spring Security itself and the dependencies to use are exactly what you already know:
the required dependencies are:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-resource-server</artifactId>
</dependency>
In order to gain the token value in a resource server you can do something like this
class PrincipalIntrospector {
public String token() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
JwtAuthenticationToken oauthToken = (JwtAuthenticationToken) authentication;
return oauthToken.getToken().getTokenValue();
}
}
in order to make sure to have the role properly configured in your principal you can have something like below:
@Bean
public JwtAuthenticationConverter jwtAuthenticationConverter() {
JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(jwt -> {
List<String> authorities = jwt.getClaim("authorities");
return authorities.stream().map(SimpleGrantedAuthority::new).collect(toList());
});
return jwtAuthenticationConverter;
}
in order to decode and make to spring to validate your jwt you can configure something like below:
// used in case of public key
@Bean
public JwtDecoder jwtDecoder() {
return NimbusJwtDecoder.withPublicKey(this.key).build();
}
// used in case of the private key
@Bean
public JwtDecoder jwtDecoder() {
return NimbusJwtDecoder.withSecretKey(this.key).build();
}
The spring security pipeline can look like below:
@Bean
public SecurityFilterChain filterChain(
JwtDecoder decoder,
JwtAuthenticationConverter converter,
HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeHttpRequests(auth->auth.
requestMatchers(whitelistedEndPoints()).permitAll()
.anyRequest()
.authenticated())
.oauth2ResourceServer().jwt().decoder(decoder).jwtAuthenticationConverter(converter);
return http.build();
}
|
76389421 | 76390179 | I have ECS which uses EC2 and EC2 has a contianer.
From EC2 node I can access the outside with this command.
[ec2-user@ip-172-31-23-50 ~]$ curl google.com
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.com/">here</A>.
</BODY></HTML>
Then I login container running on this node, docker exec -it container-name /bin/bash
root@ip-172-31-24-234:/# curl google.com
I can't access(nothing appears).
So, I check the security group of ECS Service.
However all outbound connection is allowed
Test
on EC2 node I try to run another container (Becasue I wanted to test the container which is not managed by ECS service).
`docker run -it ubuntu`
then install curl and try curl in the this ubuntu containaer,I can connect to the outside from the container.
So the problem happens only in ECS managed container,
My task difinition is made by CDK, maybe this Network mode is related....??
const adminTaskDefinition = new ecs.Ec2TaskDefinition(this, 'AdminTaskDefinition', {
networkMode: ecs.NetworkMode.AWS_VPC,
})
| Can't connect to outside from the docker container managed by ECS on EC2 | Perhaps set your Network Mode = host in your task definition.
|
76391141 | 76391779 | I have the columns Yearmonth, code, type and clntamount in my table. I want to derive column clntamount_der.
Table view
I want the 110 value in clntamount with the type = Total to be in the column clntamount_der where the type = base and the rest two rows(adj and total) as zero.
Please help with the logic.
I tried case statemnt but it didnt work maybe a subquery will work
| Creating a new column in SQL Oracle with a subquery - any suggestions? | You may use the conditional max window function as the following:
select t.*,
case
when TYPE = 'BASE'
then max(case when TYPE = 'TOTAL' then CLNTAMOUNT end) over
(partition by YearMonth, Code)
else 0
end as clntamount_der
from tbl t
order by
YearMonth, Code,
case TYPE
when 'BASE' then 1
when 'ADJUST' then 2
when 'TOTAL' then 3
end
demo
Also, it seems that the TOTAL is the sum of other types (BASE, ADJUST), in this case, it would be better to calculate the TOTAL on the fly (and not store it as a separate row) to avoid data inconsistency. i.e. when you update the CLNTAMOUNT value where type = 'BASE' how would you reflect this to the value where type = 'TOTAL'?
consider the following without having the TOTAL type stored in the table.
select d.*
from
(
select t.YearMonth, t.Code, t.Type, t.CLNTAMOUNT,
case
when TYPE = 'BASE'
then sum(t.CLNTAMOUNT) over (partition by t.YearMonth, t.Code)
else 0
end as clntamount_der
from tbl t
union all
select t.YearMonth, t.Code, 'TOTAL',
sum(t.CLNTAMOUNT), 0
from tbl t
group by t.YearMonth, t.Code
) d
order by
d.YearMonth, d.Code,
case d.TYPE
when 'BASE' then 1
when 'ADJUST' then 2
when 'TOTAL' then 3
end
demo
|
76391738 | 76391785 | I am trying to assign new values to the underlying structure of an interface in code below. But it keeps the older values. Below is the example code.
package main
import (
"fmt"
"math"
)
type Shape interface {
Area() float64
}
type Circle struct {
Radius float64
Name string
}
func (c Circle) Area() float64 {
return math.Pi * c.Radius * c.Radius
}
type Rectangle struct {
Length float64
Width float64
Name string
}
func (r Rectangle) Area() float64 {
return r.Length * r.Width
}
func assignRadius(s Shape, radius float64, name string) {
switch s := s.(type) {
case Circle:
s.Radius = radius
s.Name = name
case Rectangle:
s.Length = radius
s.Name = name
}
}
func main() {
var s Shape
c := Circle{Radius: 0, Name: "My Circle"}
s = c
fmt.Println(s.Area())
fmt.Println(c.Radius)
fmt.Println(c.Name)
assignRadius(s, 10, "My New Circle")
fmt.Println(c.Radius)
fmt.Println(c.Name)
}
The type of Shape isn't known beforehand in the assignRadius. I know it has something to do with the pointers. But can't figure it out.
| Assign new values later to the underlying object of the interface in go | The interface variable s contains a copy of the shape value. To modify it like you attempted to do, it has to contain a pointer to that shape:
var s Shape
c := Circle{Radius: 0, Name: "My Circle"}
s = &c
and in the function modifying them, you have to type-assert the pointer value:
func assignRadius(s Shape, radius float64, name string) {
switch s := s.(type) {
case *Circle:
s.Radius = radius
s.Name = name
case *Rectangle:
s.Length = radius
s.Name = name
}
|
76389675 | 76390184 | I have a large scrolling canvas that is 2000 pixels wide, with an unlimited length, inside of which is a single large UIView.
You can interact with the UIView to add objects (lines, shapes, text boxes, images, pdfs etc).
When you add a text box, I create a subclass of UITextView that is configured to auto-grow with text - limited to 600px wide and unlimited length (you can force it wider). Key point - UITextViews never scroll internally.
The problem I am having is moving the UIscrollview (i.e. the big canvas) to keep the cursor of the active text box visible. When you are on a limited width display (such as an iPhone), you should be able to click on a text box and start typing. The scroll view should move around to keep your current cursor (text entry point) on the screen, even when the UITextView is very wide.
This is not too hard - I have a UITextViewDelegate with a "DidChangeSelection:" function. When the selection moves and the delegate method gets called - I find the current cursor (SelectedTextRange), convert that into a rect (GetFirstRectForRange), then convert from UITextView coordinates to the UIView coordinates (ConvertRectToView), then request the UIScrollView being that rect into view (ScrollRectToVisible).
What is weird is that even though my rect is correct - the UITextView is always aligning so the far right hand edge is visible. So if the UITextView is 1000px wide, and the visible part of the UIScrollView is only 500px wide, then only ½ of the UITextView can be seen. No matter where the cursor is, the UIScrollView scrolls so that the right hand side of the UITextView is always visible.
The UITextView seems to be trying to make itself visible when it is the active control, but it seems to always attempt to "ScrollToRect" to its full width, and if the UITextView is wider than the visible area, the UIScrollView always seems to show the right hand side. I know this because I can turn off my delegate, and the UITextView does scroll into view, but only the right hand side.
Is this standard behaviour? Ideally I want to turn off whatever mechanism is automatically scrolling the active UITextView into view so that my correct ScrollToRect call will be used instead.
Thanks for any advice you can give.
Cheers.
| Active UITextView moving in UIScrollView | Couple options to try...
First, subclass UIScrollView:
class MyScrollView: UIScrollView {
override func scrollRectToVisible(_ rect: CGRect, animated: Bool) {
// don't do anything
}
}
This will prevent the built-in "auto-scroll" when the text view is active.
Second option:
Embed the text view in a "container scroll view"
disable scrolling of that scroll view
constrain the text view to that scroll view's .frameLayoutGuide, so the text view controls the size of the container scroll view
add that container scroll view as a subview of your "content" view
Now, when the text view is "active," its "container" scroll view will receive the auto-scroll messages instead of the "main" scroll view.
In either case, of course, your code will be responsible for managing any horizontal / vertical scrolling needed to keep the insertion point visible.
Edit
Quick example for Second Option:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let tv = UITextView()
let tvsv = UIScrollView()
let cv = UIView()
let sv = UIScrollView()
[tv, tvsv, cv, sv].forEach { v in
v.translatesAutoresizingMaskIntoConstraints = false
}
tvsv.addSubview(tv)
cv.addSubview(tvsv)
sv.addSubview(cv)
view.addSubview(sv)
let g = view.safeAreaLayoutGuide
let cg = sv.contentLayoutGuide
let fg = sv.frameLayoutGuide
let tsfg = tvsv.frameLayoutGuide
NSLayoutConstraint.activate([
tv.topAnchor.constraint(equalTo: tsfg.topAnchor, constant: 0.0),
tv.leadingAnchor.constraint(equalTo: tsfg.leadingAnchor, constant: 0.0),
tv.trailingAnchor.constraint(equalTo: tsfg.trailingAnchor, constant: 0.0),
tv.bottomAnchor.constraint(lessThanOrEqualTo: tsfg.bottomAnchor, constant: 0.0),
tv.widthAnchor.constraint(equalToConstant: 600.0),
tvsv.topAnchor.constraint(equalTo: cv.topAnchor, constant: 20.0),
tvsv.leadingAnchor.constraint(equalTo: cv.leadingAnchor, constant: 20.0),
tvsv.bottomAnchor.constraint(lessThanOrEqualTo: cv.bottomAnchor, constant: -20.0),
tv.widthAnchor.constraint(equalToConstant: 600.0),
cv.topAnchor.constraint(equalTo: cg.topAnchor, constant: 20.0),
cv.leadingAnchor.constraint(equalTo: cg.leadingAnchor, constant: 20.0),
cv.trailingAnchor.constraint(equalTo: cg.trailingAnchor, constant: -20.0),
cv.bottomAnchor.constraint(equalTo: cg.bottomAnchor, constant: -20.0),
cv.widthAnchor.constraint(equalToConstant: 1000.0),
sv.topAnchor.constraint(equalTo: g.topAnchor, constant: 20.0),
sv.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
sv.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),
sv.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: -20.0),
])
tv.isScrollEnabled = false
tvsv.isScrollEnabled = false
// so we can see the framing
tv.backgroundColor = .yellow
cv.backgroundColor = .systemBlue
sv.backgroundColor = .systemRed
view.backgroundColor = .systemYellow
}
}
Note: I have not implemented any code for manually handling the scroll view's content offset, which would be needed to keep the insertion point visible. However, this will demonstrate that the "auto-scroll" is no longer in effect.
|
76388754 | 76388863 | We provide to a bunch of customers a website so that their customers can make a booking and purchase services online using Stripe. I am in the process of Internationalizing but I have hit a barrier where some currencies are not valid for Stripe and we don't find out until we attempt to make the payment. I have tried to find a way of retrieving a list of valid currencies from Stripe so that our software can check against it before offering the option to purchase services and I can't find anything like that.
Does anybody know of a solution for automating the process?
I am curious to hear how other people have tackled this problem.
| How to get a List of valid currencies from Stripe | You can use country_specs endpoint - https://stripe.com/docs/api/country_specs
CountrySpecService is available in Stripe.NET and returns this kind of objects (see model below). I think you are looking for SupportedBankAccountCurrencies or SupportedPaymentCurrencies
// File generated from our OpenAPI spec
namespace Stripe
{
using System.Collections.Generic;
using Newtonsoft.Json;
/// <summary>
/// Stripe needs to collect certain pieces of information about each account created. These
/// requirements can differ depending on the account's country. The Country Specs API makes
/// these rules available to your integration.
///
/// You can also view the information from this API call as <a
/// href="https://stripe.com/docs/connect/required-verification-information">an online
/// guide</a>.
/// </summary>
public class CountrySpec : StripeEntity<CountrySpec>, IHasId, IHasObject
{
/// <summary>
/// Unique identifier for the object. Represented as the ISO country code for this country.
/// </summary>
[JsonProperty("id")]
public string Id { get; set; }
/// <summary>
/// String representing the object's type. Objects of the same type share the same value.
/// </summary>
[JsonProperty("object")]
public string Object { get; set; }
/// <summary>
/// The default currency for this country. This applies to both payment methods and bank
/// accounts.
/// </summary>
[JsonProperty("default_currency")]
public string DefaultCurrency { get; set; }
/// <summary>
/// Currencies that can be accepted in the specific country (for transfers).
/// </summary>
[JsonProperty("supported_bank_account_currencies")]
public Dictionary<string, List<string>> SupportedBankAccountCurrencies { get; set; }
/// <summary>
/// Currencies that can be accepted in the specified country (for payments).
/// </summary>
[JsonProperty("supported_payment_currencies")]
public List<string> SupportedPaymentCurrencies { get; set; }
/// <summary>
/// Payment methods available in the specified country. You may need to enable some payment
/// methods (e.g., <a href="https://stripe.com/docs/ach">ACH</a>) on your account before
/// they appear in this list. The <c>stripe</c> payment method refers to <a
/// href="https://stripe.com/docs/connect/destination-charges">charging through your
/// platform</a>.
/// </summary>
[JsonProperty("supported_payment_methods")]
public List<string> SupportedPaymentMethods { get; set; }
/// <summary>
/// Countries that can accept transfers from the specified country.
/// </summary>
[JsonProperty("supported_transfer_countries")]
public List<string> SupportedTransferCountries { get; set; }
[JsonProperty("verification_fields")]
public Dictionary<string, Dictionary<string, List<string>>> VerificationFields { get; set; }
}
}
Source: https://github.com/stripe/stripe-dotnet/blob/3d8d1150c9136f3d5b78e8b9b803e858cda5fe53/src/Stripe.net/Entities/CountrySpecs/CountrySpec.cs
|
76391714 | 76391787 | I'm migrating from v5 to v6. It v6 it seems you can't use regexp anymore. Is there a quick workaround for a path like this? The problem is the dash, of course.
<Route path="/doc/:id-:version" />
| symbols in paths in React Router v6 | You can't use partial dynamic segments, it's all or nothing. Use a single param and then apply string splitting logic on it in the component.
Example:
<Route path="/doc/:idVersion" element={....} />
const { idVersion } = useParams();
const [id, version] = idVersion.split("-");
See Dynamic Segments for more information.
|
76390107 | 76390190 | If I have these types:
type Orange struct {
Size float32
}
type Lemon struct {
Color string
}
type Wood struct {
Variety string
}
And that interface:
type Fruit interface {
}
How do I declare that Orange and Lemon are Fruit,
so that, elsewhere, a function may return only things who are of kind Fruit?
(Fruit being a marker interface).
| How do you declare that a type belongs to a marker interface? | To declare that a type belongs to a marker interface in Go, you need to explicitly state that the type implements the interface. In your case, to declare that Orange and Lemon types are of kind Fruit, you can do the following:
type Fruit interface {
}
type Orange struct {
Size float32
}
func (o Orange) MethodOfFruit() {
// Implement any methods of Fruit interface if required
}
type Lemon struct {
Color string
}
func (l Lemon) MethodOfFruit()
{
// Implement any methods of Fruit interface if required
}
|
76391509 | 76391791 | I am aware that in a mock server feature file, it is possible to forward requests to a specific endpoint using karate.proceed(): https://karatelabs.github.io/karate/karate-netty/#karateproceed.
We recently decided to opt for Javascript mocks, as they enable us to write more complex business logic for simulating the API we consume. Is there out-of-the-box functionality equivalent to karate.proceed() that I can use in a JS mock? Is there a way I can invoke karate.proceed() within this mock? Or is one expected to write Javascript code to enable this functionality?
| API Mocking - How do I implement request forward while using a Javascript mock? | Great question, and yes there is no context.proceed(). You need to use context.http() and manually create a new request and handle the response. All the data you need will be on the request object. For example request.method will give you the HTTP method as a string.
This is indeed an un-documented part of Karate, yet to become "mainstream". Feel free to add a feature request for a context.proceed() that will auto-use the request in scope, that does sound useful. If you could contribute a PR or two that would be awesome :)
|
76380583 | 76388872 | I have set up a new project with vue3. I started working with some package implementations but then I realized my CSS written in component is not applied in HTML. Here is a very simple view example
<template>
<div>
<p class="asd">Hello</p>
</div>
</template>
<style>
.asd {
color: purple;
}
</style>
In the result, the text is not purple.
I have checked if it is overridden by some other css but no, it does not event show up in the styles screen of dev tools:
What I have tried and checked:
I have tried writing style as "p.asd {..." and adding an !important in the end. No change.
I have checked if I am working on the correct page by changing the text from "Hello" to "Hello World" and it changes, so I am working on the correct page.
I got a production build if it is a dev env issue, but no, got the same result from the built html.
I have tried moving CSS to App.vue instead, and surprisingly styling written there works but not in the views.
I have tried on a new browser for caching issues, no change.
I have tried adding scoped, no change.
I have tried adding script tags, no change. Script tags work fine, console.log script works, but still no styling update.
I have tried inline CSS and it works.
Here is my package.json:
"name": "new-project",
"version": "0.0.0",
"private": true,
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs --fix --ignore-path .gitignore",
"format": "prettier --write src/"
},
"dependencies": {
"express": "^4.18.2",
"firebase": "^9.22.1",
"pinia": "^2.0.36",
"vue": "^3.3.2",
"vue-router": "^4.2.0",
"vue-tel-input": "^8.1.1"
},
"devDependencies": {
"@rushstack/eslint-patch": "^1.2.0",
"@vitejs/plugin-vue": "^4.2.3",
"@vue/eslint-config-prettier": "^7.1.0",
"eslint": "^8.39.0",
"eslint-plugin-vue": "^9.11.0",
"prettier": "^2.8.8",
"vite": "^4.3.5",
"vite-plugin-webfont-dl": "^3.7.4"
}
}
codesandbox example: https://codesandbox.io/p/sandbox/github/ihsanser/vue-vite-style-bug/tree/master
I don't know if I am missing something very simple, but I could not figure out the reason for hours now.
| vue styling in view does not apply to html | The space character used in .asd { is not an actual space. It is a NBSP 1.
Replace it with an actual space and everything will work as expected. This is not related to Vue, the behavior would be the same in React, Angular, Svelte or vanilla.
See it working.
As a side-note, this shows how important a runnable mcve is. In your question, you posted the code with a space. Not sure if this is due to the NBSP > Space conversion made by the browser when rendering the current page's HTML or if you simply didn't copy/paste the code in question.
I suspect it's the first.
1 - encoding NBSP outputs %C2%A0, whereas encoding a normal space outputs %20
|
76390181 | 76390195 | So I was asked this question in interview that if I have a class A how do I restrict which classes will be able to extend A. For example if I want only class C and E to be able to extend A and classes B and D should not be able to do so. I mentioned about bounded wildcards in generics but I think that didn't answer the question. I am not aware about any new feature added in newer versions of Java. Please let me know what is the correct answer to that.
| How to control what classes can extend my class in Java | Sealed classes seems to be one method to restrict which classes can extend another. This feature is available since Java 17.
Contraints:
All permitted subclasses must belong to the same module as the sealed class.
Every permitted subclass must explicitly extend the sealed class.
Every permitted subclass must define a modifier: final, sealed, or non-sealed.
Example:
public abstract sealed class Vehicle permits Car, Truck {...}
This restricts that only classes Car or Truck can extend Vehicle.
|
76391528 | 76391798 |
id_start
id_end
1
2
2
3
3
4
I want to collect elements who are "connected" like [1, 2, 3, 4]. (in an array for example)
I tried a recursive query like:
WITH RECURSIVE q_rec AS (
SELECT id_start,
id_end
FROM my_table
UNION
SELECT t.id_start
t.id_end
FROM my_table t
INNER JOIN q_rec r ON r.id_start = t.id_end
)
SELECT *
FROM q_rec;
But how can I aggregate them in an array despite they are not in the same column ?
| PostgreSQL - Aggregate attributes from different columns recursively | Another approach gathers all ids in the recursive query, as a table. Then applies aggregation.
WITH RECURSIVE cte AS (
SELECT id_start AS first_id,
id_start AS id
FROM tab t1
WHERE NOT EXISTS(SELECT 1 FROM tab t2 WHERE t1.id_start = t2.id_end)
UNION ALL
SELECT cte.first_id,
tab.id_end
FROM cte
INNER JOIN tab
ON cte.id = tab.id_start
)
SELECT first_id,
ARRAY_AGG(id) AS ids
FROM cte
GROUP BY first_id
Output:
first_id
ids
1
[1,2,3,4]
Check the demo here.
|