QuestionId stringlengths 8 8 | AnswerId stringlengths 8 8 | QuestionBody stringlengths 91 22.3k | QuestionTitle stringlengths 17 149 | AnswerBody stringlengths 48 20.9k |
|---|---|---|---|---|
76378346 | 76378431 | Regular Expression for text box validation. I need to validate textbox. conditions like below
can enter numbers and letters.
need to avoid these characters !@#$%^&*+=
Currently i am using below regular expression. but it is not working.
<input type="text" pattern="^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$" />
can u help me t... | How to modify a regular expression to validate a text box with letters and numbers only, excluding certain characters like !@#$%^&*+= | The regulation expression you are currently using is for validate email addresses.
So you have to use a regular expression to validate textboxes, make it only contain letters and numbers and avoid the characters (!@#$%^&*+=).
^[a-zA-Z0-9]+$
This will match any strings that is a letter or a number. It will not match an... |
76378408 | 76378435 | I'm trying to create a blind auction. So basically it will ask for your name and then your bid. After that, it will ask if there are any bidders, if yes it will ask you the name and the bid price. But after you said yes the terminal will be cleaned. So that the other bidder can't see how much the other person bid, if I... | How can i add new key and value in a existing list | Here's a better way to organize things. Also, I'm not sure why you are creating a list of tuples of dictionaries. Why not just make data_base a dictionary and store the new entries as keys?
import os
data_base = []
while True:
name = input("What is your name?: ")
bid = input("What is your bid: $")
data_... |
76378340 | 76378439 | I'm getting error in Android Studio on second "cannot resolve symbol second" how to fix it so that it loops from 358 to 331 in this example?
package com.example.myapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import a... | How to repeat video with start and end time in Android Studio? | According to the source code, the signature of onCurrentSecond is
override fun onCurrentSecond(youTubePlayer: YouTubePlayer, second: Float)
You are not overriding it. It should be
@Override
public void onCurrentSecond(@NonNull YouTubePlayer youTubePlayer, float second) {
if(second >= 358) youTubePlayer.seekTo(331)... |
76378344 | 76378496 | How to use React functions in CodePen?
I wrote a react function in CodePem to test React hooks, however it constantly keeps reporting errors: Uncaught ReferenceError: require is not defined.
My Code:
import {useState, useEffect,useRef } from 'react';
function Test() {
const [count, setCount] = useState(0);
const p... | how to use react function in codepen? | You can add a package by adjusting the settings in your Pen.
Take a look at the following image for reference:
By doing so, it will automatically generate the necessary import statement:
import React, { useState, useEffect, useRef } from 'https://esm.sh/react@18.2.0';
import ReactDOM from 'https://esm.sh/react-dom@18.... |
76378323 | 76378505 | The code I currently have is this, in my views.py I can't figure out how to set up my search function. All other functions work.
models.py
class User(AbstractUser):
"""User can be Employee or Customer"""
class Business(models.Model):
business = models.CharField(max_length=50)
class BusinessOwner(models.Model)... | Search Customers that are part of the logged on User's Business? | Let's break this down into tasks. I'm using values() to limit the request to what we're interested in, as I can then use that result to filter further.
#First you want to get all the businesses the logged in user owns
#(Currently they can only own one, so you could use get rather than filter,
#but you might change that... |
76378468 | 76378523 | ALL,
I made a local branch in my fork a long time ago and pushed some changes to it. I then submitted a PR which was passed the CI build.
Now after some time I came back to the same machine I produced the PR but for some reason I didn't check which branch I was on and made couple of commits on the old branch and pushed... | Remove remote commits on the branch in GitHub | After some thought, my original answer is more complicated than strictly necessary, but I'll leave it below.
The easiest way to get your original branch back to its old state and keep the new commits is to create a new branch then reset the old branch and force push. It looks like this:
git checkout old-branch
git bran... |
76378419 | 76378558 | I am creating a google chrome extension. On the popup, I am displaying a leaderboard. However, I am new to JavaScript so I don't know how to properly use async. I am using chrome.storage to get stored scores to display on the leaderboard, then sending them from background.js to score.js. My issue is that, since chrome.... | How to use async properly to get chrome.storage? | It is simpler to work with Promises and async/await instead of callbacks. chrome.storage.sync.get returns a Promise if you do not pass a callback.
async function findScores(table, website) {
// ...
if (categories.includes("personal")) {
const response = await chrome.storage.sync.get([website]);
... |
76383950 | 76384028 | I have a text field and it has an onSubmit method, inside which I check for validation and then focus on another field, but for some reason the focus does not work
onSubmitted: (value) {
//print("ga test");
if (!widget.validator?.call(value)) {
setState(() {
showError = true;
... | How do I change the focus of the text field on Submit? | I did so and it worked
if (widget.validator != null) {
setState(() {
showError = !widget.validator?.call(value);
});
}
if (widget.nextFocus != null) {
FocusScope.of(context).requestFocus(widget.nextFocus);
}
|
76380624 | 76380646 | I have an application that was executing TestNG tests perfectly with maven, for example, when using a mvn clean install command.
Currently I have updated the application to start using Spring Boot 3.1.0, and now the tests are completely ignored. No tests are executed.
I am using a classic testng.xml file defined on the... | Testng test are ignored after upgrading to Sprint Boot 3 and maven-surefire-plugin 3.1.0 | Ok, I have found the "issue". Seems that the new versions of maven-surefire-plugin needs to include a surefire-testng extra plugin for executing it:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.1... |
76380600 | 76380785 | I'm using Okta provider to create okta_app_oauth and okta_app_group_assignments. My module looks like:
resource "okta_app_oauth" "app" {
label = var.label
type = var.type
grant_types = var.grant_types
redirect_uris = var.type != "service" ?... | Terragrunt - make dynamic group optional | You can make the block optional as follows:
dynamic "group" {
for_each = length(var.app_groups) > 0 : var.app_groups : []
content {
id = group.value["id"]
priority = group.value["priority"]
}
}
also your default value for app_groups should be:
variable "app_groups" {
description = "... |
76378487 | 76378586 | I have a table PetsTable:
Id
Type
key
value
1
"Cat"
10
5
1
"Cat"
9
2
2
"dog"
10
5
1
"Cat"
8
4
1
"Cat"
6
3
2
"dog"
8
4
2
"dog"
6
3
3
"Cat"
13
5
3
"Cat"
10
0
3
"Cat"
8
0
How to insert this data into a new table MyPets from PetsTable with these conditions:
Group by Id
Only select rows when i... | Group by and select rows based on if value combinations exist | One approach is to use window functions to evaluate your conditions, which you can then apply as conditions using a CTE.
This creates the data you desire, its then trivial to insert into a table of your choice.
create table Test (Id int, [Type] varchar(3), [Key] int, [Value] int);
insert into Test (Id, [Type], [Key], ... |
76380579 | 76380826 | For work I'm needing to connect to test nodes and establish a vnc connection so you can see the desktop remotely. It's a manual process with a bunch of commands that need to be executed in order. Perfect for automation using a bash script. The problem is that some commands need to be executed on the remote node after a... | How to store multiple commands in a bash variable (similar to cat otherscript.sh) | Well, you could do:
a="echo 'hello'\nsleep 2\necho world\n"
echo -e $a
# output-> echo 'hello'
# output-> sleep 2
# output-> echo world
echo -e $a | bash
# output-> hello
# waiting 2 secs
# output-> world
The -e in echo enables the interpretation of the \n.
|
76383957 | 76384041 | I have a demo Spring Integration project which is receiving Kafka messages, aggregating them, and then releasing them. I'm trying to add JdbcMessageStore to the project. The problem is that it failing with error:
Caused by: java.lang.IllegalArgumentException: Cannot store messages without an ID header
at org.spring... | How to set ID header in Spring Integration Kafka Message? | The KafkaMessageDrivenChannelAdapter has an option:
/**
* Set the message converter to use with a record-based consumer.
* @param messageConverter the converter.
*/
public void setRecordMessageConverter(RecordMessageConverter messageConverter) {
Where you can set a MessagingMessageConverter with:
/**
* Generate {@... |
76383902 | 76384109 | I have some SQL that does some manipulation to the data i.e. filling in empty columns.
SELECT *,
ModifiedLineData = CASE
WHEN Column2 = '' AND LineData NOT LIKE ',,,0,,,,0'
THEN CONCAT(STUFF(LineData, CHARINDEX(',', LineData, CHARINDEX(',', LineData) + 1), 0, '"No PO Number"'), ',""')
EL... | Concatenate onto Next Row | Given that you can't have consecutive NULL values, using LEAD/LAG should be suitable for this task. Without knowledge of your original data, we can work on your query and add on top two subqueries, last of which is optional:
the inner adds the information needed to the record successive to "Column2=NULL" records
the o... |
76378480 | 76378588 | I'm working through The Odin Project and I'm having trouble making my main content take up the rest of the space of the browser.
Right now it looks like this:
The 1px solid red border is as far as the main content goes. I have tried this but it's not allowing for a fixed header and footer. I have also tried some other... | How do I get my main content to take up the rest of the space left over after the header and footer? | You can use flex diplay on body instead of using instead of fixed on header and footer and make the body display flex with column direction, then for main-content all you need is to set flex: 1 and remove padding top, flex: 1 will make sure that main-content take any remaining space in the parent. Set the body height t... |
76384080 | 76384128 | For whatever reason, my Kotlin program won't initialize variables assigned inside a when statement. Here's the code:
import kotlin.random.Random
import kotlin.random.nextInt
val mood: String
when(Random.nextInt(1..2)) {
1 -> {
mood = "loud"
println("$mood")
}
2 -> {
mood = "quiet"
... | Can't initialize variables inside of when statement in Kotlin | In Kotlin, variables declared with the val keyword must be initialized at the point of declaration or in the constructor of the class. In your code, the mood variable is declared without an initial value, and you are trying to assign values to it inside the when statement. However, the compiler is unable to determine i... |
76380728 | 76380908 | My deep link works fine on Android and transfers information to the app, but it doesn't work on iOS
Firebase Link
https://dvzpl.com
my short link
https://dvzpl.com/6BG2
my domain
https://dovizpanel.com/
my associated domain
<dict>
<key>aps-environment</key>
<string>development</string>
<key>com.apple.dev... | Flutter Deep Link Firebase in iOS | If you are using a custom domain for firebase dynamic links follow the instructions below:
In your Xcode project's Info.plist file, create a key called FirebaseDynamicLinksCustomDomains and set it to your app's Dynamic Links URL prefixes. For example:
<key>FirebaseDynamicLinksCustomDomains</key>
<array>
<string>https... |
76384218 | 76384269 | my question is how can I toggle/display the "Some text" content on onClick individually?.
I can use different function and state for every div an it is working but I know this is not the correct way to do it .
Can you help me with this guys? Thanks
This is my code
function App() {
const [loaded, setLoaded] = useState... | How to toggle/display content individually in ReactJS | You could create a custom component for your card that handles the state for each card:
function Card() {
const [show, setShow] = useState(false);
const handleShow = () => {
setShow(state => !state);
};
return <div className={styles.card_container} onClick={handleShow}>
<h3>Title</h3>
... |
76383839 | 76384284 | The following query was used as part of a security audit to identify users with access to install/uninstall server plugins at the database level.
SELECT user, host FROM mysql.db WHERE db = 'mysql' and (insert_priv='y') or (delete_priv='y') or (insert_priv='y' and delete_priv='y');
I need to revoke that permission from... | Revoking permission to install plugins? | You are able to install plugins when you have INSERT permissions on the mysql.plugin table, see INSTALL PLUGIN:
To use INSTALL PLUGIN, you must have the INSERT privilege for the mysql.plugin table.
So when you have database wide INSERT permissions on the (internal administrative) database mysql, then you can install ... |
76378670 | 76378715 | I am new to pandas, I have this data frame:
df['educ1']
which gives
1 4
2 3
3 3
4 4
5 1
..
28461 3
28462 2
28463 3
28464 2
28465 4
Name: educ1, Length: 28465, dtype: int64
when I try querying with
dt=df[df.educ1 > 1]
It's working fine returning multiple rows, ... | pandas dataframe query not working with where | You likely have NaNs in many columns, try to subset:
df.where(college_grad_mask).dropna(subset=['educ1']).head()
Or better:
df[college_grad_mask].head()
|
76378383 | 76378734 | I'm learning tidymodels. The following code runs nicely:
library(tidyverse)
library(tidymodels)
# Draw a random sample of 2000 to try the models
set.seed(1234)
diamonds <- diamonds %>%
sample_n(2000)
diamonds_split <- initial_split(diamonds, prop = 0.80, strata="price")
diamonds_train <- training(diamonds_... | Problem when scoring new data -- tidymodels | This problem is related to log transform outcome variable in tidymodels workflow
For log transformations to the outcome, we strongly recommend that those transformation be done before you pass them to the recipe(). This is because you are not guaranteed to have an outcome when predicting (which is what happens when you... |
76380693 | 76380922 | Is it possible to name a term created in a formula? This is the scenario:
Create a toy dataset:
set.seed(67253)
n <- 100
x <- sample(c("A", "B", "C"), size = n, replace = TRUE)
y <- sapply(x, switch, A = 0, B = 2, C = 1) + rnorm(n, 2)
dat <- data.frame(x, y)
head(dat)
#> x y
#> 1 B 4.5014474
#> 2 C 4.0252796
... | How to name a term created in the formula when calling `lm()`? | adapted from the info in this comment : Rename model terms in lm object for forecasting
set.seed(67253)
n <- 100
x <- sample(c("A", "B", "C"), size = n, replace = TRUE)
y <- sapply(x, switch, A = 0, B = 2, C = 1) + rnorm(n, 2)
dat <- data.frame(x, y)
out <- lm(y ~ x, dat)
summary(out)
out2 <- lm(y ~ x2, transform(dat... |
76378708 | 76378750 | I am trying to translate a Stata code from a paper into R.
The Stata code looks like this:
g tau = year - temp2 if temp2 > temp3 & (bod<. | do<. | lnfcoli<.)
My R translation looks like this:
data <- data %>%
mutate(tau = if_else((temp2 > temp3) &
(is.na(bod) | is.na(do) | is.na(lnfcoli)), ... | Translating Stata to R yields different results | None of bod, do or lnfcoli are missing (NA), so your logic returns FALSE and returns NA_integer_ (false= in the if_else). Stata treats . or missing values as positive infinity, so that check is actually looking for not missing.
So the equivalent in R/dplyr is probably:
data %>%
mutate(
tau = if_else(
... |
76383859 | 76384297 | This c++ code cannot compile:
#include <iostream>
int main()
{
constexpr int kInt = 123;
struct LocalClass {
void func(){
const int b = std::max(kInt, 12);
// ^~~~
// error: use of local variable with automatic storage from containing function
... | Why sometimes local class cannot access constexpr variables defined in function scope | 1. odr-using local entities from nested function scopes
Note that kInt still has automatic storage duration - so it is a local entity as per:
6.1 Preamble [basic.pre]
(7) A local entity is a variable with automatic storage duration, [...]
In general local entities cannot be odr-used from nested function definitions ... |
76380850 | 76380929 | Let's say I have a React Select with a placeholder ('Selected Value: '), and I want to keep the placeholder and append it into the selected value so that it looks something like ('Selected Value: 1'). Is there any way to do it?
import Select from "react-select";
export default function App() {
const options = [
... | How do I keep and append placeholder text into the selected value in React Select? | you can accept my answer
import Select from "react-select";
import { useState } from "react";
export default function App() {
const [selectBoxValue, setSelectBoxValue] = useState('')
const options = [
{ value: 1, label: 1 },
{ value: 2, label: 2 },
{ value: 3, label: 3 },
{ value: 4, label: 4 }
]... |
76380934 | 76380982 | Installed FlareSolverr in docker.
cURL work correctly and return the correct response.
curl -L -X POST 'http://localhost:8191/v1' -H 'Content-Type: application/json' --data-raw '{
"cmd": "request.get",
"url":"http://google.com",
"maxTimeout": 60000
}'
but when using from python + flask I get an error - 405 Metho... | Method not allowed, flask, python | you are using a GET request in your python code. It should be a POST request. Use requests.post
|
76378592 | 76378760 | I was having this problem about last week in this code
a = int(input())
b = int(input())
c = int(input())
print(min(a+b,b+c,c+a))
so when I enter three input like this: 2 5 6 (three interger in 1 line)
It show me a error:
File "c:\Users\Administrator\Documents\Code\Python\baitap(LQDOJ)\EZMIN.py", line 1, in <module>... | Can't not write three value in 1 line | Method 1
The error you're encountering is because you're trying to convert the entire string '2 5 6' into an integer using the int() function. However, the int() function expects a single integer value, not a string containing multiple numbers.
code:
a = int(input())
b = int(input())
c = int(input())
x = a + b
y = b +... |
76383945 | 76384326 | I try to define a custom interfaces like this :
export interface IAPIRequest<B extends any, P extends any, Q extends any>
{
body: B;
params: P;
query: Q;
}
This type is supposed to be extended in a lot of other types for each request mu API is supposed to handle.
For example :
export interface ILoginRequest exte... | Typescript type extension | TypeScript doesn't automatically treat properties that accept undefined to be optional (although the converse, treating optional properties as accepting undefined, is true, unless you've enabled --exactOptionalPropertyTypes). There is a longstanding open feature request for this at microsoft/TypeScript#12400 (the titl... |
76380868 | 76380985 | This Quarkus mailer guide requires that the sending email is preconfigured in property file: quarkus.mailer.from=YOUREMAIL@gmail.com. However, my use case for email includes unique originator email based on user. Using the provided method looks something like:
public void sendEmail(EmailSender emailSender) {
// Se... | How to configure the Quarkus Mailer extension to allow dynamic 'from' email addresses based on user? | The documention showcases how to use multimailer (Multiple From Addresses)
quarkus.mailer.from=your-from-address@gmail.com
quarkus.mailer.host=smtp.gmail.com
quarkus.mailer.aws.from=your-from-address@gmail.com
quarkus.mailer.aws.host=${ses.smtp}
quarkus.mailer.aws.port=587
quarkus.mailer.sendgrid.from=your-from-add... |
76380847 | 76380988 | This is a question from rust onomicon # lifetime
The first example can compile, as x is a reference and the compiler can infer its lifetime as minimal as the last use here :println!(), so x is dropped after this line.
let mut data = vec![1, 2, 3];
let x = &data[0];
println!("{}", x);
// This is OK, x is no longer neede... | Why Drop trait is only executed at the end of the scope, instead of after the last use? | The primary reason is that it was once defined to be like that, and now changing it isn't possible any more because it wouldn't be backwards-compatible and might break stuff.
Your code is easily fixable by introducing a nested scope, though, which is (to my understanding) best practice in those situations:
#[derive(Deb... |
76384211 | 76384348 | I've a microservice architecture, and need some common logic.
When it's necessary to create a custom spring boot starter rather than create a new microservice?
| When it's necessary to create a custom spring boot starter rather than create a new microservice? | In my experience, creating a new microservice from the ground up is generally due to preventing any monoliths occurring. Microservices should generally have one job and then do it well. You don't want to muddy up the implementation and purpose of your microservice by adding unrelated operations.
There are many design p... |
76378628 | 76378769 | AttributeError: 'int' object has no attribute 'astype' in automatic WhatsApp message sender script
The following is an automated WhatsApp message sender script I partially developed. I tried the following script and it worked fine with an excel with 5 numbers in it. However, I tried upscaling it to 1700+ numbers, and ... | How to fix 'int' object has no attribute 'astype' error when sending WhatsApp messages to large number of contacts using Python and pandas? | Try using -
cellphone = str(data.loc[i,'Cellphone'])
I think loc returns a single element of type "numpy.int64", calling the "str" should be enough.
|
76378370 | 76378800 | I have two tables, one has course name and course ID. The second table has the ID of the students and the course ID they have taken. I need to find all the class ID’s of the classes a student hasn’t taken. For example, in table 2 student 03 has taken classes 01 and 02 but not 03 and 04 from table one. The course ID’s 0... | SQL How to return record ID's not included in table 2 from table 1 based off of user ID in table 2 | As per your current requirement below query will work
SELECT * FROM table1 t1
WHERE course_ID
NOT IN (SELECT course_ID FROM table2 WHERE user_ID =3)
If you have more records in table2 and if you need to populate more than one student's details then you have to use other logic
If you want to modify your q... |
76380967 | 76381059 | In T-Sql I am parsing JSON and using PIVOT.
Select * from (select [key],convert(varchar,[value])[value]
from openjson ('{"Name":"tew","TabTypeId":9,"Type":3}'))A
pivot(max(value) for [key] in ([Name],tabTypeId,[Type]))b
It is not treating tabTypeId as equal to TabTypeId. I am getting NULL for tabTypeId.
If I use ... | Why is SQL Server Pivot being case sensitive on TabTypeId instead of treating it as the actual column name? | It's not PIVOT that is case sensitive, it's the data returned from OPENJSON that is. If you check the data returned from it, you'll see that the column key is a binary collation:
SELECT name, system_type_name, collation_name
FROM sys.dm_exec_describe_first_result_set(N'SELECT [key], CONVERT(varchar, [value]) AS [value]... |
76384091 | 76384360 | I have a query here that uses four subqueries inside a single CTE, and each subquery is scanning every row of another CTE for each row in itself. I would think that this is very inefficient.
Are there any SQL optimizations that I can implement now that the proof of concept is finished?
I don't have write access to the ... | PSQL / SQL: Is it possible to further optimize this query with requiring write access to the database? | An obvious optimization is to eliminate redundant table scans. There isn't any need in preprocessed to query from all_users more than once. The following query uses COUNT with FILTER to gather the same statistics:
WITH datetable AS (SELECT GENERATE_SERIES(
DATE_TRUNC('week', (SELECT MIN(crea... |
76378322 | 76378801 | I cannot work out how to convert an int to a generic type containing complex128. Here is an example which doesn't compile unless the complex128 is commented out:
package main
import "fmt"
type val interface {
int64 | float64 | complex128
}
func f[V val](a, b V) (c V) {
q := calc()
return a * b * V(q)
}
... | How can I convert an int to a generic type containing complex128 in Go? | This one works but it needs to list every type in the switch statement:
func f[V val](a, b V) (c V) {
q := calc()
var temp any
switch any(c).(type) {
case complex128:
temp = complex(float64(q), 0)
case int64:
temp = int64(q)
default:
temp = float64(q)
}
return a ... |
76378721 | 76378829 | enter image description here
in wordpress and woocommerce Plugin
is there anyway to hide "Display Cart" button in wordpress mini card widget ?
i can hide "checkout" button individually but it seems theres no Special Css Class Fot "Display Card" buttun. ?!?!
| Hide 'Display Cart' button in WooCommerce mini cart widget | you can try this
add_action( 'woocommerce_widget_shopping_cart_buttons', 'bbloomer_remove_view_cart_minicart', 1 );
function bbloomer_remove_view_cart_minicart() {
remove_action( 'woocommerce_widget_shopping_cart_buttons', 'woocommerce_widget_shopping_cart_button_view_cart', 10 );
}
OR
.widget .woocommerce-mini... |
76378661 | 76378944 | I'm looking for the fastest way to parse a hex string representing a ulong into a uint keeping as many leading digits as a uint can handle and discarding the rest. For example,
string hex = "0xab54a9a1df8a0edb"; // 12345678991234567899
Should output: uint result = 1234567899;
I can do this by simply parsing the hex in... | The fastest way to convert a UInt64 hex string to a UInt32 value preserving as many leading digits as possible, i.e. truncation | For decimal truncation, all the high bits of the hex digit affect the low 9 or 10 decimal digits, so you need to convert the whole thing. Is there an algorithm to convert massive hex string to bytes stream QUICKLY? asm/C/C++ has C++ with SSE intrinsics. I commented there with some possible improvements to that, and t... |
76384304 | 76384361 | I am faced a problem. I have a project which is in firebase. I have used there firebase Authenticate, Firebase realtime database, Firebase function and some more. Now I have changed my decision. I want to make my own server where I will set up and manage everything.
So that I want to backup my project to move all data ... | How to backup a full project of firebase | You'll have to write code or use the CLI to query all of the data you want, and write it to a place you want. Firebase does not provide a tool to do all this automatically for an entire project. You will need to deal with each product's data separately.
You can use the Firebase Admin SDK or the Firebase CLI to access ... |
76378577 | 76378945 | I am trying to build a simple language translating program. I imported the 'language_converter' gem to aid with this goal. I wrote the following code:
require 'language_converter'
class Translator
def initialize
@to = 'ja';
@from = 'en';
end
def translate text
lc(text, @to,@fr... | Why does ruby recognise a method outside of a class, but not inside? | The gem is more than 10 years old and only has one method. And that method is implemented as a class method.
You are properly better off with just rewriting that method in your application with a modern Ruby syntax and proper error handling.
For reference, this it how lib/language_converter.rb in the gem looks like:
re... |
76384270 | 76384365 | In this example, I want the purple rectangle to change its opacity to 100% regardless of the value of the parent. I tried using all: unset/initial and !important but it doesn't seem to work.
.rect {
width: 500px;
height: 600px;
margin-top: 200px;
margin-left: 300px;
background-color: black;
/*... | How to override parent's styles in css? | So like Haworth pointed out, using opacity on the element itself brings all children under the influence of the pixelshading used to make the opacity effect.
If you want to get the same effect while retaining your html structure I'd recommend a different approach for the same result using RGBA or hex with an alpha chan... |
76378347 | 76378974 | I'm running a bat file in windows. I'm trying to generate a log file of all the output that appears in the command prompt, to have as a document.
Note, Not a log file of the contents of the bat file but of the command prompt that it outputs.
How would I do this? Thanks
| How to generate a log file of the windows prompt when I run a bat file | Redirecting to output is done by using > or appending to file using >>
for batch-file, we typically call them.
(call script.cmd)2>&1>"logfile.log"
or append
(call script.cmd)2>&1>>"logfile.log"
Note, 2>&1 2>&1 is redirecting the stderr stream 2 to the stdout stream 1, it is important here, seeing as you said you want... |
76384255 | 76384399 | I need to find out the value of "name" inside on the obj object. How can I find it without function invocation?
I wanna use just obj.isActive not obj.isActive()
let obj = {
name: "X Æ A-12 Musk",
isActive: function () {
return this.name.length > 4;
},
};
// and after a while I need to check if is active:
co... | calculate an object property based on the value of another property of the same object | If you do not want to have to call isActive as a function, you can use a getter.
const obj = {
name: "X Æ A-12 Musk",
get isActive () {
return this.name.length > 4;
},
};
console.log(obj.isActive);
|
76384220 | 76384400 | Source Data::
json_data = [{"studentid": 1, "name": "ABC", "subjects": ["Python", "Data Structures"]},
{"studentid": 2, "name": "PQR", "subjects": ["Java", "Operating System"]}]
Hardcoded_Val1 = 10
Hardcoded_Val2 = 20
Hardcoded_Val3 = str(datetime.datetime.now())
Need to create a flat .txt file with the ... | Code to format JSON data and append hardcoded data to create a flat .txt file | I would bypass using pandas for this and just build the string manually primarily using a list comprehension and join().
import datetime
import csv
Hardcoded_Val1 = 10
Hardcoded_Val2 = 20
Hardcoded_Val3 = str(datetime.date.today())
json_data = [
{"studentid": 1, "name": "ABC", "subjects": ["Python", "Data Structur... |
76380911 | 76381092 | Im making an application multi Language.
I want to build typing as strict and simpel as possible. My Code is the following:
//=== Inside my Hook: ===//
interface ITranslation {
[key:string]:[string, string]
}
const useTranslator = (translations:ITranslation) => {
const language = useLanguage() // just getting th... | Expect function Parameter to be Key of Object with Dynamic Properties | This solution will work only for Typescript >= 4.9 since it uses the satisfies operator introduced in the 4.9.
Adding as const is the approach we will go with, and satisfies will allow us to type-check it.
const translation = {
'something in english': ['something in german', 'something in spanish'],
'anotherthing i... |
76381023 | 76381114 | I have added a script for showing a div before different divs in different screen size. This is the code I used:
jQuery(function($){
jQuery(document).ready(function(){
jQuery(window).on('resize', function(){
if(jQuery(window).width() <= 1024){
jQuery( ".checkout.woocommerce-checkout .woocommerc... | jquery above and below screen sizes | Just put your code in a function and call it on the document ready:
$(function(){
resize();
$(window).on('resize', resize);
function resize(){
$( ".checkout.woocommerce-checkout .woocommerce-shipping-fields__wrapper" )
.insertBefore(
$(window).width() <= 1024 ?
".checkout.wooco... |
76378620 | 76378997 | I am trying to compare the QuickCheck library to the SmallCheck one. In SmallCheck I can reach particular value manipulating depth parameter. In QuickCheck:
>a<-generate (replicateM 10000 arbitrary) :: IO [Int]
>length a
10000
>maximum a
30
and my question then is: why are 10,000 "random" ("arbitrary") integers limite... | How is arbitrary distributed for Int? Why is it limited by so small values? | The documentation contains a clue:
The size passed to the generator is always 30
By default QuickCheck works by starting with 'easy' or 'small' inputs to see if it can find counterexamples with those. Only if it finds no problems with the small inputs does it gradually widen the range of generated input. The size val... |
76384387 | 76384457 | I have the following simple function (make) that calls the handle function and is supposed to retry a number of times whenever that function throws. If the retries are exhausted, the make function should throw the error.
const handle = async (): Promise<string> => 'hi';
const make = async (): Promise<string> => {
co... | How can I resolve the TypeScript error 'Function lacks ending return statement and return type does not include 'undefined'' in my code? |
My understanding is that the make function can only either return a string (inside the try block) or throw an error once the retries have been exhausted.
I'm fairly sure you're right, but TypeScript can't quite follow logic that complex, so it (incorrectly, I think) sees a path through the function that doesn't do an... |
76384356 | 76384460 | I am new to promql. So not sure if promql supports my requirement or not.
max_over_time(cbnode_systemstats_cpu_utilization_rate{instance="a",node="a"}[6h])
This above query gives me result of max cpu utilization in past 6 hr for instance a single instnace a.
However I want a query which fetches all metrics for all th... | How can i get all the metrics where two label have same values using promql? | There is no easy elegant way to do that.
But you can utilize label_replace, logic of label matching for binary operations and a pinch of ingenuity.
label_replace(cbnode_systemstats_cpu_utilization_rate{}, "pseudoid", "$1", "instance", "(.*)")
== label_replace(cbnode_systemstats_cpu_utilization_rate{}, "pseudoid", "$1"... |
76381015 | 76381115 | This is ItemManufactureController file
class ItemManufactureController extends Controller
{
public function index(){
return view('item_manufacture');
}
// Save category data into the database
public function store(Request $request){
$newManufacture = new ItemManufacture;
$newMa... | How to Save data to the Database using Laravel 8? | Please make your route as post since you're storing the data and change your route in chaining name() method as saveManufacture.store
Route::post('/save_manufacture', [ItemManufactureController::class, 'store'])->name('saveManufacture.store');
And in your blade file wrap your inputs inside form tag and set named route... |
76378362 | 76378998 | I am working with a chrome extension which uses webpack to build.
To build I use this : cross-env NODE_ENV=production yarn webpack -c webpack.config.js --mode production
webpack.config.js
const HTMLPlugin = require('html-webpack-plugin');
const CopyPlugin = require('copy-webpack-plugin');
const path = require('path');
... | Prevent webpack from auto-incrementing project version | This is caused by extension-build-webpack-plugin which you really shouldn't have struggled to find, as there's a total of 4 plugins there to look at.
No, it does not offer any method of avoiding version bumps. You can only configure if you want it to bump the major or minor version number, defaulting to minor.
It's a r... |
76384281 | 76384463 | I want to parse some data that's in a string format. Anything enclosed in parenthesis in the string to parse should be replaced with itself run through a function. This is what I want:
function foo(str) {
return parseInt(str) + 1; // Example function, not actually what the function will be
}
function parse(str) {
... | Javascript: run specific parts of strings through a function | Here's what I would do. I would match the string with a RegEx that would match anything inside parenthesis in the string. With that, I would then use str.replaceAll() to replace the matched string with the result of the foo() function.
const regex = /\((\d*)\)/gm;
function foo(str) {
return parseInt(str) + 1;
}
f... |
76381105 | 76381147 | I have a time series every which looks like this :
Time
Volume every minute
2023-05-25T00:00:00Z
284
2023-05-25T00:01:00Z
421
.
.
.
.
2023-05-27T23:58:00Z
894
2023-05-27T23:59:00Z
357
I have to make new CSV by iterating Time column finding unique date and making new columns with corresponding valu... | Find unique date from existing dataframe and make a new CSV with corresponding column values | First add parameter parse_dates to read_csv for convert Time column to datetimes:
train_data = pd.read_csv('date25to30.csv', parse_dates=['Time'])
Then create minutes by converting HH:MM:SS to timedeltas by to_timedelta and Series.dt.total_seconds, divide 60 and add 1 because python count from 0:
minutes = (pd.to_time... |
76378633 | 76379006 | I want to hide the AppBar on scroll. The search icon is hidden properly and also the opacity decreases on scroll. But for the title, it is not working.
import 'package:flutter/material.dart';
import 'package:vet_mobile/screens/chat.dart';
import 'package:vet_mobile/screens/logot.dart';
class HomeScreen extends Statele... | Cannot properly hide the appbar title on scroll in flutter | Seems that this effect does not work when you set a custom style. Remove the fixed style setting from here:
Text(
'PawCare',
// remove this
/*style: TextStyle(
color: Theme.of(context).textTheme.bodyLarge!.color,
),*/
),
To set the style of the title text, use the titleTextStyle configuration of SliverAppB... |
76378657 | 76379177 | I have the following algebraic data type:
data Tree a = Empty | Node a (Tree a) (Tree a)
deriving (Show, Eq)
Also, I have
data Step = StepL | StepR
deriving (Show, Eq)
Now, I need a function search that takes
a root of the tree
a target value t
... and it must return a path of type [Step] leading to a node with ... | Haskell: cache result of a function in pattern matching | The use of the word cache confused me, but if I understand the question correctly, the real problem is the repeated use of the same expression. That could certainly become a readability and maintainability issue in a larger code base, so is worthwhile addressing.
From the context this looks like a 'toy problem'. There'... |
76383893 | 76384507 | Python OOP problem
MultiKeyDict class, which is almost identical to the dict class. Creating an instance of MultiKeyDict class should be similar to creating an instance of dict class:
multikeydict1 = MultiKeyDict(x=1, y=2, z=3)
multikeydict2 = MultiKeyDict([('x', 1), ('y', 2), ('z', 3)])
print(multikeydict1['x']) # 1
... | Implement MultiKeyDict class in Python with alias() method for creating aliases. Existing code fails when original key is deleted. Need fix | Some remarks:
As the specification says that keys should have precedence over aliases (when both exist), you should first test key membership on self before looking in aliases. Your methods first check for membership in aliases...
As a value must continue to exist when a key is deleted for which there are still alias... |
76381091 | 76381163 | The scenario is the following:
type Option = 'a' | 'b' | 'c' | 'd'
type Question = {
message: string;
options: Option[];
default: Option // here's the issue
}
I want the default prop to be the one of the options used inside question.options. For example:
const q1: Question = {
message: 'first question',
opt... | Narrow down literal unions based on previously used values | It can be done just by using Question; however, it will be a complex type that will cause a horrible time for the compiler since it grows at the speed of power of two, and if you have more options (more than 10), the compiler will reach its limits and won't compile.
Instead, I would suggest adjusting Question to accept... |
76378693 | 76379413 | I want to make my NavigationBar transparent. I have tried extendBody: true on Scafold with surfaceTintColor=Colors.transparent to the NavigationBar widget, but nothing changed.
| How to create a transparent Material 3 NavigationBar in Flutter? | According to the document, SurfaceTintColor is the color of the surface tint overlay applied to the app bar's background color to indicate elevation.
If you want to make the AppBar transparent, just use the property backgroundColor instead.
Scaffold(
extendBody: true,
backgroundColor: Colors.white,
ap... |
76378332 | 76379520 | I am use library(tableone) to make my descriptive statistics for multiple variables
This is my code:
library(tableone)
myVars <- c("class", "age", "Sex", "bmi", "bmi_category",
"drink_freq", "smoke_yn", "edu_dummy")
catVars <- c("class", "Sex", "bmi_category",
"drink_freq", "smoke_yn", "edu_d... | How to use tableone to change table percentage by row? | With some clever getting-your-hands dirty, you can manipulate the percentages in the TableOne object. This uses an example dataset called pbc from survival package.
library(tableone)
library(survival)
data(pbc)
## Make categorical variables factors
varsToFactor <- c("status","trt","ascites","hepato","spiders","edema",... |
76384509 | 76384598 | In the code below, we have a dataset that can be read as: "two cooks cook1, cook2 are doing a competition. They have to make four dishes, each time with two given ingredients ingredient1, ingredient2. A jury has scored the dishes and the grades are stored in _score.
I want to use Altair to show a graph where the x-axis... | Altair: showing the value of the current point in the tooltip | cook1_score is not a column in df_melt, which is why you see the error. Setting tooltip=id_vars+['score'] will work.
|
76384490 | 76384624 | I have created a simple material app in flutter with:
flutter create --platforms=android,windows columntest
When I run the program on Android and Windows, I get some kind of padding between the ElevatedButtons on Android, but not on Windows. Do you know where this comes from and how I can make the design consistent?
Th... | Flutter: Inconsistent column padding on Buttons between Android and Windows | So, this implementation is done by flutter.
This is behaviour is because of the ThemeData.materialTapTargetSize parameter for the MaterialApp.
This feature decides what should be touchable dimensions of Material Button, in your case ElevatedButton.
You have 2 potential solutions
Change padding from ElevatedButton like... |
76378581 | 76379917 | In my Mojolicious Controller, I have:
my @promise;
foreach my $code (\&doit1, \&doit2,) {
my $prom = Mojo::Promise->new;
Mojo::IOLoop->subprocess(
sub {
my $r = $code->("Hello");
return $r;
},
sub {
my ($subprocess, $err, @res) = @_;
return $prom->reject($err) if $err... | Perl Mojolicious: Passing arguments to a code ref |
Now I converted doti1() and doit2() as helpers. So the code looks like:
foreach my $code (sub {$self->myhelper->doit1("Goodbye")},
sub {$self->myhelper->doit2("Good night")},
) {
#....
}
Yes but you are calling the helpers from another anonymous sub,
How can I continue to pass the same set... |
76378589 | 76381943 | I need to retrieve the attributes of a certificate that is stored in the keychain on my Mac from the command line. I can collect them manually from the Keychain Access app, but I want to do that with a script.
I used the security command to get a certificate and "grep" to inspect the "subject" section:
security find-c... | How can I parse the certificate information output from the security command in Mac? | As for the format, the certificates are stored in DER/PEM format, which is a representation of ASN.1 encoded data. What you see in the output is the hexadecimal representation of the ASN.1 binary data. The blob indicates that the value or attribute is stored as binary data.
As for exporting (for certificates), I would ... |
76384082 | 76384628 | I have two variables that I'm trying to model the relationship between and extract the residuals. The relationship between the two variables is clearly a non-linear exponential relationship. I've tried a few different approaches with nls, but I keep getting different error messages.
# dataset
df <- structure(list(y = ... | error messages fitting a non-linear exponential model between two variables | log-Gaussian GLM
As @Gregor Thomas suggests you could linearize your problem (fit a log-linear regression), at the cost of changing the error model. (Basic model diagnostics, i.e. a scale-location plot, suggest that this would be a much better statistical model!) However, you can do this efficiently without changing t... |
76382271 | 76382378 | I'm trying to insert the data inside a forall loop. For this case, I cannot use a temporary variable and set result of the function beforehand.
The function just maps a number to a string:
create or replace function GetInvoiceStatus(status number)
return nvarchar2
as
begin
case status
when 0 then return... | Function call as a parameter inside insert values statement | This error means that the parameter value (status) is not one of the cases in the case expression (which are 0, 200, 300).
If you executed this code select GetInvoiceStatus(555) as dd from dual you will get the same error. So, add ELSE clause like this:
create or replace function GetInvoiceStatus(status number)
ret... |
76384531 | 76384635 | I have a spreadsheet where I have an importrange and vlookup to another file where its looking up to a pivot table. Some data is blank in the pivot table and when I lookup in the formula, I have a result of blank even though I have set it to return to 0 by iferror.
Here's my formula:
=iferror(VLOOKUP(A5,importrange("12... | pivot returning blank instead of 0 google sheet | You may try:
=let(Σ,ifna(vlookup(A5,importrange("12PaJfEC7Q7gOcCx2zlMHG3YybQuk1TSsNjZDw26qFRg","Converted Pivot!A:E"),3,),"no_match_found"),
if(Σ="",0,Σ))
blank_value will now be shown as 0 & a non-match output error will be prompted with no_match_found
|
76380577 | 76381169 | I am trying to make a layout with:
A header (gray block in the snippet)
A body (lime borrder)
Main body content ( blocks with red border)
If you scroll horizontally, then the header should not scroll, it should be full width and stay in view. If you scroll vertically, then the header should scroll off the page as us... | Make an element not scroll horizontally | What I have done here is make header sticky to the left part of the screen. Its parent element must be aware of size of your content to allow header to move. So I set body min-width to min-content and same with main so it can transfer its children's size to body.
You also may notice I used box-sizing: border-box; in th... |
76382239 | 76382400 | I'm trying to create a small web application using Svelte.
One of the requirements is to be able to change the application "theme" on demand, for example - dark theme, light theme, high contrast, and so on.
I've been using an online mixin snippet to help me with that -
https://medium.com/@dmitriy.borodiy/easy-color-the... | "Unused CSS selector" when using a SASS themify mixin with Svelte and Vite: | You could try checking these different items:
If you use svelte-preprocess, try to add scss: { prependData: `@import 'src/styles/theme.scss';` } or whatever the path to your theme is, to the config object.
If it still does not work, maybe try to swap svelte-preprocess with vite-preprocess
Disable any potential css pur... |
76384567 | 76384661 | I learned 2 ways of inserting elements into a vector.
And I've been wondering which way is faster since I'm working with time limits.
Method 1:
int n;
cin>>n;
vector<int> v(n);
for(int i = 0;i<n;i++){
cin>>v[i];
}
Method 2:
int n;
cin>>n;
vector<int> v;
for(int i = 0;i<n;i++){
int x;
cin>>x;
v.push_back(x);
}
... | Is it faster to use push_back(x) or using an index (capacity)? | Both have issues:
You should be using reserve(n)
int n;
cin >> n;
vector<int> v;
v.reserve(n);
for(int i = 0; i < n; ++i){
int x;
cin >> x;
v.emplace_back(x);
}
In the first version: Setting size.
Here you have the issue that you are constructing all the elements in the array. Now for integers this may be... |
End of preview. Expand in Data Studio
This dataset is scraped from Stack-Overflow.
Loading the dataset
You can load the dataset like this:
from datasets import load_dataset
dataset = load_dataset("satoshi-2000/llms-suitable")
- Downloads last month
- 4