QuestionId stringlengths 8 8 | AnswerId stringlengths 8 8 | QuestionBody stringlengths 91 22.3k | QuestionTitle stringlengths 17 149 | AnswerBody stringlengths 48 20.9k |
|---|---|---|---|---|
76388802 | 76388888 | When overloading the new operator in a global scope in C++, are we just redefining the original functionality? From what I understand operator and function overloading works when the overloads have different signatures, however when overloading new operator using
void* operator new(size_t n){
return malloc(n);
}
w... | Does overloading the new operator in C++ redefine the operator? | operator new is replacable (from cppreference, same link):
The versions (1-4) are implicitly declared in each translation unit even if the header is not included. Versions (1-8) are replaceable: a user-provided non-member function with the same signature defined anywhere in the program, in any source file, replaces t... |
76389588 | 76390201 | I have a really wide table in Oracle that's at type 2 dimension.
Records have from_dates and to_dates with the latest 'current' records having a high end date of 31st Dec 9999. There are currently two partitions on the table, one for the 'current' records and one for 'history' records.
There's a new requirement to onl... | Oracle partition / archive strategy for type 2 dimension table | You aren't accomplishing much with merely two partitions, "current" and "history". You need to repartition this by month. Then you can implement a rolling partition drop of partitions older than 12 months, which will require a bit of scripting.
Normally we use interval partitioning INTERVAL(NUMTOYMINTERVAL(1,'MONTH')) ... |
76391632 | 76391801 | How to find the matching element in array from different array? in C#
I have different varities of products and dynamically created attributes of every variety
public class SingleVariety
{
[JsonProperty("varietyId")]
public int VarietyId { get; set; }
[JsonProperty("varietyName")]
... | How to find the matching element in a list from different list? in C# | One (flexible) way of doing this would be to chain your queries:
//Start with the whole set
var results = (IEnumerable<SingleVariety>)varities;
for (int i = 0; i < filterObject.Count; i++)
{
var filter = filterObject[i];
//Refine with each attribute match
results = results.Where(i => i.Attributes.FirstOrDe... |
76389895 | 76390260 | I need to change the Theme using stateprovider of flutter riverpod ,I dont understand what i did wrong here
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(const ProviderScope(child: MyApp()));
}
class MyApp extends ConsumerWidget {
const MyApp({super.key});
@override
Widget build(BuildContex... | The UI theme state is not updating until I resave the code while using flutter_riverpod stateprovider | Inside of MyApp class it should be
final isDarkTheme = ref.watch(isDarkThemeProvider);
And alternatively, inside your onTap you can toggle value like this:
onTap: () {
ref
.read(isDarkThemeProvider.notifier)
.update((state) => !state);
},
|
76388828 | 76388921 | I was unit testing in C#, and I found the following code gives an overflow exception:
using System;
public class Program
{
public static void Main()
{
int i = 0;
Console.WriteLine(new float[i - 1]);
// System.OverflowException: Arithmetic operation resulted in an ove... | Why does initializing a negatively-sized array cause an overflow exception? | This behaviour is explicitly specified in C# language specification, section 12.8.16.5
The result of evaluating an array creation expression is classified as
a value, namely a reference to the newly allocated array instance. The
run-time processing of an array creation expression consists of the
following steps:
(...)... |
76390204 | 76390266 | I am currently struggling with container queries. As long as I just use min-width and max-width everything is fine and works well. As soon as I try to use logic operators like and/or it doesn´t work anymore.
.wrapper {
width: 300px;
container-name: wrapper;
container-type: inline-size;
}
.box {
background-co... | how to use min-height, aspect-ratio, ... with container queries? | According to the docs:
The inline-size CSS property defines the horizontal or vertical size
of an element's block, depending on its writing mode. It corresponds
to either the width or the height property, depending on the value of
writing-mode.
– inline-size | MDN Web Docs
In your example, since writing-mode has the ... |
76391160 | 76391823 | I'm sorry if this sounds vague or idiotic, but consider the following:
if I have a main function like so:
int main(void)
{
int red_wins = 0;
game_loop(&red_wins);
// code
printf("red has %d wins\n", red_wins);
}
then have a a game_loop function which calls another function that uses red_wins:
void game_lo... | Does it make a difference to pass a pointer to a pointer as an argument or simply pass the first pointer? | You only need to pass a pointer to pointer in the following situations:
Where the called function is updating the pointer value, not the thing being pointed to:void update( T **p )
{
*p = new_TStar_value();
}
int main( void )
{
T *var;
update( &var ); // updates var
}
Where the pointer is pointing to the first ... |
76388620 | 76388953 | I'm on Windows, I try to run label-studio on a docker-img and enable automatic annotations with a tesseract machine learning model provided from label-studio-ml-backend on another docker-img. (I'm discovering docker these days...)
Set up:
So far I was able to launch a docker with label-studio, and a docker with tessera... | Connect 2 Docker images for label-studio | Add lbl-studio to tesseract's docker-compose file as third service. For connect from computer to services use http://127.0.0.1:9090 and http://127.0.0.1:9090. To connect between tesseract and lbl-studio use services name: http://lbl-studio:8080 and http://server:9090. Example:
version: "3.8"
services:
redis:
im... |
76391465 | 76391838 | In the uvicorn exmaple, one writes uvicorn filename:attributename and by that start the server. However, the interface I have generated has no such method attributename in filename. Therefore, I am unsure what to pass as attributename.
Generated code in main.py
"""
Somename
Specification for REST-API of somena... | How to start from example diverging REST interface? | The attribute name that you should specify is the name of the variable that holds your FastAPI instance. As they say in the docs:
The ASGI application should be specified in the form path.to.module:instance.path.
In this case for you, it would be uvicorn main:app where main.py is the file your code is in and app is t... |
76390244 | 76390337 | Trying to clear an MDList
New and trying to learn :)
I have a simple gui using kivy and kivymd.
one button adds a list of TwoLineListItem's
and i would like the other button to clear the previously generated list.
the idea is for one button to add the list, the other button to clear it
so i can populate the list and cl... | Trying to clear kivymd MDList | Use:
self.ids.List.clear_widgets()
instead of:
self.ids.List.remove_widget()
The clear_widgets() method removes all the children of the object. The remove_widget() method removes just one child (and that child must be specified).
|
76390299 | 76390358 | I would like to use the names of the INDEX factor in my FUN function in tapply.
My data and function are more complex but here is a simple reproducible example :
data <- data.frame(x <- c(4,5,6,2,3,5,8,1),
name = c("A","B","A","B","A","A","B","B"))
myfun <- function(x){paste("The mean of NAME is ", ... | R tapply : how to use INDEX names as a FUN additional argument? | One option would be to pass both the value and and the index column to your function:
data <- data.frame(
x = c(4, 5, 6, 2, 3, 5, 8, 1),
name = c("A", "B", "A", "B", "A", "A", "B", "B")
)
myfun <- function(x) {
sprintf("The mean of %s is %f", unique(x[[2]]), mean(x[[1]]))
}
tapply(data[c("x", "name")], data$nam... |
76388795 | 76388962 | In my code, I need to add the value of the specific checkbox that has been checked to the span element. The problem is it's first clicks of the checkbox, the calculation goes wrong.
As you can see, if you click a checkbox for the first time, it substract the value instead of adding it. Is there something I forgot to ad... | Incrementing/Decrementing a number using checkbox | It makes no sense that you are looping over all checkboxes each time, and then subtract the value of those that are not checked - because you never added the values of those in the first place.
Just keep working with the current cu value, and then either add or subtract the value of the currently changed checkbox only.... |
76391373 | 76391893 | Is there any way to use hard borders for RANGE?
The correct code is:
SELECT user_id,
created_at,
COUNT(*) OVER (ORDER BY created_at
RANGE BETWEEN '30 days' PRECEDING
AND '30 days' FOLLOWING) AS qty_in_period
But this sample is wrong:
SELECT user_id,... | SQL window function and (date+interval) as a border of range |
Is there any way to use hard borders for RANGE?
No. The documentation is explicit about it:
In the offset PRECEDING and offset FOLLOWING frame options, the offset must be an expression not containing any variables, aggregate functions, or window functions.
Attempting to use such syntax raises the following error:
... |
76390309 | 76390403 | Here's an easy algorithm question about stack and queue, could anyone please help me to look at what's wrong with my code?
Implement a queue with two stacks. The declaration of the queue is as follows. Implement its two functions appendTail and deleteHead, which perform the functions of inserting an integer at the end ... | Algorithm question - Stack and Queue - easy | There are two issues:
Comparing a list with 0 is not really useful, as that will never be true. To test whether a list is empty, you can use the not self.__stackA or len(self.__stackA) == 0, or a combination of the two.
When stack B is empty, but stack A has values, you should not transfer one element from the top of... |
76389693 | 76390406 | Here i attached the screenshot of the button when on hover take a effect like.
https://prnt.sc/xJSqNRU-IqdQ
I am try with skew effect but it doesnt work. I am also trying with skew effect but this doesn't work with button here. Let me provide the solution here.
.skew-button {
display: inline-block;
padding: 10px ... | Apply effect of button as per the attached screemshot on hover | The easiest way to do this, that I can think of, is the following. There are explanatory comments in the code:
/* simple reset to remove default margins and padding, and to
force all browsers to use the same algorithm for sizing
elements: */
*,
::before,
::after {
box-sizing: border-box;
margin: 0;
paddin... |
76391827 | 76391909 | There are two WAR files that rarely change and it should be running in my machine.
The tomcat path is /Users/myuser/Downloads/apache-tomcat-9.0.53 and the tomcat server in IntelliJ configuration use it also.
If I deploy the WARs in webapps directory, run another Java project that uses Tomcat in IntelliJ then I can't ac... | How to keep WAR files running in Tomcat while I'm using IntelliJ? | IntelliJ IDEA Tomcat run configuration has an option to deploy applications already present in webapps directory:
|
76391039 | 76391910 | I have been dealing with customer bill of materials that contains references with numbers that are separated by a dash, rather than the full sequence of references spelled out, e.g. C1-4 instead of C1, C2, C3, C4 or C1 C2 C3 C4
Some customers will use a comma to separate references, some only space, sometimes there is ... | Excel Macro for changing references with numbers separated by a dash into the full set of references | Another approach:
Sub Tester()
Dim c As Range, arr, el, txt As String, rv As String, sep As String
For Each c In Selection.Cells 'loop selected range
txt = Trim(c.Value)
If Len(txt) > 0 Then 'cell has a value?
arr = Split(Normalize(txt), " ")
rv = ""
... |
76388622 | 76388983 | I am a bit confused as how to interpret the dependencies list available on nuget.org and in the NuGet Package Manager in Visual Studio...
Sometimes, the list contains frameworks and a sub-list of dependencies per framework. Sometimes it does not contain the framework I have targeted for a particular project at all, how... | Understanding NuGet Package dependecies from Nuget.org | A package author can choose what target framework monikers (TFMs) to support; this can be diverse or ultra-specific. In this case (Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore), they have gone "specific", with the v6 versions of the library only targeting net6, v7 versions of the library only targeting net7, et... |
76388773 | 76389015 | Need an Input on the below XPath requirement:
XML:
<component>
<Bundle>
<entry>
<resource>
<Condition>
<id value="123456"/>
</Condition>
</resource>
<search>
<mode value="match"/>
</search>
... | Xpath: evaluate condition at parent node along with filtering duplicate entries | Consider the following example of Muenchian grouping:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:key name="k1" match="entry[search/mode/@value='match']" use="resour... |
76390149 | 76390411 | class ArticleResponse(
val id: Int,
val previewContent: String
)
fun ArticleResponse.mapToEntity() = Article(
id = id,
previewContent = previewContent,
content = null
)
class SingleArticleResponse(
val id: Int,
val content: String
)
fun SingleArticleResponse.mapToEntity() = Article(
i... | Android room: Don't override properties with null | I think the easiest and most robust way to do this is to have 6 separate update queries and run them all inside a transaction.
@Dao
interface ArticleDAO {
@Query("UPDATE Article SET content = :content WHERE id = :id")
suspend fun updateContent(id: Int, content: String)
@Query("UPDATE Article SET previewCon... |
76390317 | 76390432 | I'm trying to write a program that waits when it sees it's memory is becoming full. It finds out what the current available memory is using /proc/meminfo. Now I'm trying to test it by running systemd-run --scope -p MemoryMax=100M -p MemorySwapMax=0 but /proc/meminfo is still returning the old values (which I kind of ge... | systemd-run memory limit is not shown in /proc/meminfo, is there another way? | Systemd uses cgroups.
$ systemd-run -P --user -p MemoryMax=10240000 -p MemorySwapMax=0 bash -c 'd=/sys/fs/cgroup/$(cut -d: -f3 /proc/self/cgroup); tail $d/memory{.swap,}.max'
Running as unit: run-u923.service
==> /sys/fs/cgroup//user.slice/user-1000.slice/user@1000.service/app.slice/run-u923.service/memory.swap.max <==... |
76388859 | 76389025 | I have this router:
const router = createBrowserRouter(
[
{
path: '/',
element: <Navigate to={'/dashboards'}/>
},
{
path: '/dashboards',
element: <Dashboards/>,
loader: () => store.dispatch(retrieveWarehouses()),
children: [
{
path: ':warehouse',
... | How to render a subroute and trigger react router parents loader? | If the Dashboards component is rendered as a layout route then it necessarily should render an Outlet for its nested routes to render their content into.
Example:
import { Outlet } from 'react-router-dom';
const Dashboards: React.FC<any> = () => {
const {
warehouses,
loading
} = useAppSelector(selectWareho... |
76390643 | 76391915 | Consider this code
@Mapper
@RequiredArgsConstructor
public abstract class QuestionCommentMapper {
protected final QuestionService questionService;
public abstract QuestionComment dtoAndAuthenticationToQuestionComment(QuestionCommentRequestDto dto,
... | Is Mapstruct capable of passing a source object to an @AfterMapping method? | Mapstruct is capable of that with no extra code needed. Here's the generated method
@Override
public QuestionComment dtoAndAuthenticationToQuestionComment(QuestionCommentRequestDto dto, Authentication auth) {
if ( dto == null ) {
return null;
}
QuestionComment questionComment = ... |
76388819 | 76389035 | I need to retrieve a big amount of data.
I'm trying to order by 'id'. But the query returns an empty collection. if remove orderBy('id') it works properly.
How to sort by document id?
mQuery = docRef.orderBy('id')
.limit(bulk_size)
.get();
| Firebase firestore db orderBy document id | When you call .orderBy('id') it means that you trying to order the documents that you get from Firestore according to a field called id. If you want to order the documents according to the document ID, then please use:
mQuery = docRef.orderBy(firebase.firestore.FieldPath.documentId())
.limit(bulk_size)
... |
76390160 | 76390445 | I got a Dashboard model that is filled by a schduled Job.
dashboard model
class dashboard(models.Model):
topvul1=models.IntegerField(default=0)
topvul2=models.IntegerField(default=0)
topvul3=models.IntegerField(default=0)
I want to show the most found, second most found and third most found VID from the c... | DJANGO Get First, Second and Third most found Value in a Model | You can count the number of clientvuls for each vul and then order and return the first three:
from django.db.models import Count
vul.objects.alias(
num_client=Count('clientvul_set')
).order_by('-num_client')[:3]
there is no need to make a model for this. Unless we are talking about billions of records, such quer... |
76390300 | 76390453 | I have a loop that loads two float* arrays into __m256 vectors and processes them. Following this loop, I have code that loads the balance of values into the vectors and then processes them. So there is no alignment requirement on the function.
Here is the code that loads the balance of the data into the vectors:
size_... | Give the CLANG compiler a loop length assertion | You can use __builtin_assume to give the compiler constraint information that is not explicitly in the code. This should work for gcc and clang.
In the posted code, just replace the assert with __builtin_assume(bal < FLOATS_IN_M256).
|
76391255 | 76391923 | I have a data file having multiple date fields coming in string data type. I am trying to validate the date field and discard the records having wrong date format. Data looks like below.
schema = StructType([StructField("id",StringType(),True), \
StructField("dt1",StringType(),True), \
StructField("dt2",StringType(),Tr... | Date Validation in Pyspark | I think you can try to parse the date and then filter rows with None values, you can have a list of date columns to be more generic
from pyspark.sql.functions import coalesce, to_date, col
from pyspark.sql.types import StructField, StructType, StringType
schema = StructType([StructField("id",StringType(),True), \
Stru... |
76388794 | 76389049 | Suppose I've a simple model class:
public class Car
{
public string Make { get; init; }
public string Model { get; init; }
public string Year { get; init; }
}
In my ViewModel, I've two lists:
public class ViewModel
{
public ObservableCollection<Car> Cars { get; }
public List<Car> CanBeSold { get; }... | ListView Item - Generate column value based on criteria not part of Item's class | You may use a MultiBinding that contains a Binding to the CanBeSold property of the parent view model and a Binding to the current Car element.
<GridViewColumn Header="Can Be Sold">
<GridViewColumn.DisplayMemberBinding>
<MultiBinding>
<MultiBinding.Converter>
<local:ListElementCo... |
76389832 | 76390470 | Trying to add, subtract, two Series that contains datatype List[i64]. The operation seems to be not supported.
a = pl.Series("a",[[1,2],[2,3]])
b = pl.Series("b",[[4,5],[6,7]])
c = a+b
this gives the error:
PanicException: `add` operation not supported for dtype `list[i64]`
I would expect a element-wise sum, like wou... | Polars - How to add two series that contain lists as elements | you can do the following:
c = (a.explode() + b.explode()).reshape((2,-1)).alias('c')
shape: (2,)
Series: 'a' [list[i64]]
[
[5, 7]
[8, 10]
]
Final thoughts: if your list has a fixed size, then you might consider using the new Polars Array datatype.
|
76383169 | 76391967 | My API allows users to upload and download files to my Azure Storage account. To do this, they need a SAS token with permissions based on if they want to download or upload a file. I was wondering if there was a secure method to provide users with these tokens, other than sending it through more unsecure methods such a... | Is there a secure way to provide users with Shared Access Signature Tokens for Azure Storage containers? | Proposal 1: You can create a new Azure function as a proxy on your storage account for uploading/downloading. Thanks to managed identity, you won't have to provide a SAS token. User authorization on the Azure Function will ensure that the permission is removed when the user is no longer authorized.
Proposal 2: You can ... |
76387974 | 76389074 | I'm migrating old Quarkus project from RestEasy to ResteasyReactive and I have some difficulties migrating ResteasyContext.pushContext since there is no real 1:1 alternative in rest easy.
I'm using the ResteasyContext.pushContext in my ContainerRequestFilter to push some custom object to Context and later retrieve it u... | Migration from RestEasy to RestEasyReactive with ResteasyContext and ContainerRequestFilter | When using RESTEasy Reactive, there is a far easier way of doing things like this: just use a CDI request scoped bean.
Something like the following should be just fine:
@Singleton
public class CustomHttpRequestProducer {
@RequestScoped
@Unremovable
public CustomHttpRequest produce(HttpHeaders headers) {
... |
76391970 | 76392001 | I want to search for an index of the element in the ArrayList but I want to start searching from starting index different than 0.
I tried like this:
import java.util.*;
public class Test{
public static void main(String[] args) {
ArrayList<String> bricks = new ArrayList<String>(List.of("BBBB","CCCC","DDDD")... | How to find an index of the ArrayList from the starting index in Java? | Your code finds the index within the sublist.
To find the index within the original list, add the index used to create the sublist to the result:
System.out.println(bricks.subList(1, bricks.size()).indexOf("CCCC") + 1);
Some refactoring makes this clearer:
public static <T> int indexOfAfter(List<T> list, T item, int f... |
76388533 | 76389099 | I have a data loaded into Power Bi that look like this:
ID
TYPE
Product 1
Product 2
Product 3
1
A
1
1
0
1
B
0
0
1
2
A
0
1
1
2
B
1
0
1
3
A
1
0
0
So every column besides the "ID" and "TYPE" columns, is a binary 0/1 column, that indicates whether certain person acquire given product.
What I want to do,... | How do I create a single slicer from a group of columns | If you cant get a table with one product column before you connect to Power-BI and everything else fails you can to the following:
In the query editor create a new query and refer it to your table above
= YourTableName
So you get the table 3 times. Now for table one delete the columns 4 & 5, for table two delete column... |
76391852 | 76392026 | (if you are only interested in the problem, then go to "What if in short?")
What kind of stupid question?
I'm doing work and before that I built all graphics with x and I don't want to change the style.
And now I need a histogram, but it does not suit me with ggplot2.
What do I mean?
I took the width of the column from... | Recreate hist() binning in ggplot2 with geom_histogram() | Using your data, I believe this does what you want:
h <- hist(my_vector)
ggplot(data = data.frame(x = my_vector),aes(x = x)) +
stat_bin(geom = 'bar',breaks = h$breaks)
|
76388593 | 76389100 | There are a lot of topics around how can we configure the Jackson to ignore additional properties during the un-marshaller process. But I didn't find any answer how can we ignore it but also collect the unrecognized properties.
Our flow is: We would like to ignore them but collect all of the unrecognized properties in ... | Jackson ignore unrecognized property and collect the errors | Using override DeserializationProblemHandler.handleUnknownProperty get unknown property name?
public class IgnoreUnknownPropertiesHandler extends DeserializationProblemHandler {
@Override
public boolean handleUnknownProperty(DeserializationContext ctxt, JsonParser p, JsonDeserializer<?> deserial... |
76390394 | 76390482 | I use the * command to fill the search register (/) with the current word (under cursor) so I don't have to paste it into the substitute command.
To do a find and replace I can do it quickly like so:
:%s//MyNewValue/g
instead of
:%s/MyOldValue/MyNewValue/g
But sometimes I just want to change one character in the word... | Why nvim (vim) adds \< and \> to search pattern and what they means? | The \< and \> are word boundaries, see :help \< or :help \>.
This is similar to the "match whole word" checkbox in the search dialog of graphical editors.
For example, it will do the following:
Put the cursor on "foo" and press star.
It will match foo in this line.
But not foobar in this one.
If you don't want this, u... |
76388334 | 76389142 | I try to save data on Firebase but the data is stored in strange way although the value is string like this:
Description
"TextEditingController#d9024(TextEditingValue(text: ┤├, selection:
TextSelection.invalid, composing: TextRange(start: -1, end: -1)))"
Price
"TextEditingController#c11e0(TextEditingValue(text: ┤├, se... | Firestore save data in strange formation using Flutter | In order to get a text from the controller you need to use text property of TextEditingController
String? title = adTitleController.text.toString();
String? desc = adDescription.text.toString();
String? price = priceController.text.toString();
|
76391687 | 76392032 | I've got this TypeScript error and I don't fully understand what's going on:
src/helpers.ts:11:14 - error TS2322: Type '<T extends "horizontal" | "vertical" | undefined, U extends AriaRole | undefined>(ariaOrientation: T, role: U) => "horizontal" | "vertical" | NonNullable<T> | "both"' is not assignable to type 'Resolv... | Struggling to type a TypeScript function | Your ResolveOrientationFunction type definition,
type ResolveOrientationFunction = <
T extends HTMLAttributes<HTMLElement>["aria-orientation"],
U extends HTMLAttributes<HTMLElement>["role"]
>(
ariaOrientation: T,
role: U
) => "both" | NonNullable<T>;
is generic in both T, the type of ariaOrientation, and U, th... |
76390348 | 76390491 | I created a Website for my Wife's Blog in React and am hosting it on Firebase. I also use DB from firebase.
After the site release I found out that Google is not waiting until all data is finally loaded from the site to index the final site, but is trying to index a loading site.
For now I solved the issue with prerend... | Is there a way to make Google wait until all data is loaded for my React website hosted on Firebase with a DB from Firebase before indexing? | SEO is known problem of SPA websites built with front-end frameworks/libraries. The only options are to: prerender or use SSR (Server Side Rendering).
For your case, I would suggest using the second option since you want to have dynamic indexing depending on language.
When using SSR, you typically need a NodeJS server ... |
76388160 | 76389158 | I have a function
def test(self):
tech_line = self.env['tech_line']
allocated_technician = self.env['allocated_technician']
users = self.env['res.users']
tech_line = tech_line.search(
[('service_type_id', '=', self.service_type_id.id)])
al_a6 = self.env['tech_line... | search method optimization for searching field area in odoo15 | You can avoid searching in the for loop by using a search on all users:
def test(self):
tech_line = self.env['tech_line']
tech_lines = tech_line.search(
[('service_type_id', '=', self.service_type_id.id)])
# get all users to avoid search in a for loop
users = tech_lines.mapped("technician_alloci... |
76391751 | 76392039 | I have two datasets using r:
df_100= data.frame(siteid=c(seq(1,5,1),conflu=c(3,2,4,5,6),diflu=c(9,2,30,2,5))
df_full= data.frame(siteid=c(seq(1,10,2),conflu=c(6,3,5,2,3),diflu=c(5,9,2,30,7))
If the siteid is the same between df_100 and df_full, I want to take the difference between the conflu columns of each data fram... | if match between column ID in two different datasets, then create a new dataset with the difference of other columns r | I don't follow the calculations to get what you have as the sample output, but based on your description:
library(dplyr)
df_100 <- data.frame(siteid= seq(1,5,1),conflu=c(3,2,4,5,6),diflu=c(9,2,30,2,5))
df_full <- data.frame(siteid = seq(1,10,2),conflu=c(6,3,5,2,3),diflu=c(5,9,2,30,7))
df_difference <- df_100 |>
i... |
76391960 | 76392049 | I have a function here, where my intent is to add a record to the table. The column name is dynamically defined based on the firstCharVar variable.
The dataframe tblname is a blank table. The first character field in that table is called myvar. There are other columns in that table, and they should remain blank.
#up... | R Studio add_row with dynamic field name | As in other dpylr verbs you could assign values to dynamically created LHS names by using the walrus operator := and !!sym(col) or glue syntax "{col}".
Using a minimal reproducible example based on mtcars:
library(dplyr, warn=FALSE)
col <- "cyl"
mtcars |>
head() |>
add_row(cyl = 1) |>
add_row("{col}" := 2) |>... |
76390325 | 76390505 | I'm using mix-blend-mode to change the background color of an image. The problem I'm facing is that I've a grey-ish text which overlaps the background image intentionally when shown on a mobile device. This makes however the text unreadable. I've tried all variations of mix-blend-modes and believe my only option is to ... | Change rgb color of text on overlap | I believe your best shot would be to change the text color when you are on an mobile device. I've read your fiddle and you already have some @media zone defined. We can take advantage of that to add some CSS to change the text color whilst in mobile mode.
This block of code:
@media (min-width: 640px) and (max-width: 10... |
76391983 | 76392056 | I am using Spring Boot and Spring Data Elastic. I have an accounts index data like below
public interface AccountsRepository extends ElasticsearchRepository<Accounts, Long> {
List<Accounts> findByLastname(String lastname);
List<Accounts> findByAge(Integer age);
}
I am getting below error when perfor... | How to only get _source fields of elasticsearch using Spring Data Elastic? | You marked the property account_number of your entity, which is a Long, as the @Id. But the id in your index is a String (here with the value "KH-9fIgBhfTLJt8QzMP_").
Add proper id property:
@Id
private String id;
Edit: 03.06.2023:
As for the error
java.lang.ClassCastException: class org.springframework.data.domain.P... |
76388624 | 76389229 | I am relativly new to SQL and I have a short question. I already searched for similar questions in stackOverflow but I couldn't find anything.I have created some Views. These Views change from one Version to antother. To make migration easier for the customer, I want to filter differences in data_types of columns betwe... | How can I filter differences of datasets in a table | I think you can achieve this via "SELF JOIN". Join the tables with itself on "column_name" column.
Here is the code:
SELCT t1.versionsnummer, t1.install_timestamp, t1.column_name, t1.data_type
FROM [your_table_name] t1
JOIN [your_table_name] t2 ON t1.column_name = t2.column_name
WHERE t1.data_type <> t2.data_type;
Exa... |
76390367 | 76390507 | Have coded an emacs minor mode with the definition shown below.
Would it be possible to simplify this, to perhaps call a function instead? Or is it not such a big deal having a minor-mode defined in this way ?
What would be the general way to set a minor-mode in terms of functionality (e.g. enable, disable, ...) ?
(de... | Defining an emacs minor mode | I think you did it the proper way.
Next would be to toggle your minor mode in your emacs configuration file .emacs.d/init.el with a hook probably like this :
(add-hook 'org-mode-hook 'komis-luna-minor-mode)
If you want your minor mode to be enable when entering org-mode.
For further and more specifics questions and pr... |
76391607 | 76392057 | I'm trying to pass an array using extravars to the Ansible URI module.
% ansible-playbook someplaybook.yml -e '{ "letters": [ "aa", "ab", "ac", "ad", "ae" ] }'
When I run it through the URI module, I'm getting [ "['aa', 'ab', 'ac', 'ad', 'ae']" ] in the response. How do I send the entire array without the brackets and... | How to pass array to Ansible URI module | Your letters variable is a list, but when you write:
"{{ letters }}"
You are asking -- explicitly -- to render it as a simple string. You don't want that; you want to maintain the structure of the data. You can do that like this:
- name: Create a letter job
uri:
url: 'http://localhost:8000/api/app'
method: P... |
76388538 | 76389242 | I am using Java 17 and the iText pdf library (5.5.4), I'm currently attempting to write a paragraph on an existing pdf file inside a rectangular area, however I seem to have a NullPointerExeption when invoking the go() method, I'm not sure exactly why. I have included my code, any help would be appreciated.
public clas... | Cannot write a paragraph to a pdf file using iText pdf | I could reproduce your issue using your example file with iText 5.5.4. Then I tried again with the current 5.5.13.3. There was no issue. Thus, please update.
Comparing the 5.5.4 code (where the exception occurs) with the corrsponding 5.5.13.3 code, one sees that there indeed was an unconditional call of a method of a p... |
76380856 | 76389538 | I wrote this code to search a specific folder's text files for word matches and to specify them:
import re, os, sys
from pathlib import Path
#Usage: regs directory
try:
if len(sys.argv) == 2:
folder = sys.argv[1]
fList = os.listdir(folder)
uInput = input('input a regex: ')
regObj = ... | How can I replace matches in a Python regex with a modified version of the match? | I've figured out the answer:
using a lambda function as a repl= variable with re.sub i was capable of modifying the matches and then using them to substitute.
import re, os, sys
from pathlib import Path
#Usage:regs directory
try:
if len(sys.argv) == 2:
folder = sys.argv[1]
... |
76389533 | 76390559 | Does a Kafka cluster have some unique ID that I can get programmatically out of a Kafka consumer? I checked for message headers, but it looks like there's no metadata in them by default and I don't see any methods in a KafkaConsumer or ConsumerRecord for retrieving such a value either.
| Kafka consumer unique cluster ID? | You can use AdminClient to get the cluster id, but generally, there's no reason for clients to know internal server information
|
76390462 | 76390585 | I have a query for deployment table. There is no data for hotfix column now. I want to show all change count without hotfix and with hotfix for time intervals.
Table data:
deployTime
changeno
hotfix
2022-08
aaa
2022-08
bbb
2022-11
ccc
2023-01
ddd
First attempted query:
SELECT deployTime ... | How to return 0 for all time intervals instead of nothing when counting | The problem with your query is that you're using a WHERE clause, that removes records. What you should do instead, is apply conditional aggregation on presence/absence of hotfix values:
SELECT deployTime AS times ,
COUNT(DISTINCT changeno) FILTER(WHERE hotfix = '') AS "Change Count"
FROM deployments
GROUP B... |
76392054 | 76392081 | I have a table where each instance in the table is a sold ticket and tickets can have different ticket types. Looking something like this:
Event
Ticket Type
Event 1
a
Event 2
a
Event 1
b
Event 2
a
Event 1
a
I want it to be grouped by the event but displaying both the total tickets for that event as ... | How do I break down data that I am grouping by? | Yes, it is possible by using GROUP BY to group the event data and then calculating the totals. The following query works by counting the number of tickets, then counting the number of tickets for each type "a" and "b".
SELECT
Event,
COUNT(*) AS 'Total Tickets',
COUNT(CASE WHEN TicketType = 'a' THEN 1 END) ... |
76389631 | 76390588 | I'm trying to create a Client library that will allow users to push serialized data to a service.
so I created a class
public class Data
{
public string Prop1 {get; set;}
public SubData Prop2 {get; set;}
}
public abstract class SubData
{
public string Prop3 {get; set;}
}
I would like to allow users to extend... | Polymorphic serialization of property | As an alternative to the custom JsonConverter, you can replace the SubData property with generic
public class Data<TSubData>
where TSubData : SubData
{
public string Prop1 { get; set; }
public TSubData SubData { get; set; }
}
string SerializData<TSubData>(Data<TSubData> data)
where TSubData : SubData
{... |
76388586 | 76389618 | I have poor understanding in this question. The major step to distribute any application is the code signing, it signs application with dependant dynamic library. As I understand OS will check signed application during installation and subsequent calls. If application or dynamic library was changed then os rejects the ... | How to sign dylib file which can be replaced? | That's not how this works.
The signature of the library isn't going to matter if the entire library will be replaced. What matters is the signature of the main executable of the process, specifically whether it enforces library validation. But even if you disable library validation, that is likely only going to work fo... |
76392070 | 76392085 | So to make it very simple.
If I write print("Hello World") and run it on the RUN icon on top right corner it works perfectly fine.
And only then if I type in terminal python hello.py executes again just fine.
But if I change program to print("Hello to everybody") and I type in terminal python hello.py it execut... | Cannot run updated file from terminal of VSC, for Python | Are you saving the file after changing it? The Run button will run the code that is currently in the editor, while running it via python in the command line will run it from the saved file.
|
76391253 | 76392089 | I have a plugin written in Vue 2 that programmatically mounts a component onto existing app instance.
export default {
install (Vue) {
const component = new (Vue.extend(Component))()
const vm = component.$mount()
document.body.appendChild(vm.$el)
}
}
Trying to migrate this to Vue 3 and this is the clos... | Vue 3: Mount component onto existing app instance | Interesting problem! There is a discussion on the Vue GitHub and they created a module that you can use: mount-vue-component. I found it very helpful to look at the module's code, it does exactly what you want to do.
To instantiate the component, you have to create a VNode, which you can do with createVNode() (which is... |
76390122 | 76390602 | spsolve is then - sometimes - unable to find a solution.
Our teacher gave us test cases that we have to satisfy however I passed all of them but seems to fail the hidden test cases.
My code checks for the following: If they share a node and only those two resistors are connected then print SERIES else NEITHER. If their... | Matrix Circuit Analysis using Algorithms | Electron travel between Vdd and ground. The Dijkstra algorithm ( google it ) finds these routes. If two resisters are on the same route, they are in series.
Setup
LOOP over every pair of resisters
IF the ends of the two resistor are connected to the same nodes
- mark as parallel
Create adjacency list for resister... |
76390958 | 76392099 | Does a StatefulSet pod, when deleted or failed, get redeployed on the same worker node, or is it deployed on another available worker node?
Seeking clarification on the default behavior of StatefulSet pods in Kubernetes when they are deleted or failed whether they are rescheduled on the same worker node or on different... | Does a StatefulSet pod, when deleted or failed, get redeployed on the same worker node, or is it deployed on another available worker node? | By default, k8s will schedule a new pod on any 1 of the nodes which has sufficient CPU and memory resources available. If you specified any special conditions like Pod affinity, Pod affinity or Node affinity, k8s will follow them accordingly. Please check out this official document
|
76387953 | 76389700 | I am plotting 3D data using matplotlib==3.3.4:
fig = plt.figure(figsize=(15, 10))
ax = fig.gca(projection="3d")
ax.view_init(30, 0)
# facecolors is a 3D volume with some processing
ax.voxels(
x, y, z, facecolors[:, :, :, -1] != 0, facecolors=facecolors, shade=False
)
fig.canvas.draw()
image_flat = np.frombuffer(fi... | Image duplicated when using fig.canvas.tostring_rgb() | The NumPy array ordering is (rows, cols, ch). The code image_shape = (*fig.canvas.get_width_height(), 3) switches rows and cols, which leads to the output image being incorrectly shaped, which looks like two copies.
Replace image_shape = (*fig.canvas.get_width_height(), 3) with:
image_shape = (*fig.canvas.get_width_he... |
76389973 | 76390614 | Are there any elvis like operator in Ocaml ?
Any sort of optional chaining that return the right value when the left one is empty, a default value operator, like the |> operator with opposite effect.
If not what are the good practices ?
As an example of a use case :
let get_val val_1 val_2 =
if (val_1) then (val_1) ... | Are there any default value tricks / Elvis Operator in Ocaml? | First, in OCaml if ... then ... else ... is an expression and thus there is no needs to have a distinct ternary operator.
Second, OCaml has optional arguments.
If I guess correctly the supposed semantics of your get_val function, it can be written:
let default = []
let get_val ?(val_1=default) () = val_1
which gives ... |
76388435 | 76389815 | i am using axios on react to send http request to laravel backend. but cors prevent laravel to answer my request. i catch below error:
p://localhost/todo/laravel/public/api/test' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested reso... | send a get http request by axios on react to laravel 10 backend on localhost | try
'paths' => ['todo/*'],
I' not sure, that ['*'] is allowed
|
76387968 | 76389842 | Sometimes, in a Data JPA environment, when three queries occur in one method, one query does not work normally in DB.
@Transactional
public void method1(Log log){
Long userId = log.getUserId();
User user = userRepository.findById(userId).orElseThrow(RuntimeException::new)
BigDecimal point = Big... | Sometimes, in a Data JPA environment, when three queries occur in one method, one query does not work normally in DB | You can enable SQL logging and check what data is actually passed to the database.
One of the reason can be: @Transactional annotation doesn't work. You need to get a service from the Spring Context to allow Spring to wrap method1() with a proxy method to do dirty checking and save data.
@Transactional annotation is a ... |
76392047 | 76392103 | I am trying to write a mongo query to help produce a report from the data.
The documents look something like this:
[{
"DeviceType" : "A",
"DeviceStatus" : "On"
},
{
"Device Type" : "B",
"Device Status" : "On"
},
{
"DeviceType" : "A",
"DeviceStatus" : "Off"
},
{
"DeviceType" : "A",
"Devic... | How can I count over multiple fields in mongo? | You can use $cond + $eq to return either 1 or 0 to $sum operator:
db.collection.aggregate([
{
$group: {
_id: "$DeviceType",
DeviceStatusOnCount: { $sum: { $cond: [ { $eq: [ "$DeviceStatus", "On" ] }, 1, 0 ] } },
DeviceStatusOffCount: { $sum: { $cond: [ { $eq: [ "$DeviceStatus", "Off" ] }, 1, 0 ]... |
76390575 | 76390615 | (MacOS Monterey):
I have external hard disks with files written under Windows, using Cygwin rsync.
The files are perfectly readable under MacOS, but when I want to delete/overwrite them, quite some appear "locked" (operation not permitted when doing a rm) on MacOS. Using the Finder, I can remove the lock by getting the... | How to remove the "locked" flag (programmatically) | I just found the command to do so:
chflags nouchg FILENAME
The command is described here
|
76388274 | 76389975 | I have a scenario where my pipeline should update the app registration with an additional redirectUrl.
I have managed to extract the current web.redirectUris with the following:
existing_urls=$(az ad app show --id '<client-id>' --query "[web.redirectUris]" --output tsv)
I would like to achieve something like this
exis... | Updating web redirect uri of Azure AD app registration | Tried as shown :But got the same error:
az ad app show --id 1e7bxxx7830
existing_urls=$(az ad app show --id 1e7b8fxxxx830 --query "[web.redirectUris]")
az ad app update --id 1e7xxx0a7830 --web-redirect-uris "$existing_urls https://hostname.com/newCallback"
$updated_urls="$existing_urls https://hostname.com/newCallba... |
76390603 | 76390619 | I'm trying to find the closest value in a reference data frame but it is not outputting the correct row.
I am using the below data frame which is then used to find the relevant row corresponding to the closest value in column 'P' to a defined variable. For example if p = 0.22222 then the code should output row 2.
DF:
... | I'm trying to find the closest value in a reference data frame but it is not outputting the correct row. Where am I going wrong? | You need to use idxmin:
closest_p = (df['P']-p).abs().idxmin()
Output: 2
For the row: df.loc[(df['P']-p).abs().idxmin()]
A fix of your approach would have been to use sort_values (but it's less efficient):
closest_p = df.loc[(df['P']-p).abs().sort_values().index[0]]
|
76391811 | 76392128 | In this code
#include <type_traits>
#include <iostream>
template <class T>
void func(const T& a)
{
if constexpr(std::is_same_v<T,int>)
{
static_cast<void>(a);
}
else if constexpr(std::is_same_v<T,double>)
{
// oops forgot to use it here
}
else
{
}
}
int ... | Unused parameter warning in templated function with if constexpr | We can say that the parameter a is not fully unused, it's conditionally unused.
The C++ standard requires to generate diagnostic messages for ill-formed programs. Your program is not ill-formed. The C++ standard does not require compilers to generate other warnings at all. So it's up to the compiler vendor to decide ho... |
76391083 | 76392133 | I have a library, namely pfapack (1), that I want to use in rust. So the initial code is written in Fortran, but a C interface exists and works well. I want to make a Rust crate (2) that ships this code so I can use it in any other Rust project (3). Doing so, (3) gives an undefined symbol error.
I have written a build ... | Trouble with undefined symbols in Rust's ffi when using a C/Fortran library | The solution was quite simple and right under my nose. Note that the symbol not found does not have an ending underscore, as pfapack functions do after mangling. This was because I tried to do the bindings to the C interface and the pretty Rust functions in the same crate. Looking at the Rust book, https://doc.rust-lan... |
76390438 | 76390623 | I wonder why Apache Parquet writes metadata at the end of the file instead of the beginning?
In the official documentation of Apache Parquet, I found that Metadata is written after the data to allow for single pass writing.. Is the metadata written at the end to ensure the integrity of the file? I don't understand what... | Why metadata is written at the end of the file in Apache Parquet? | I think the main reason is so you can write bigger than memory data to the same file.
The meta data contains information about the schema of the data (type of the columns) and its shape (number of row groups, size of each row groups).
So in order to generate the metadata you need to know what the data is made of. This ... |
76387965 | 76390012 | We are trying to integrate NewRelic with our Fast API Service. It works fine when we are not providing numbers of worker in uvicorn config
if __name__ == "__main__":
# newrelic.agent.register_application()
import newrelic.agent
newrelic.agent.initialize()
print("api key ", os.environ.get("NEW_RELIC_LIC... | NewRelic Not working with multiple workers Fast API Uvicorn | The reason is the following: when you run uvicorn.run with only one process, it will start the server as a normal Python function. But, when you run with workers=n, uvicorn will start n new processes, and the original Python process will remain as an orchestrator between these. In these new processes, it will not start... |
76392029 | 76392136 | I am trying to open a C-file in Python by using the "subprocess"-module.
I cannot execute the program without triggering a 'FileNotFoundError', and if I put in the full path of the file, I get an 'Exec format error'.
I don't necessarily need to use the 'subprocess'-module, I just don't know of any other method.
The Pyt... | How can I open a C-file in Python using 'subprocess' without triggering an Exception? | You are passing the C source file itself, not the compiled executable (*.exe).
For further info if needed, C is not an interpreted/scripted language, so it cannot be run through its code file like other scripting languages (e.g. Python, Batch). It's a compiled language, meaning that it has to be run through a compiler ... |
76390211 | 76390625 | I am trying to scrape the medium website. Here is my code.
import requests
from bs4 import BeautifulSoup as bs
class Publication:
def __init__(self, publication):
self.publication = publication
self.headers = {'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chro... | WebScraping - BeautifulSoup Python | As Barry the Platipus mentions in a comment, the content you want is loaded via Javascript. A complicating factor is that this content is only loaded when you scroll the page, so even a naive Selenium-based solution like this will still return only the same set of results as your existing code:
from selenium import web... |
76390552 | 76390629 | I have a simple Django app to show the output of an SSH remote command.
views.py:
from django.http import HttpResponse
from subprocess import *
def index(request):
with open('/home/python/django/cron/sites.txt', 'r') as file:
for site in file:
# out = getoutput(f"ssh -o StrictHostKeyChecking=ac... | Python show output of remote SSH command in web page in Django | You're returning the CompletedProcess object instead of its output.
Try updating the run command to capture output by adding the optional parameter
out = run([...], capture_output=True)
AND changing the output to show the stdout instead of the object
return HttpResponse(out.stdout)
|
76392117 | 76392146 | sorry if this is a simplistic question or demonstrates some misunderstanding of HTML, this is my first time using it. If there's any missing info or stuff I should have included in the question, I'm happy to provide it.
I have a python program, app.py, and it calls and renders an HTML page. That HTML page contains a fe... | Can I pass a variable string into the "Value" attribute for a HTML input tag? | Flask's templates use the {{ val }} syntax:
Put the double curly brackets around Qty_Wheels:
<form action="/new" method="post">
<label for="qty_wheels">Number of wheels:</label>
<input type="text" name="qty_wheels" value = "{{ Qty_Wheels }}" />
<label for="flag_color">Colour of flag:</label>
<i... |
76388849 | 76390020 | I am working on a react project with the tailwind. I checked the inspection of Chrome and saw the same tailwinds variables multiple times. I thought maybe something is not working properly in our project and checked Shopify and it was the same, I wonder why it is working in this way?
Screenshots are taken from first pa... | Why does Tailwind declare CSS variables multiple times? | There are Tailwind CSS default variables defined for ::backdrop in a separate rule from the *, ::before, ::after rule for two reasons:
The *, ::before, ::after selector does not cover ::backdrop. As per tailwindlabs/tailwindcss#8526:
This PR adds the ::backdrop pseudo-element to our universal default rules, which fix... |
76389558 | 76390634 | I've started to play with middlewares, it's great !
Here's an example of how I can inject a middleware when calling endpoints /api/playlists or /api/playlists/:id (I edited the file src/api/playlist/routes/playlist.js).
module.exports = createCoreRouter('api::playlist.playlist', {
config: {
find: {
middlewares... | In Strapi V4, How should I register a middleware to alter the responses returned by /user or /user/:id? | I finally found out :
create the file src/extensions/user-permissions/strapi-server.js
This is mine. It registers a middleware for each of those endpoints:
GET /users/me : plugin::spiff-api.user-me
GET /users : plugin::spiff-api.user-find
GET /users/:id : plugin::spiff-api.user-find-one
("use strict");
module.exp... |
76392112 | 76392173 | I'm trying to create a game in which, Starting of the game I have to ask the user for 'How many times he wants to play' and the user input must be an integer.
So I write the code I shared below. But it doesn't work as I expected.
If anyone can help me to figure out what I did wrong it will be helpful to me.
Thanks in a... | Input validation with regular expression not working | The problem is you convert the number into the array, while you simply can do this by directly checking the input against regex. Here is my version of the problem
let playCount = 0;
let regxNum = /^[0-9]+$/; // Regular Expression to match all numbers between 0-9
let askPlayCount = () => {
playCount = Number(prompt... |
76392174 | 76392197 | I noticed this difference when comparing xxhash implementations in both Python and Java languages. Calculated hashes by xxhash library is the same as hexadecimal string, but they are different when I try to get calculated hash as an integer(or long) value.
I am sure that this is some kind of "endian" problem but I coul... | Java and Python return different values when converting the hexadecimal to long | You converted the BigInteger to long which is the reason for the difference. Because long is a signed 64-bits integer it overflows to a negative. If you just print the BigInteger as it is it gives the same result.
System.out.println(new BigInteger(hexString,16));
# 15154266338359012955
|
76388858 | 76390104 | library(terra)
library(RColorBrewer)
# sample polygon
p <- system.file("ex/lux.shp", package="terra")
p <- terra::vect(p)
# sample raster
r <- system.file("ex/elev.tif", package="terra")
r <- terra::rast(r)
r <- terra::crop(r, p , snap = "out", mask = T)
terra::plot(r,
col = brewer.pal(9, "pastel1"),
... | change the size and orientation of legend title while plotting raster | You can add text whereever you want. For example
library(terra)
p <- terra::vect(system.file("ex/lux.shp", package="terra"))
r <- terra::rast(system.file("ex/elev.tif", package="terra"))
plot(r, mar=c(3,3,3,6))
text(x=6.77, y=49.95, "Score", srt=-90, cex=2, xpd=NA, pos=4)
lines(p)
|
76392129 | 76392209 | When I learned React to build virtual DOM,I use the editor on babel's website,Why are the two editors turning different code?
Why are the two editors turning different code?
| Why is babel home page different from the editor in the online tool | In the editor tool screenshot we can see that the selected option for the "React Runtime" configuration is "Automatic", while Babel's website editor looks like it's using the "Classic" option.
The difference between both is documented in https://babeljs.io/docs/babel-plugin-transform-react-jsx
There is also this blog p... |
76389865 | 76390685 | When working with ConstraintValidators, we just need to define the class and constraint and Spring is able to detect the validators and instantiate them automatically, injecting any beans we ask for in the constructor.
How do I add my custom Spring Validators (https://docs.spring.io/spring-framework/docs/current/javado... | How to register custom Spring validator and have automatic dependency injection? | You have to let the controller to know which validator will validate your request. I use following code to find supported validators:
@ControllerAdvice
@AllArgsConstructor
public class ControllerAdvisor {
private final List<Validator> validators;
@InitBinder
public void initBinder(@NonNull final WebDataBi... |
76388494 | 76390287 | In a Kivy form i set 2 Recycleviews(A and B). I would add the item clicked in Recycleview A, to the RecycleView B, using a Python3 script:
from functools import partial
from kivy.app import App
from kivy.lang.builder import Builder
from kivy.uix.recycleview import RecycleView
class B(RecycleView):
def __init__(self... | Python3 - Kivy RecycleView's data Dictionary succefully updated, but not phisically the Widget | The main problem with your code is that the line:
b=B()
is creating a new instance of B that is unrelated to the instance of B that is created in your kv. So anything done to that new instance of B will have no effect on what you see on the screen.
There are many possible approaches to do what you want. Here is one:
F... |
76390793 | 76392258 | I am trying to compare different where statements in my Kusto query using Kusto Explorer app, so I would like to export the result from the Query Summary tab.
In case has a query or a way to export this manually, it would be awesome.
Is it possible?
| How to export results from Query Summary from Kusto Explorer | In Kusto.Explorer, if you switch to the QueryCompletionInformation tab in the result set, you can see & copy the QueryResourceConsumption payload
|
76390320 | 76390714 | I am trying to move my bot written using discord.py/pycord to github for easier access, and I accidentally pushed my bot tokn to the hub, thankfully discord reset it for me and nothing hapened.
Now i want to use GitHub repository secrets to prevent this from happening, but i am having some trouble when trying to import... | How do I include GitHub secrets in a python script? | - name: start bot
env:
TOKEN: ${{ secrets.SECRET }}
In the GitHub Action you named the variable secrets.SECRET but in environment variables you named it TOKEN. Either change the name of the environment variable to SECRET:
- name: start bot
env:
... |
76381802 | 76390352 | I'm using this html to have the user choose a color:
<input type="color" id="main-color" name="head" value="#15347d"">
Then I'm using a button to call my python function
button py-click="generate_color_schemes(False)" id="button-submit">Update!</button>
Works well. (generate_color_schemes() examines the Element("main-c... | Pyscript color input - triggers to soon | As you say, you've got the right syntax but the wrong event(s). Rather than listening for the click event, you can listen to the input event (which is dispatched every time the value of an input changes) or the change event (which is dispatched, in this case, when the color picker closes). To do this in PyScript (or to... |
76389003 | 76390723 | I have a compute shader which updates a storage image which is later sampled by a fragment shader within a render pass.
From khronos vulkan synchronization examples I know I can insert a pipeline barrier before the render pass to make sure the fragment shader samples the image without hazards. Note the example is modif... | How to synchronize a draw call with a dispatch call as late as possible? | You should put that in a subpass external dependency for the subpass you need to use it within. However, unless the rendering commands you want to overlap with the compute shader are in a prior subpass in the dependency graph, this probably won't give you any greater performance.
Note that not even dynamic rendering he... |
76392154 | 76392264 | Description:
I have a problem very similar to https://leetcode.com/problems/jump-game-ii/description/.
Apart from discovering the minimum steps to reach the end, I need to retrieve the winning path array.
The winning path that is needed for my problem must satisfy the rule that given path A like [0,2,4,7] there are not... | Find BFS best path array |
The winning path that is needed for my problem must satisfy the rule that given path A like [0,2,4,7] there are not any other paths with the same price (steps to the end, 3 in this case) whose nodes starting from the path's end has lower indexes.
I can produce all the paths with BFS and hence compare them but is the... |
76390601 | 76390737 | I am new to Spring Boot and I'm getting the following error when writing a login validationAPI:
Field userservice in com.Productwebsite.controller.UserController required a bean of type 'com.Productwebsite.service.UserService' that could not be found.
The injection point has the following annotations:
- @org.springfram... | spring boot application not working bean error | Add @ComponentScan to com.Productwebsite and restart the app.
@ComponentScan(basePackages = "com.Productwebsite")
@SpringBootApplication
public class YourMainClass{
...
}
Try the following, if the above changes do not work:
Change annotation by adding the bean name:
@Repository("userservice")
|
76388789 | 76390508 | Im using renderer function as below and want to hide/show specific checkcolumn-cells depending on variable record.data.hidden in my gridview.
{
xtype: 'checkcolumn',
renderer: function(value, metaData, record, rowIndex, colIndex, store, view) {
/*
if (record.data.hidden === true) {
// che... | How to hide/show specific Cell in Grid | You can use the metaData passed to the renderer function to apply styling to the cell element, see the documentation here.
One easy way is to set the display CSS property depending on your criteria. This will be applied to the HTML <td> element created by Ext JS for the cell.
Try this:
{
xtype: 'checkcolumn',
ren... |
76392232 | 76392265 | I'm trying to create a generic component in React TypeScript. Here is the code
interface Props<T> {
name: T;
}
function CheckChild<T>(props: Props<T>) {
return <div>My name is {props.name}</div>;
}
export default function Check() {
const name = "Alex";
return (
<div>
<CheckChild n... | Generic Component in React - Type is not assignable to type 'ReactNode'. But no error with JSON.stringify() | The reason why the type error disappears when you wrap props.name in JSON.stringify() is because JSON.stringify() converts the value to a string representation. In TypeScript, the type ReactNode represents the type of a valid React node, which can be a string, a number, a React component, an array, etc.
When you direct... |
76388077 | 76390533 | I want to get the data where I marked. But since I made the side collection a custom name (as you can see in the picture TbarRow and latpuldown), I cannot fetch the last data I want to reach. Actually, when I write the name of the collection by hand, I reach it, but I don't know how to fetch that name without writing i... | Fetch data Firestore Flutter | To get the array from the document, would be something like:
var array = snapshot.get('gunharaketisimleri') as List;
Then you can loop over the list to get the individual values.
|
76389459 | 76390741 | I am having real issues stubbing one particular thing using sinon. I have a simple function I am testing
const floatAPIModels = require("models/float/floatAPIModels");
const insertFloatData = async (databaseConnection, endpoint, endpointData) => {
try {
const floatModel = floatAPIModels(databaseConnection);
... | Stubbing Models contained within an Object | floatAPIModels is a function that returns { Person } object. There is no Person property on this function. That's why you got the error.
In order to stub the floatAPIModels function, I will use the proxyquire module to do this.
E.g.
model.js:
const { DataTypes } = require("sequelize");
const floatAPIModels = (sequeliz... |
76391788 | 76392266 | Write a program that determines for two nodes of a tree whether the first one is a parent of another.
Input data
The first line contains the number of vertices n (1 ≤ n ≤ 10^5) in a tree. The second line contains n numbers, the i-th one gives the vertex number of direct ancestor for the vertex i. If this value is zero,... | How do I resolve the time limit? | Your approach using a depth first search is inefficient. This in general will look at more than just the path from b to a though the "parent pointers" or to the root, if b is not a descendant of a.
Instead start the search at b and go to the parent node repeatedly until you find the root or a. This will only consider t... |
76387967 | 76390557 | I have this html/JS code that generates N tables based on user input. I'm trying to separate the content in pages of "A4" size and with no more that 6 tables within each page in order to give the option to print as PDF.
I'm using the built-in JS function window.print(). The issue is that when the browser opens up the p... | How to print as PDF all pages in HTML? | One problem is the hidden page overspill
so simply remove that such that all contents are eligible for printing. Note you may want to move hidden to just the button at print time.
And the 2nd is you may need a page-break-after: always;
when the table container blocks reach 6 to a page limit, so try add that in. Note ev... |
76390332 | 76390748 | Problem statement:
I want to experiment with different sequences for the routing through the selectOutput5 block.
Example:
Random (all 5 Outputs can be choosen by probability 0.2) (thats the easy part that i solved)
Fixed: (Output1: 6 agents, after those six agents, Output2: six agents and so on...
Do you have an idea ... | Fixed Output sequence for selectOutput5 | Set the "Use:" property in your SelectOutput5 block to "Exit number". Then you can define which exit to use.
For your example, I would create an int type variable named currExit and set the initial value to 1. Set the value of "Exit number [1..5]:" in your SelectOutput5 block to currExit and write this code to the "On ... |
76388627 | 76390717 | I have the following JDBC input:
input {
jdbc {
id => "mypipeline"
jdbc_driver_class => "com.mysql.jdbc.Driver"
jdbc_driver_library => "/usr/share/logstash/drivers/mysql-connector-j-8.0.32.jar"
jdbc_connection_string => "my-connection-string"
jdbc_password => "my-user"
jdbc_user => "my-pass"
... | Exception when executing JDBC query - Illegal instant due to time zone offset transition with Logstash | "Illegal instant due to time zone offset transition" - Istanbul does not currently change between daylight saving time and standard time, but it has done in the past.
It is currently observing what is effectively DST year-round - and has done so since March 27th 2016, when the clocks moved forward by 1 hour from a UCT ... |
76389709 | 76390777 | I have a Power BI table with a column called "hours". It can have different time records with following different formats:
PT5H15M{YearMonthDayTime}, PT0S{YearMonthDayTime}, PT5H15M, PT10H, etc.
How can I clean them up so that the hours are represented as numbers, for example, PT5H15M{YearMonthDayTime} would be 5,25 a... | Clean column with different time records in powerbi | You can achieve this in power query
Steps followed in Power Query
Extract Text between delimiters PT and H to populate Hours column. Change type to decimal
Extract Text between delimiters H and M to populate Minutes column. Change type to decimal
Replace Errors with zero. Replace all null values with zero.
Devide Minu... |
76391920 | 76392279 | So this was the question and I implemented it using python language but there is error in code and I am not able to fix it so please help. I am attaching code also.
def delete23(a):
for i in range(0, len(a) - 1):
for j in range(0, len(a) - 1):
if a[i] == a[j] and i != j:
a.pop(j)... | Write a Python program to remove duplicates from a list of integers, preserving order | To filter duplicates while preserving the order, a set of seen values is used quite often. The logic is very simple: if a value is not present yet in seen, the value is encountered for the first time.
lst = [1, 2, 3, 4, 4, 1, 7]
seen = set()
lst2 = []
for x in lst:
if x not in seen:
seen.add(x)
lst... |
76388344 | 76390724 | The below code generates a plot and 4PL curve fit, but the fit is poor at lower values. This error can usually be addressed by ading a 1/y^2 weighting, but I dont know how to do it in this instance. Adding sigma=1/Y_data**2 to the fit just makes it worse.
from scipy.optimize import curve_fit
import matplotlib.pyplot as... | Apply a weighting to a 4 parameter regression curvefit | Don't add inverse square weights; fit in the log domain. Always add bounds. And in this case, curve_fit doesn't do a very good job; consider instead minimize.
import numpy as np
from scipy.optimize import curve_fit, minimize
import matplotlib.pyplot as plt
def fourPL(x: np.ndarray, a: float, b: float, c: float, d: fl... |
76392252 | 76392286 | I am currently developing a multi-threaded application in C++ where different threads are expected to process data from a shared data structure. I'm aware that the standard library provides std::future and std::async to easily handle asynchronous operations, and I'm trying to use these in my application.
Here's a simpl... | Multithreading with std::future in C++: Accessing shared data | If the data is readonly (and its not too much, just copy it).
Otherwise make a shared_ptr to your data (and using a lambda expression) you can capture the shared_ptr by value (! not reference!!!) This will extend the lifetime of the data to the lifetime of the thread that uses it longest. So something like this :
std::... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.