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 consec...
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(...
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::num...
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...
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('con...
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 = $_POS...
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 p...
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 ...
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...
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 constrai...
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 solu...
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...
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({ 'nam...
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: sc...
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()") pri...
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; Li...
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 MF...
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 M...
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) =...
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 ...
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 ((sub...
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_lin...
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: f...
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 aft...
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,...
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)...
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 ...
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 ...
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 ...
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 t...
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; ...
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...
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 $@ d...
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 exi...
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="con...
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 c...
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 a...
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 ...
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 th...
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 employe...
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 ...
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") Ho...
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:flutte...
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<TextEditingContr...
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 ...
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...
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, tes...
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])...
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 arrayOf...
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-02T...
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 ...
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 ...
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 ... ... .....
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 =...
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 ...
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 call...
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.Inter...
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...
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/.an...
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 thi...
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 ge...
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 t...
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 = FirebaseFirest...
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 do...
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 (compo...
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,...
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 ...
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 ne...
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/pre...
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 formul...
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 ...
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 = { ...
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...
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 wi...
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...
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, espec...
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_comp...
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 lo...
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": ...
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...
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/>}/> ...
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...
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 ...
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...
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 s...
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: boo...
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 ...
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 yo...
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...
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 = us...
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<-...
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 ...
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: 'final...
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.nam...
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...
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...
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 th...
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 requestPayl...
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 }; } ...
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 han...
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 savedInst...
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....
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 sub...
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(isDefa...
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 ...
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. ...
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. ...
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 su...
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...
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 canno...
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/...
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 re...
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 ...
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 compati...
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 w...
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 prom...
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 ...
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 defa...
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, Eve...
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 ...
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,...
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 th...
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 Framew...
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...
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....
76388597
76388771
Code first. <div data-a="a b" data-b="a&nbsp;b" id="test"></div> <div data-a="a<b" data-b="a&lt;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&nbsp;b" console.log('1:',test1_a===test1_b); //...
  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 &#32;. I updated your example using the 'non breaking spac...
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, ...
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 # run...
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\ ...
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, ...
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...
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": "sta...
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>", "field...
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');...
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 t...
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:...
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 m...
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 an...
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: fun...
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 st...
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 s...
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 i...
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...
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...
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 tha...
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 ...
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 r...
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 h...
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...
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 SecurityFilterCh...
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> ...
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 HRE...
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 cas...
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 ...
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) A...
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 fl...
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 tex...
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 "con...
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...
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 Stri...
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 informati...
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...
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()...
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...
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 ...
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 r...
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. I...
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...
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 ...
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...
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 F...