QuestionId stringlengths 8 8 | AnswerId stringlengths 8 8 | QuestionBody stringlengths 91 22.3k | QuestionTitle stringlengths 17 149 | AnswerBody stringlengths 48 20.9k |
|---|---|---|---|---|
76387405 | 76387433 | Let's imagine a situation where we have a queue positioned before the seize block, and this queue has the timeout property activated.
In such cases, it is important to note that the seizure queue cannot be reduced to zero. The seize queue always has a minimum capacity of 1. If the seize queue capacity were set to 1, on... | Why seize queue cant be zero in AnyLogic | You can manually avoid having agents in the Seize queue by using a Hold block upstream and only releasing agents into the Seize block if its queue is empty.
|
76382756 | 76385488 | I'm looking to find an efficient method of matching all values of vector x in vector y rather than just the first position, as is returned by match(). What I'm after essentially is the default behavior of pmatch() but without partial matching:
x <- c(3L, 1L, 2L, 3L, 3L, 2L)
y <- c(3L, 3L, 3L, 3L, 1L, 3L)
Expected out... | Efficiently match all values of a vector in another vector | A variant in base using split.
split the indices of both vectors by its value. Subset the second list with the names of the first, that both have the same order. Change NULL to NA and bring the lengths of the second list to those from the first. Reorder the indices of the second list by those of the first.
x <- c(3L, 1... |
76378680 | 76385544 | I'm trying to extract a couple of elements from XML files into an R dataframe but the parent nodes are all named the same, so I don't know how to associate child elements. I'm very new to xml (about 3 hours) so apologies if I use the wrong terminology. I did not find any R-based solutions.
This is the general structure... | R - How to rename xml parent node based on child element (or associate child elements)? | I have previously used xml_find_all() for this kind of simple conversion.
This works as long as each Annotation node always has exactly
one ObjIndex and MicronLength child node:
library(xml2)
xml <- read_xml("
<Annotations>
<Version>1.0.0.0</Version>
<Annotation>
<MicronLength>14.1593438418</MicronLeng... |
76387362 | 76387470 | How to set UID and GID for the container when Python SDK is used to spin up the container?
| How to set UID and GID for the container using python sdk? | As the documentation you've linked says, pass in user and group_add to run():
client.containers.run('alpine', 'echo hello world', user='foo', group_add=[123])
Both accept both IDs and names, but group_add needs to be a list.
|
76387121 | 76387471 | I want to center a text vertically such that the highest point of the text and the lowest point of text are on equal distance from the ending div that it is enclosed in.
I have the following css code:
padding-left: 30px;
font-family: 'Playfair Display', serif;
font-weight: 100;
width: 140%;
line-height: 68px;
color: #f... | How to align text vertically according to the highest point of the text and lowest point? | This can only be done by adding padding at the bottom or Top and this may vary as per different Fonts. I question is why do you want to do this? As anigning center as per your way would further discurb the balance.
Also, The positioning of certain letters, such as "p," "g," "y," and "q," are lower than the center line ... |
76388879 | 76388972 | Whenever I change the minutes on the timer it works perfectly, but when I change the seconds on the timer, no matter what, it instantly stops. I'm not sure what I'm doing wrong. This program is apart of a codepen exercise. When I had the timer on a countdown setting it worked perfectly, but when I changed it to countup... | Timer isn't dealing with seconds properly | You don't set the limit correctly - you set it directly to the content of the timer, which includes non numeric characters such as ":". When using parseInt on something that isn't all digits, anything after the first non numeric character is discarded. Therefore, by using anything under a minute to test with, limit wil... |
76383134 | 76385590 | The program runs multiple commands that require sudo privileges (such as sudo dnf update). Since the program should be installed using the go install command, it can't be run as sudo its self without configuration done by the user (afaik).
The program doesn't show the output to the user to keep the output clean. To sho... | Is it possible to run a sudo command in go without running the program itsself as sudo | _, err := exec.Command(os.Getenv("SHELL"), "-c", "sudo dnf update -y").Output()
In this exapmle, with adding sudo before the command that you want run as sudo, and after running the program, will ask password for sudo, If you apply this to your example code you can't see password request message, because the spinner gr... |
76387535 | 76387552 | When trying to install sui binaries using
cargo install --locked --git https://github.com/MystenLabs/sui.git --branch devnet sui
as suggested by the official docs,
gives the below error
Updating git repository `https://github.com/MystenLabs/sui.git`
error: could not find `sui` in https://github.com/MystenLabs/sui.git... | error: could not find `sui` in https://github.com/MystenLabs/sui.git?branch=devnet with version `*` | I used the below command which includes the tag to install it
cargo install --locked --git https://github.com/MystenLabs/sui.git --branch devnet --tag devnet-<version> sui
where you can replace version as required (e.g v1.3.0)
|
76387474 | 76387579 | I am observing this weird behavior when I am raising an integer to the negative power using an np.array. Specifically, I am doing
import numpy as np
a = 10**(np.arange(-1, -8, -1))
and it results in the following error.
ValueError: Integers to negative integer powers are not allowed.
This is strange as the code 10*... | Wierd behavior with raising intgers to the negative powers in python | This is happening because the input 10 is an integer.
10**(np.arange(-1, -8, -1))
numpy.arange() is designed such a way that that has to give 10**(np.arange(-1, -8, -1)) integers or nothing since input is an integer.
On the contrary;
a = 10.**(np.arange(-1, -8, -1)
gives results happily as 10.0 is a float
Edit: foun... |
76383413 | 76385687 | I have two classes in my Database in Django
class Test(models.Model):
sequenzaTest = models.ForeignKey("SequenzaMovimento", null=True, on_delete=models.SET_NULL)
class SequenzaMovimento(models.Model):
nomeSequenza = models.CharField(max_length=50, blank=False, null=False)
serieDiMovimenti = models.TextFiel... | Get value of a field from a foreigKey in Django Models | This should work:
try:
testo_sequenza = Test.objects.get(pk=idObj)
except Test.DoesNotExist:
# do here what you need the program to do if not found. maybe a return if function or a continue/break if you're in a loop
print("Testo Sequenza not found")
sequenza_test = testo_sequenza.sequenzaTest
serie_di_movim... |
76388965 | 76389014 | I am looking to programmatically apply a typically infixed operation (eg: +, -, *, /) on two integers, where the operation is specified via a string. I have had success accessing the method itself using .method
This is a pattern that works, 1.+(2) which correctly resolves to 3
By extension, I'd to define a way that cou... | How to use integer methods using `method`, not their infix form, in Ruby | The Method class has several instance method of it's own. The one you're looking for here is call
It is also aliased to [] and ===
1.method('+').call(2) #=> 3
1.method('+')[2] #=> 3
1.method('+') === 2 #=> 3
|
76387189 | 76387609 | I am attempting to install an R package named 'infercna', the github repository to which is linked here.
The install process attempts to load another package named 'scalop', which is linked here.
Specifically, this command:
devtools::install_github("jlaffy/infercna")
returns
Downloading GitHub repo jlaffy/infercna@HEA... | Fatal error relating to "include S.h" when installing R 'scalop' package | The "S.h" headers file is from the "S" language (the precursor to R); replacing "S.h" with "R.h" fixes the 'cant find S.h' error, but causes other issues. Clearly this package is not being maintained :(
I've forked the repository and made a couple of changes to the source code (commits fe15cf9 and ab9fe5c). I successfu... |
76383296 | 76385696 | I have searched widely but not found an answer to this question:
Is it possible to change a variable in a Jetpack compose user interface from a broadcast receiver?
| Broadcast receiver change UI | You can't modify your compose ui from Broadcast receiver directly. Instead, your Broadcast receiver should change some data in your data layer - datastore, preferences, database or just in memory in some Repository singleton class. Then you should make this data observable and observe them from your compose ui.
|
76389017 | 76389067 | I have a template function
template <typename B, typename A>
B func(A x) {/*do something*/}
And in my code I am doing something like
uint32_t a[6] = {1,2,3,4,5,6};
uint64_t b = func(a);
But this fails with
test.cxx:10:16: error: no matching function for call to 'func'
uint64_t b = func(a);
^~~~~~~~~
... | Automatic template argument deduction fails for return type | If the argument cannot be deduced from func(a); then it cannot be deduced. auto return type can be deduced from the return statement, but not here. What you assign the return value to is not relevant. It simply doesnt work like this.
It does work however with a templated conversion:
#include <iostream>
#include <cstdio... |
76381199 | 76387620 | I am on a learning curve with Kubernetes and recently started working with K3D. I am trying to deploy my project on a local K3D cluster. When I created a pod to run an application, I saw it hang in the pending state for some time, and below is the kubectl describe pod output (events).
application.yaml file's resource ... | How to increase allocated memory in a k3d cluster | Assuming the machine where you are running has more than 3GB of RAM (you can check by running lsmem or free), you can try re-creating the Kubernetes cluster using k3d, by passing an explicit memory limit. E.g.
k3d cluster create --agents-memory 8G
Or if you are doing a multi-node deployment, by adding a node with suff... |
76382660 | 76385756 | I'm writing a small interface in PyQT5 that has a graph that I use PyQtGraph to create. The graph starts to be drawn by pressing the "Start" button, and at first everything looks fine:
But over time and an increase in the number of points, the entire graph shrinks to the width of the screen and becomes not informative:... | update PyqtGraph plot in PyQt5 |
step 1: add the PlotCurveItems as members of Mainwindow, set them up in the constructor, so you can access them later
step 2: in the draw_graph function use the getData() and setData() functions of the PlotcurveItems, update them
step 3: if you have enough x-values set the xRange, so not all data is shown, I use a max... |
76388928 | 76389086 | The following is a minimum example code with the problem.
struct TestView: View {
@State var text = "Hello"
let useCase = TestUseCase()
init() {
useCase.output = self
}
var body: some View {
Text(text)
.onAppear {
// β useCase.output = self
... | Can not update @State variable via delegate set in View.init() | SwiftUI views are structs, and therefore immutable. Whenever a SwiftUI changes, a new instance of that view struct is created.
When you update text, SwiftUI needs to create a new instance of TestView. But, the new instance has text set to Hello (and it was also have a new instance of TestUseCase) so you don't see an... |
76387595 | 76387683 | react-number-format Showing Format On inserting value
I have used this package for the Phone Input format
import { PatternFormat } from 'react-number-format';
<PatternFormat
value={value}
className='form-control'
format="(###) ###-####"
/>
Due to this format whenever I add any single value, The format... | react-number-format Showing Format On inserting value | You could build the pattern diffrent if the value reaches said length then change (empty space) for a - (dash)
import { PatternFormat } from 'react-number-format';
let pattern;
if (value.length >= 9) {
pattern = "(###) ###-####";
} else {
pattern = "(###) ### ####";
}
<PatternFormat
value={value}
cl... |
76387605 | 76387686 | I installed libssh through vcpkg on my Windows 8.1 machine.
vcpkg install libssh
Now I am trying to compile my c++ code making use of libssh.
#include <libssh/libssh.h>
#include <stdlib.h>
int main()
{
ssh_session my_ssh_session = ssh_new();
if (my_ssh_session == NULL)
exit(-1);
...
ssh_free(my_ssh_sessi... | Compiling C++ code using libssh library through vcpkg | First, you should ensure that you are installing libraries with correct "triplet" matching your compiler and architecture.
I don't know if your gcc is MingW or Cygwin.
See instructions here.
Second, you should either use CMake as described here, or manually point the compiler where to find the library headers and stati... |
76388987 | 76389120 | I have an unknown number of items and item categories in a json array like so:
[
{
"x_name": "Some Name",
"x_desc": "Some Description",
"id": 1,
"category": "Email"
},
{
"x_name": "Another name here",
"x_desc": "Another description",
"id": 2,
"... | How can I sort a JSON array by a key inside of it? | Here is a small script I made for that.
Script
def sort_by_category():
categories = {}
output = []
a = [
{
"x_name": "Some Name",
"x_desc": "Some Description",
"id": 1,
"category": "Email",
},
...
]
for i in a:
if i["c... |
76387588 | 76387690 | I'm using a library which requires a function with a void* pointer as a parameter. I have a 2D string array and I want to pass that array through that parameter and extract it inside the function. I successfully passed the array as a pointer but I don't know how to convert that pointer back to my array.
This is my curr... | Casting a void pointer to a 2D String array pointer (C/CPP) | You cannot cast a pointer to an array. Instead you access your array through another pointer. That pointer has type String (*)[10]. Like this
String str_array[100][10];
int callback(void* data) {
String (*str_array_ptr)[10] = (String (*)[10])data;
str_array_ptr[0][0] = "text"; // Note no '*'
return 0;
... |
76382813 | 76385918 | Currently transitioning from BizTalk 2013r2 to 2020, and implementing Azure Pipelines to automate deployment with BTDF.
So far, we're able to deploy our Core applications, but we've just realised there are dependencies with the 'child applications' (applications that take schemas from the Core apps).
How should I refe... | BizTalk 2020 with BTDF & Azure Pipelines - Application dependencies | No, I don't believe that BTDF can take care of that.
You should either.
Version increase your assembly version number of your Core Application and do a side by side deployment (e.g. leave the original ones in place).
Later on when you need the newer version in the dependent application then reference the later DLL (and... |
76387658 | 76387707 | I have used a custom DisplayConverter on some columns of my Nattable.This displayconverter shows long values as hex strings.
Whenever I scroll my Nattable horizontally, this converter shifts one/mulitple columns. This results in columns which show hex values to be shown in default numeral format. On the other hand, col... | Nattable Display converter shifts columns when the table is scrolled horizontally | This happens if you apply your custom labels (HEX_FORMAT in your case) on the ViewportLayer or above. If you have a strong relation on the structure, you should apply the labels on the DataLayer as there is no index-position conversion.
|
76383599 | 76386234 | Subject 1: I am using Laravel version 7 in my project, and in order to add a query to all my models in Laravel, I have added a global scope to all my models. In this way, all my models inherit from another model. The mentioned model is provided below.
namespace App\Models;
use Illuminate\Database\Eloquent\Builder;
cl... | Getting SQLSTATE[23000] error with Laravel global scope in many-to-many relationship | I believe you got that error because a number of your tables are having that client_token column. So when you got a database query involving multiple tables, it just doesn't know which client_token column you are talking about.
Lets create a scope class so we can access the table name of the model:
<?php
namespace Ap... |
76389075 | 76389126 | I'm creating a calendar for event bookings. The calendar is already working at the event registration level. I'm having trouble then showing the events registered in the database on the calendar.
To show the data in the database I am trying this way:
var datta = [
{PequenoAlm: "Peq_AlmoΓ§o", Valencia: "Teste1", Ano:... | Return data from database and show in calendar | You are configuring your event incorrectly - when defining event_data, you define a single event that has arrays of all of the events. For example, the first event has the date of all of them. Since there is only one, you end up with day = ["23"] instead of 23, which is breaking the calendar code. You also need to conv... |
76381797 | 76387767 | I want to get the Calendar Events of all of the members in the organization/team via Power Automate. As I see now the "Get Calendars (V2)" and the "Get Calendar View of Events (V3)" only return the corresponding values of the user itself (the one who owns the flow). I was wondering if there's a way to get the calendar ... | Get Calendar Events of all group members via Power Automate | The built-in connector will use the current user.
I don't think you can impersonate a user this way.
The best approach or alternative is to use Graph API with a servcie account (Azure AD app registration). You can get events from anyone, so from each users part of a group.
GET /users/{id | userPrincipalName}/calendar/e... |
76387472 | 76387866 | My goal is to change value 99999 with the value adjacent to it unless it's 99999 again.
I took the advice from here before, now I am having a new problem.
MRE:
'as' is a dataframe with 9 different cohort datasets; 10030 obs of 7060 variables. I am mainly (as of now) dealing with as$AS1_WEIGHT ... as$AS9_WEIGHT
> as %>%... | tidyr::pivot_longer() with duplicate problems with no apparent duplicate column names or dataset in R | I suspect you already have a column named name or value before you run pivot_longer, which by default tries to create columns with those names. As noted here, the error message isn't necessarily clear that's the problem.
Try grep("name", colnames(as)) and grep("value", colnames(as)) to find those columns.
Either rename... |
76383552 | 76386291 | I have a has_many_through association where Users have many Projects through ProjectUsers. Rails has some magic that allows updating this relationship with:
u = User.first
u.update(project_ids: [...])
Is there a clean way to do the same thing with create?
Running User.create(name: ..., project_ids: [...]) fails with V... | Create Record With "has_many_through" Association β Ruby on Rails | Active Record supports automatic identification for most associations with standard names. However, Active Record will not automatically identify bi-directional associations that contain the :through or :foreign_key options. (You can check here)
So you have to define inverse_of explicitly.
class Project < ApplicationRe... |
76387583 | 76387869 | Can anyone explain why the SQL function (using SQL Server 2019) returns results that to me appear to be counter intuitive? Here are the queries and the scores:
SELECT
DIFFERENCE('Good', 'Good Samaritans'); --Result is 4 (High score match)
SELECT
DIFFERENCE('Samaritans', 'Good Samaritans'); --Result is 1 (Low... | SQL Function DIFFERENCE returns interesting scores | If you change the order of words you will see there is a bias on the first word. Then if you consider SOUNDEX you will begin to understand why. Also read the reference below.
SOUNDEX converts an alphanumeric string to a four-character code that is based on how the string sounds when spoken in English. The
first charac... |
76389016 | 76389173 | I have the following dataframe:
import pandas as pd
pd.DataFrame({'index': {0: 'x0',
1: 'x1',
2: 'x2',
3: 'x3',
4: 'x4',
5: 'x5',
6: 'x6',
7: 'x7',
8: 'x8',
9: 'x9',
10: 'x10'},
'distances_0': {0: 0.42394711275317537,
1: 0.40400179114038315,
2: 0.4077213959237454,
3: 0.3921048592156785,
4: ... | How to get the index with the minimum value in a column avoiding duplicate selection | Use Series.idxmin with filter out existing values in ouput list:
df1 = df.set_index('index')
out = []
for c in df1.columns:
out.append(df1.loc[~df1.index.isin(out), c].idxmin())
print (out)
['x6', 'x8', 'x10']
|
76381633 | 76387897 | I have a pandas dataframe which is sorted by a date column. However I wish to ensure a minimum time interval between observations. Say for simplicity this window is 10 minutes, what this means is that if my first observation occurred at 8:05 AM then the second observation must occur at at least 8:15 AM. Any observation... | Ensuring a minimum time interval between successive observations in a Pandas dataframe | With your condition mentioned in comments, I think you can't vectorize whole code. However, you can browse through the dataset faster:
window = 10
# convert date as numpy array (in seconds)
arr = df['Date'].values.astype(float) / 1e9
# compute dense matrix using numpy broadcasting
m = arr - arr[:, None] > window * 60
l... |
76382810 | 76386312 | I am reading some examples of SFINAE-based traits, but unable to make sense out of the one related to generic lambdas in C++17 (isvalid.hpp).
I can understand that it roughly contains some major parts in order to implement a type trait such as isDefaultConstructible or hasFirst trait (isvalid1.cpp):
1. Helper functions... | Have difficulty understanding the syntax of generic lambdas for SFINAE-based traits |
F is a function object callable with Args...
For the sake of mental model, picture std::declval<F>() as a "fully constructed object of type F". std::declval is there just in case F is not default-constructible and still needs to be used in unevaluated contexts.
For a default-constructible type this would be equivalent... |
76383773 | 76386482 | Hello I just tring send to bottom of its parent:
<form class="flex flex-col w-full" (submit)="updatePhoto(title, description)">
<div class="w-full block">
<input type="text" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-out... | Taildwind css align bottom | It works fine just use grid on the outer container. There's also a lot of opportunity to streamline both the markup and the classes.
<script src="https://cdn.tailwindcss.com"></script>
<div class="m-4 grid max-w-4xl grid-cols-2 gap-3 rounded border p-4 shadow">
<img class="w-full" src="https://picsum.photos/id/23... |
76389093 | 76389203 | According to the chrome console there are no problems however there are as my variable is "undefined" despite it being set as "0"
I have used the following resources:
Resource 1
Resource 2
I am trying to make it so when the user clicks my image it will add +1 to the points variable (Game.points) here is my code (for co... | How do I display Javascript variable using | The points variable is not a member of the Game object. To reference it, just use the points keyword.
There's also a couple of changes you can make to improve the code quality:
Remove the inline onclick and onload attributes. They are outdated and not good practice. Use addEventListener() to bind events within JS, ins... |
76382922 | 76386636 | I have very CPU heavy process and would like to use as many workers are possible in Dask.
When I read the csv file using the read_csv from dask and then process the dataframe using map_partitions only one worker is used. If I use read_csv from pandas and then convert the file to a Dask dataframe, all my workers are use... | Dask map_partition does no use all workers on client | The DataFrame.set_index method in both dask.dataframe and pandas returns the updated dataframe, so it must be assigned to a label. pandas does have a convenience kwarg inplace, but that's not available in dask. This means that in your snippet, the first approach should look like this:
dask_df = dask_df.set_index(UID, n... |
76378627 | 76387024 | I made a program where users can keep track of their expenses by entering them into the system after creating their own account. The system requires users to fill in four fields: customer, category, price, and month. I would like the first field (customer) to automatically populate with the username of the logged-in us... | User can't create objects in the page | This is the solution i found and worked perfect too.
I made 2 changes:
views.py:
@login_required(login_url='login')
def homeView(request):
items = Finance.objects.filter(customer=request.user).order_by(Cast('month', IntegerField())).reverse()
if request.method == 'POST':
form = FinanceForm(reques... |
76387813 | 76387951 | I have this working code to process a single file:
import pandas as pd
import pygmt
#import table
df = pd.read_table("file1.txt", sep=" ", names=['X', 'Y', 'Z'] )
#min/max
Xmin = df['X'].min()
Xmax = df['X'].max()
Ymin = df['Y'].min()
Ymax = df['Y'].max()
#print(Xmin, Xmax)
#print(Ymin, Ymax)
#gridding with pyGMT
g... | Find Min/max for X and Y, then interpolate for 5000 txt files with python | As said before in comment section you also can do it by iterating all .txt filenames and changes their formats to .nc with saving names.
import glob
import pandas as pd
import pygmt
filenames_in = glob.glob("*.txt")
for filename_in in filenames_in:
filename_out = filename_in.replace('.txt', '.nc')
# YOUR CODE... |
76383379 | 76387122 | I am learning x86-64 assembly with an online course and the course is horribly unclear in detail. I've searched online and read several SO questions but couldn't get an answer.
I tried to figure out how to calculate binary multiplication by hand, but I am stuck with imul .
Given this example of binary multiplication, 1... | How do you manually calculate imul -1 * 3? | Honestly, I can't fully understand the other two answers. It's over complicated for me. I just need a dumb, simple and universal rule.
I'd like to just pick up what works for me.
The result is equivalent to sign-extending (imul) or zero-extending
(mul) both inputs to the destination width and then doing a
non-widening... |
76388975 | 76389211 | The circular dependency between self.buttons and self.radiobuttons has been impossible for me to solve
class Program(tk.Tk):
def __init__(self, title, size):
super().__init__()
self.title(title)
self.geometry(f"{size[0]}x{size[1]}")
self.frame = tk.Frame(self, background = ... | How do I eliminate this circular dependency | You can create another class method of Buttons to pass self.radiobuttons to it after self.radiobuttons is created.
Below is an example:
class Buttons(ttk.Frame):
def __init__(self, master, entries, output):
super().__init__(master)
self.entries = entries
self.output = output
# another c... |
76387859 | 76387955 | I faced an issue when I had to terraform import some role_assignment resources, specially regarding the APP CONFIG DATA READER role assignment, in terraform.
the problem I had to solve was due to an evolution of our iac to make the terraform plan more readable and explicit.
Here is the code for role assignment that cha... | Maps containing keys with spaces are not properly validated when those keys are used as resource names | So I've had to test my get_ResourceId methods in local on a powershell VSCode terminal, that does not accept the above code (as the paces wher badly interpreted by powershell)
So, after a quick search that explain to me that the "`" was the escape character for Powershell, I've tested this that works and give to me the... |
76378706 | 76387141 | In C++, I can't find a way to appropriately terminate a WMI session with a remote server. Any attempt to release the IWbemServices pointer throws an exception; the TCP connection to the server remains established until the process exits (it's open after the last CoUninitialize call). This problem (thrown exception) d... | (WMI) IWbemServices::Release() throws "Access Denied" exception when connected to remote machine | I was able to resolve the issue. If you are not using the current logged-on user token, you must specify the pAuthInfo parameter of CoSetProxyBlanket to a valid COAUTHIDENITY structure pointer. The docs for IWbemLocator::ConnectServer actually state that it's best practice to include the domain in the strUser paramet... |
76383760 | 76387258 | I've been going through react-router's tutorial, and I've been following it to the letter as far as I'm aware. I'm having some issues with the url params in loaders segment.
The static contact code looks like this
export default function Contact() {
const contact = {
first: "Your",
last: "Name",
avatar: ... | Going through the react-router tutorial and rather than using default or null values when loading an empty object, it kicks up an error | There are some subtle, but detrimental, casing issues in the route path params.
The Contacts component's route path param is declared as contactID.
const router = createBrowserRouter([
{
path: "/",
element: <Root />,
errorElement: <ErrorPage />,
loader: rootLoader,
action: rootAction,
children... |
76387927 | 76387999 | I would like to display either one of two images in a modal based on an API response...unfortunately, the API returns a long string array. I need to be able to determine if the word "Congratulations" is in this array. So far, I've tried a couple basic things:
Here is an example API response:
{
id: 12,
message: ... | Checking the values of JSON response in React Native | I would join the array and than call include.
const data = {
id: 12,
message: ["1 bonus point!", "Congratulations", "You have leveled up!"]
}
const containTerm = data.json().message.join().includes('Congratulations')
console.log('Is term in array', containTerm)
|
76383873 | 76389257 | I have a DataFrame consisting of the following columns:
VP-ID,
MotivA_MotivatorA_InnerDriverA_PR,
MotivA_MotivatorA_InnerDriverB_PR,
MotivA_MotivatorB_InnerDriverA_PR,
MotivA_MotivatorB_InnerDriverB_PR,
MotivA_MotivatorC_InnerDriverA_PR,
MotivA_MotivatorC_InnerDriverB_PR,
MotivA_MotivatorD_InnerDriverA_PR,
MotivA_Motiv... | Creating a "FootBall Field Chart" | It's a spine chart. The issue with that is it'll not line up your bars. So to do that, you need to get creative:
import pandas as pd
import random
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
columns = [
'MotivA_MotivatorA_InnerDriverA_PR',
'MotivA_MotivatorA_InnerDriverB_PR',
'... |
76383427 | 76387760 | I am trying to build the AOSP but i always get this error.
In every thread the answer is that its a RAM problem.
I have tried the build with the following commands. Nothing works
m -j32
m -j16
m -j12
m -j8
m -j2
m -j1
I am using a 32GB 14Core Native Linux Workstation.
| AOSP build not working - failed to build some targets | After adding 20GB of Swap Storage it now works.
|
76389244 | 76389294 | I want to use python scheduler module for an api call.
I have two main tasks.
1-Generate token at interval of 10 mins
2-Call the api using the token generated in previous step
The expected behavior is when a user calls the api it should use the same token for 10 mins and after 10 mins the toekn will be updated in backg... | Use python schedule module in an efficient manner | You are getting stuck in the (infinite) loop inside schedule_run. First define the two scheduled jobs, the run the schedule waiting loop:
token=""(This is a global variable)
def generate_token():
token=//Logic to generate token//
def apicall():
schedule.run_pending() #will update the token if it has not been done i... |
76388900 | 76389306 | Get the average traffic from last week data per WEEK number and get the traffic data for last week Traffic(D-7)
For example if date = 5/13/2023, need to output traffic data (Traffic(D-7)) for date = 5/6/2023
I manage to get the Average but no idea how to retrieve the date-7 data and output it altogether
create table a... | PostgreSQL - Get value from from the same table | First of all, you need to fix your flaws in your table schema design, and declare:
dates with the "DATE" type (instead of VARCHAR(50))
week values with the INT type (instead of VARCHAR(5))
traffic values with the DECIMAL type (instead of FLOAT)
CREATE TABLE tab(
DATE DATE,
Tname VARCHAR(50),
Week... |
76382863 | 76388174 | I have a Firebase Realtime Database with users and the email is stored in a child field, for example:
/users/00Vho6lTQke46IqpRv0D5dw6DXs2/email -> user@email.com
I want to query once and get a user based on the MD5 hash of the email address. For example, MD5('user@email.com') -> 'b58c6f14d292556214bd64909bcdb118'.
I d... | Firebase RT Database Query on field value hash equality |
Is it possible to query using an MD5 function to transform the email field to MD5 and query on that?
No, unless you save the MD5 as a field inside the database. If you do that, you'll be able to query using the MD5. Your schema should look like this:
db
|
--- users
|
--- 00Vho6lTQke46IqpRv0D5dw6DXs2
... |
76387305 | 76388059 | Help me create an sql query.
There are two databases DB1 and DB2. In each of them there are tables "users" and "cities" with the names of cities. Users and city names are the same in both databases. But the city ID values are different in the two databases. In the first DB1 database, the "users" table contains the city... | Update + join from two databases | Use an update with join:
update DB2.users set
city = DB2.cities.ID
from DB2.users
join DB1.users on DB1.users.ID = DB2.users.ID
join DB1.cities on DB1.cities.ID = DB1.users.city
join DB2.cities on DB2.cities.name = DB1.cities.name
The join from DB2.users to DB2.cities goes via DB1's tables, going over using user ID a... |
76389247 | 76389335 | I have a nested list of strings that I would like to write to a CSV file using CSV helper. So, it is a list called Entries and each element has a list of strings called Entry.
My current code is exporting a blank CSV file.
Entry example:
{"Date", "param1", "param2", "param3", "param4"}
and the Entries list will have a... | Writing a Nested List of Strings to CSV using CSV helper | I used the current code to get it working
using (var stream = new MemoryStream())
using (var writer = new StreamWriter("yodelTesting.csv"))
using (var reader = new StreamReader(stream))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
foreach (var record in output)
{
foreach (var ... |
76382701 | 76388249 | I've been using the Bitmap-class and it's png-ByteStream to deal with images in my WPF-application, mostly with reading/writing files, getting images from native cam libs and showing them in the UI.
Lately I've got some new requirements and tried to upgrade some of that to deal with 64 bit deep images (or 48 bits, I do... | How to deal with 48 or 64bit images in C# | I do not think you will have much success with System.Drawing.Bitmap. In my experience these just have poor support high bit depths. I would instead take a look at the corresponding System.Windows.Media classes. I know PngBitmapEncoder/decoder at least support 16 bit grayscale, but I suspect 48/64 bit works fine as wel... |
76387881 | 76388086 | The Ansible documentation has a list of Variable precedence
Some of them are clear to me but I wonder whether anybody coulde kinkdy shed some light on those 2.
20. role (and include_role) params
21. include params
usage, location, syntax.
I am trying to get Variable declaration a little further to the surface inside ... | Ansible Variable precedence - what are 'role params' & 'include params' | In a nutshell examples:
role params
(full playbook)
- name: I'm a dummy play
hosts: localhost
roles:
- role: somerole
vars:
param1: "I'm a role param"
Include role params
(task only)
- name: Including role somerole
ansible.builtin.include_role:
name: somerole
vars:
param1: "I'm an in... |
76389245 | 76389353 | I came across this code somewhere when practicing basic C questions:
int func(num) {
if (num > 0) {
return (num + func(num - 2));
}
}
int main() {
printf("%d\n", func(5));
return 0;
}
The code when executed returns 8 as the answer. But I think that the answer should be "cannot be determined".
... | Why garbage value is not being returned in a recursive call to a function with undefined behavior? |
Why garbage value is not being returned in a recursive call to a function with undefined behavior?
Because "garbage" does not mean what you think it means in this context. In particular, "garbage" does not mean "random". (Or if it does, it's more in the sense of xkcd 221.)
Computers are usually deterministic. You ... |
76387483 | 76388088 | I require to fetch the count of PRODUCT_ID between 00:15:00 and 01:15:00 and subsequentially for any date range.
Example Scripts:-
My DB structure and data is as follows.
CREATE TABLE time1 (cr_date date , product_id number );
insert into time1 values (to_date ('01-JAN-2022 01:00:00', 'DD_MON-YYYY HH:MI:SS') , 12345);... | SQL to fetch the count between tow date range | Sample data you (initially) posted is pretty much useless, there's no time component involved.
In one of my tables, there's a datum column and values look like this:
SQL> SELECT id, TO_CHAR (datum, 'hh24:mi') hrs FROM obr WHERE rownum <= 10;
ID HRS
---------- -----
21547 08:41
21541 08:17
21563 ... |
76383461 | 76388255 |
ID_1
ID_2
ID_3
LANG
1
11
111
F_lang
1
11
111
null
2
22
222
null
Is it possible to build a query which returns only these two lines below.
It should be grouped by the first three columns and should take only that line with value of column LANG which is preferably not null, if no value for LANG exists, i... | DB2 Group by specific columns | Does this anwser the question ?
with t1(id_1, id_2, id_3, lang) as (
VALUES
('1', '11', '111', 'F_lang'),
('1', '11', '111', NULL),
('2', '22', '222', NULL),
('3', '33', '333', 'F_lang_3_1'),
('3', '33', '333', 'F_lang_3_2'),
('3', '33', '333', NULL)
)
select id_1, id_2, id_3, lang from t1 where lang is n... |
76382933 | 76388472 | I am on thin ice both syntax-wise and English-wise here, apologise if my way of expressing maths here is a rambling of a mad-man.
I have two sequences/"functions" f(n) and g(n). They are technically not functions, I have them just defined as a sequence of repeating modulus of 9 and 10.
n = 0,1,2,3,...
f(n): nMOD9={0,3,... | How to express h(n) which is the "union" of the two sequences f(n) & g(n) | One possible solution would be to find all values of h(n) up to 90, then h(n) will be those nMOD90, so
h(n): nMOD90={0,3,4,9,13,15,18,24,30,33,39,40,45,48,49,54,58,60,63,69,75,78,84,85}
|
76388049 | 76388104 | I recently changed the dependency
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4</version>
</dependency>
to
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.6.0</version>
</dependency>
because Java 8 doesn't su... | "BASE64DecoderStream" gives error for javax-mail dependency | You're using the wrong dependency. You have only added the JakartaMail API. You should use the JakartaMail 1.6.x implementation:
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>jakarta.mail</artifactId>
<version>1.6.7</version>
</dependency>
This dependency does include com.sun.mail.util.BASE64Dec... |
76389296 | 76389365 | According to this statement, pygame.time.Clock().tick() should be called at the end of the main loop. However, I couldn't see any differences on my screen display regardless where I executed that method within the loop. Could someone please give some clarification on this? Thanks
| Where should pygame.time.Clock().tick() be called in the script | The documentation say :
A call to the tick() method of a Clock object in the game loop can
make sure the game runs at the same speed no matter how fast of a
computer it runs on
So it is better to call it at the end of the loop because if you do it in the middle of your display fonction, a part of the element will be ... |
76383813 | 76388631 | I am trying to run scripts on a remote server with DataSpell, so I am trying to configure a remote interpreter.
I follow these instructions and I get the error
Cannot Save Settings:
SSH Python x.x.x user@IP : Python x.x.x
(path/to/interpreter) can't be used as a workspace interpreter
As a path to the interpreter I hav... | Remote Interpreter DataSpell | It appears that Dataspell can have different interpreters for its workspace and projects or notebooks that are opened in the workspace.
I right-clicked the project folder in the Project window, and selected a remote interpreter just for the project. This is what the second source that I posted on my OP says. This works... |
76382654 | 76388806 | I'm trying to implement on-behalf-of user flow for Microsoft Graph API. I'm using Microsoft Graph .NET SDK and I'm encountering Access Denied (status code 403) for my requests. I'm not sure how to correctly set up permissions for users of my organization in Active Azure Directory. I'm trying to implement SharePoint / O... | Microsoft Graph .NET SDK on-behalf-of flow returns Access Denied 403 for Sites/Files | You want to be able to access any drive/site files and be able to upload/download/list. Then on-behalf-of flow isn't suitable for you. OBO flow will generate access token with Delegated API permission, which can't be used to access any others' drive/site files. We need to use access token with Application API permissio... |
76387995 | 76388110 | I am trying to copy some files from Firebase into a Gitlab repo.
Using my personal SSH credentials, I am able to do this.
I'd like to use deploy tokens. I generated a fresh token and gave it all the permissions I can. However, when I run the CI pipeline I get an "fatal: Authentication failed"
| Gitlab CI Deploy Token cant push to repo | A deploy token is simply not made for that. As per the documentation a deploy token is not capable to write to a GitLab repository. Here is what you can do with a deploy token:
Clone Git repositories.
Pull from and push to a GitLab container registry.
Pull from and push to a GitLab package registry.
What may be a bet... |
76389214 | 76389384 | I have a simple countdown timer which is launched on the click of the .btn-submit-a button. I tried to make it so that after the timer ends, button A is replaced by button B (.btn-submit-b), but, unfortunately, nothing comes out. How can I achieve this? I will be glad for any help.
jQuery(function($){
$('.btn-submi... | Replace one button with another when countdown timer ends | You had a weird combination between jquery and native code. You can do that ofcourse but I would recommend to stick to either jQuery or native where possible. Therefore I changed some code to jQuery functions.
This said you can hide and show elements with the hide() and show() jQuery functions as you can see in the exa... |
76389116 | 76389387 | I have a table (description of table):
Name
Type
KEYVALUE
VARCHAR2(100)
TEXT
CLOB
Example
Keyvalue
Text
101
Customer Input 05/15/2023 07:20:20 My name is ABX +++ Private Notes What is you name+++Customer Input 04/30/2023 19:40:58 I have issue related to water purifier purchased on Jan 23 +++ Publi... | Clob Issues- Splitting a clob column to multiple rows | The code you posted will get that error if the source text is a CLOB, whatever the length. The problem isn't the length itself, it's that each split row value is also a CLOB, and you can't use distinct with CLOBs.
The use of distinct is often a sign that there's a deeper problem that's just covering up. Without it you ... |
76383547 | 76389112 | On an isolated network (without internet access to do public IP address lookups), I want to run a playbook from a controller against a number of target hosts where one of the tasks is to download a file via HTTP/HTTPS from the controller without hard-coding the controller IP as part of the task. E.g.
Controller: 192.16... | How can I get Ansible client IP from target host? | Limited test on my machine which has a single ip and with a single target. But I don't see why it would not work in your scenario.
Given the following inventories/default/hosts.yml
all:
hosts:
target1:
ansible_host: 192.168.0.10
target2:
ansible_host: 192.168.0.11
target3:
ansible_host: ... |
76387851 | 76388128 | My array of objects looks like this:
[{"data": [5, 2, 7, 2, 4, 2], "date": {"begin": "03.07.", "beginYear": "2023", "end": "10.07.", "endYear": "2023", "timestamp": 1688335200000}}, {"data": [5, 2, 7, 2, 4, 2], "date": {"begin": "26.06.", "beginYear": "2023", "end": "03.07.", "endYear": "2023", "timestamp": 16877304000... | How can I split an array of objects and extract specific keys while adding 0s to fill up to a specific length? |
let arr = [{
"data": [5, 2, 7, 2, 4, 2],
"date": {
"begin": "03.07.",
"beginYear": "2023",
"end": "10.07.",
"endYear": "2023",
"timestamp": 1688335200000
}
}, {
"data": [5, 2, 7, 2, 4, 2],
"date": {
"begin": "26.06.",
"beginYear": "2023",
"end": "03.07.",
"endYear": "2023... |
76382277 | 76389186 | I am using PHP 8.2 to read our JFrog Artifactory API and this works fine. Now I am in the need to either create or update some of the properties on an artifact - so either create it if it does not exists, and update it if it does exists.
For example I can read all properties for a specific artifactory with this code:
<... | How to create/update key/value pair in JFrog Artifactory with PHP and cURL? | Actually I did figure out this myself and it was a stupid/simple mistake. I easily solved this after finding the right help page - I should probably have invested more time in finding this in the first place :-)
Let me show the solution first:
<?PHP
// Full URL for specific artifact and the property to create/update
$... |
76388109 | 76388143 | I have been training my custom Image classification model on the PyTorch transformers library to deploy to hugging face however, I cannot figure out how to export the model in the correct format for HuggingFace with its respective config.json file.
I'm new to PyTorch and AI so any help would be greatly appreciated
trai... | How to export a PyTorch model for HuggingFace? | You are using HuggingFace Transformers, you can use:
model.save_pretrained("FOLDER_NAME_HERE")
After you saved the model, the folder will contain the pytorch_model.bin along with config JSONs.
|
76389395 | 76389396 | I am trying to find 9 raise to power 19 using numpy.
I am using numpy 1.24.3
This is the code I am trying:
import numpy as np
np.long(9**19)
This is the error I am getting:
AttributeError: module 'numpy' has no attribute 'long'
| AttributeError: module 'numpy' has no attribute 'long' | Sadly, numpy.long was deprecated in numpy 1.20 and it is removed in numpy 1.24
If you wan the result you have to try numpy.longlong
import numpy as np
np.longlong(9**19)
#output
1350851717672992089
https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations
|
76390641 | 76390728 | I have a static web site in the s3 bucket behind the cloudfront distribution.
The bucket serves the static site, and the origin is bound to the web site endpoint.
I see a couple of pages if they were added before the distribution
However, when I upload some new html files, I receive 403 for them.
How should I fix this ... | 403 for the new pages in the cloudfront distribution | Try to invalidate cloudfront cache. Go to cloud front distribution and click on invalidation enter "/*". Click on create invalidation.
If you are trying to access object publicly, then provide public access to s3 bucket objects.
|
76387987 | 76388168 | Imagine I have the following SQL table:
| id | price | start_time |
---------------------------
| 1 | 0.1 | 2023-01-01 |
| 2 | 0.3 | 2023-03-01 |
| 3 | 0.2 | 2023-02-01 |
But then I want to query the prices in that table in a way that I can also get the end time as the start time of the next in time column. S... | Get the end_time in a query using the start time of the next sorted column | This can be done using the window function lead() to get the which follows the current row :
select *, lead(start_time) over (order by start_time) as end_time
from mytable
With where clause it can be :
select * from (
select *, lead(start_time) over (order by start_time) as end_time
from mytable
) as s
where price... |
76388994 | 76389403 | I'm currently working on a Next.js 13.4 project and trying to set up NextAuth using the app/ router. However, I'm encountering a type error that I can't seem to resolve.
Here's my route.ts file:
import NextAuth, { AuthOptions } from "next-auth";
import DiscordProvider from "next-auth/providers/discord";
export const a... | Next.js 13.4 and NextAuth Type Error: 'AuthOptions' is not assignable to type 'never' | Okay i solved it myself. For anyone having the same issue, i created a new file @/utils/authOptions.ts:
import { NextAuthOptions } from "next-auth";
import DiscordProvider from "next-auth/providers/discord";
export const authOptions: NextAuthOptions = {
providers: [
DiscordProvider({
clientId: ... |
76390749 | 76390796 | I'm New to React, and I'm trying to learn about React Component right now. but when I create nameList.js, add data in there, and export to app.js, it does not show anything in the browser. I read some answers in Stackoverflow and tried it. but not show anything.
App.js
import './App.css';
import nameList from './Compon... | is defined but never used no-unused-var | Ensure that nameList starts with a capital letter so that React knows it's a component and not an HTML element.
import React from 'react';
function NameList() {
return (
<div>
<h1>Name List</h1>
<ul>
<li>Stu1</li>
<li>Stu2</li>
<li>Stu3</li>
</ul>
... |
76387775 | 76388177 | This code is where I modified the data, wherein I update the "checked" to whether "true" or "false". and this code works because when I console.log() it it updates the state.
setRolesData((prevState) => {
const newState = Array.from(prevState);
newState[targetCb]["checked"] = e.target.checked;
... | useState() not updated when state is used in a loop | In React, components have a lifecycle that is based around the idea of preserving state. When you update a value in a component we effectively trigger a re-render of the component. So if you have a variable at the top of your component with a certain value and try to update this value inside a function, you'll find tha... |
76389309 | 76389422 | I am trying to write a Python regex pattern that will allow me to capture words in a given text that have letters separated by the same symbol or space.
For example, in the text "This is s u p e r and s.u.p.e.r and sπuπpπeπr and s!u.p!e.r", my goal is to extract the words "s u p e r", "s.u.p.e.r", and sπuπpπeπr... | How to capture words with letters separated by a consistent symbol in Python regex? | You may consider using
pattern = r"(?<!\S)\w(?=(\W))(?:\1\w)+(?!\S)"
results = [m.group() for m in re.finditer(pattern, x)]
See the Python demo and the regex demo.
import re
x="This is s u p e r and s.u.p.e.r and sπuπpπeπr and s!u.p!e.r"
pattern = r"(?<!\S)\w(?=(\W))(?:\1\w)+(?!\S)"
print([m.group() for m in re.fi... |
76390683 | 76390801 | I am transforming from Graph API to Graph SDK. How can I transform this API call?
https://graph.microsoft.com/v1.0/users/XXX/calendarView?startDateTime=YYY&endDateTime=ZZZ&$expand=extensions($filter=id eq 'NAME')
Expand part is missing. How should I add Expand = ??? or do it somehow with Filter or Select?
var ret = aw... | How to transform Microsoft Graph API query with expand=extensions to SDK code | Thank you @user2250152 . I made a typo. Solution:
requestConfiguration.QueryParameters.Expand = new string[] { "extensions($filter=id+eq+'NAME')" };
|
76387285 | 76388205 |
I am new to Flutter development
The horizontal list stops scrolling but is able To Scroll while using Axis.vertical.
What is expected is Once All the content of List Scrolls then only go to the next Slider.
Problem = only displays the list of items that we can visible on a screen unable to scroll horizontally
lib-link... | Unable to add horizontal ListView.builder while using overlapping_panels 0.0.3 | I Looked at your code. And also looked at the Library of OverlappingPanels.
The thing is, if you wrap you page with Overlapping Panels, It wrap you whole Screen with a Gesture Detector and it listens to a gesture to swipe from right to left.
If you are new, I would try something else. Otherwise you can copy their libra... |
76390731 | 76390810 | I'm parsing a list of emails in a text file and I need to parse dates in the email headers. The dates are in a multitude of formats and languages:
sexta-feira, 26 de agosto de 2022 16:41
viernes, 26 de agosto de 2022 19:24
2022/08/26 13:30:56
26 de agosto de 2022 13:32:49 BRT
Mostly portuguese, spanish, italian and en... | Parsing multiple date string languages and formats | The dateparser package provides modules to parse localized dates in most string formats.
The following snippet successfully retrieves all dates in the given example:
import dateparser
text_dates = [
"sexta-feira, 26 de agosto de 2022 16:41",
"viernes, 26 de agosto de 2022 19:24",
"2022/08/26 13:30:56",
... |
76389259 | 76389434 | Consider the MWE below
WITH samp AS (
SELECT '2023-01-01' AS day, 1 AS spent UNION ALL
SELECT '2023-01-02' AS day, 2 AS spent UNION ALL
SELECT '2023-01-03' AS day, 3 AS spent
)
SELECT day,
spent
, ARRAY_AGG(spent) OVER(ORDER BY day BETWEEN '2023-01-02' AND '2023-01-03') ss
FROM samp
ORDER B... | Window function, order by clause, between operator | The clause
day between '2023-01-02' and '2023-01-03'
is a boolean expression, and will only evaluate to two possible values, true or false (1 or 0). Therefore, your window function array_agg(spent) will compute using an order where dates other than 2023-01-02 and 2023-01-03 will be ordered first, followed by these da... |
76389304 | 76389435 | The username is in column one and PID in column two of ps gaux, so I have:
ps gaux | awk '{print $2;}' | while read line ; do grep -i umask /proc/$line/status ; done
but is there a way to print the username as well?
| How do I print the user and umask for all running processes? | I hope this helps
ps gaux | awk '{printf $1 " " ; system("grep Umask /proc/"$2"/status | tr -dc [:digit:]"); printf "\n"}'
Explanation:
get output from ps
print first column (username) and space
run the grep and remove everything except the actual umask, which is a number (awk does not print the command output, it ge... |
76383190 | 76390828 | I am getting this error:
IntegrityError at /register/
null value in column "total_daily_mission_progress" violates not-null constraint
DETAIL: Failing row contains (363, 0, 374, free, 0, null, unranked, 0, , odifj@gmail.com, 0, f, [], 0, {}, {}, t, null, null, null, null, null, {}, null, null, No phone number set, Thi... | Django - INTEGRITY ERROR on column that no longer exists | Ended up figuring it out, ended up using python3 manage.py dbshell and runnning the following command:
ALTER TABLE_NAME FROM USERMODAL
|
76387798 | 76388214 | How to disable italics on static methods called inside AndroidStudio IDE?
I know, it's a personal preference question but is there a way to disable italics? and only keep the colour coding?
| How to change color scheme for static methods in IntelliJ IDEA / Android Studio | Settings/Preferences (on macOS) | Editor | Color Scheme | Java | Methods | Static method
Additional trick: to easily find the corresponding color scheme settings do the following:
Put the cursor at the needed element you need to change
Press Shift twice
Type Just to Colors and Fonts and press Enter. Then select the c... |
76389341 | 76389488 | I am trying to do some text processing and was interested to know if I can have a common/unified regex for a certain pattern. The pattern of interest is strings that ends with {string}_{i} where i is a number, on the second column of test.csv. Once the regex is matched, I wish to replace it with {string}[i].
For now th... | common/unified regex for a set of pattern | I would use sub with a single generic pattern :
with open("test.csv", "r") as file2:
for row in csv.reader(file2):
s = re.sub(r"(.+)_(\d+)$", r"\1[\2]", row[-1].strip())
print(s)
Regex : [demo]
Output :
COMP_NUM[0]
COMP_NUM[2]
COMP_NUM[11]
FUNC_1V8_OLED_OUT[7]
FUNC_1V8_OLED_OUT[9]
FUNC_1V8_OLED... |
76387936 | 76388264 | total nube in PL/PGSQL. I would like to define an array of strings and then used that in my SELECT... WHERE In statement but can't seem to get it to work, help appreciated.
DO $$
DECLARE
testArray varchar[] := array['john','lisa'];
ids integer[];
BEGIN
ids = array(select id from tableA where name in (t... | How to use array variable in my sql statement in plpgsql | You can use any near of testarray.
DO $$
DECLARE
testArray varchar[] := array['john','lisa'];
ids integer[];
BEGIN
ids = array(select id from tableA where name = any(testArray));
-- this works
ids = array(select id from tableA where name in ('john','lisa'));
END $$;
|
76390640 | 76390875 | I have two 3D masked arrays (netCDF4 files output from climate model) that I want to add together. I followed this thread and got the following (simplified) code out of it:
import numpy as np
from netCDF4 import Dataset
from operator import and_
from numpy.ma.core import MaskedArray
with Dataset(dir + 'V10.nc') as fil... | Adding 3D masked arrays results in TypeError: 'numpy.bool_' object is not iterable | You can use np.logical_and to create the mask.
with Dataset(dir + 'V10.nc') as file_V10:
with Dataset(dir + 'U10.nc') as file_U10:
raw_V10 = file_V10.variables['V10'][744 : 9503, :, :] ** 2
raw_U10 = file_U10.variables['U10'][744 : 9503, :, :] ** 2
mask = np.logical_and(raw_V10.mask, raw_U10... |
76389299 | 76389493 | I have this SELECT statement in SQL Server:
select testname as 'Test',
tests_morning ,
tests_evening ,
Date
from labtests_hajj
left join departments_statistics on departments_statistics.test_id = labtests_hajj.testid
inner join departments on labtests_hajj.dept_id = departments.dept_id
The ou... | Select the data and generate the SELECT for each day from date to date? | There are have two ways
use DimDate or calendar table
you create a date table yourself with CTE
With DimDate
declare @StartData date='2023-02-01'
declare @EndData date='2023-02-06'
;with _t as
(
select testname as 'Test',
tests_morning ,
tests_evening ,
Date
from labtests_... |
76389280 | 76389522 | Why this works
sed -n '242p' /usr/local/lib/python3.6/site-packages/keras/models.py
model_config = json.loads(model_config.decode('utf-8'))
sed -i "242s/.decode('utf-8')//" /usr/local/lib/python3.6/site-packages/keras/models.py
sed -n '242p' /usr/local/lib/python3.6/site-packages/keras/models.py
mod... | sed doesn't replace a string when this is at the end of the line | There's an important one character difference:
utf8
utf-8
|
76388209 | 76388265 | I am trying to build a mock factory, like this:
public Mock<T> CreateMock<T>(SomeParams someParams) where T : IMyInterface
{
Mock<T> result = new Mock<T>();
...
}
However, I am getting the compiler error CS0452: The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or me... | Cannot Mock but can Mock? |
I don't understand, why I am getting the compiler error, when the code is functionally the same?
Consider this case:
public struct Awkward : IMyInterface
{
}
...
Mock<Awkward> mock = MockFactory.CreateMock<Awkward>();
That satisfies the constraint you've put on CreateMock - but Awkward is a value type. Mock<T> requi... |
76390665 | 76390920 | import pandas as pd
from sklearn.cluster import KMeans
dataset = pd.read_csv("smogon.csv")
dataset.drop(["url", 'texto'], axis=1, inplace=True)
km = KMeans(n_clusters=1, n_init='auto')
cluster = km.fit_predict(dataset[["moves"]])
dataset["Grupo"] = cluster
print(dataset)
it shows (cluster = km.fit_predict(dataset[["m... | Does an error existe on the next code? it shows error on line 7 | Try to use LabelEncoder to convert your column moves as numeric:
import pandas as pd
from sklearn.cluster import KMeans
from sklearn.preprocessing import LabelEncoder
dataset = pd.read_csv("smogon.csv")
dataset.drop(["url", 'texto'], axis=1, inplace=True)
# It does not make sense to have only one cluster...
# There i... |
76380543 | 76388271 | I have created a document upload site with asp.net core web app's, and I have encountered a small bug but I'm not sure how to fix it.
On my site, you first create a 'file' like so:
It then appears in a list like so:
And when you press upload attachment, it passes the id from the previous table to ensure it uploads to... | Detecting page refresh c# | You can custom the error message
[BindProperty]
[Required(ErrorMessage ="You must select a file before upload this form")]
public IFormFile file { get; set; }
And you also need to add Jquery validation library to your view:
@section Scripts {
@{
await Html.RenderPartialAsync("_ValidationScriptsPartial");
... |
76389514 | 76389555 | I need to detect if a string contains a specific word like "Hello".
Hello -> yes
HhhheeeEEEElllLLLLoooOOOO -> Yes
hell0 -> yes
h e l l o / h. e .l .L . o -> Yes
h@@$$eee///LLL!!!ooo -> yes
My attempt:
let string = "h@@$$eee///LLL!!!ooo";
if (string.match(/\bhello\b/i)) {
console.log("Yes");
} else {
... | Regex to detect deformed words | You can use .* between the chars, [o0] for o and zero and the flag i for case-insensitive matches:
[
"h@@$$eee///LLL!!!ooo",
"Hello",
"HhhheeeEEEElllLLLLoooOOOO",
"hell0",
"h e l l o / h. e .l .L . o",
"h@@$$eee///LLL!!!ooo"
].forEach(string => {
if (string.match(/h.*e.*l.*l.*[o0]/i)) {
console... |
76389515 | 76389565 | This is my df:
df <- data.frame(id=as.integer(c(1:6)),
code=as.character(c("C410", "D486", "D485", "D501", "D600", "D899")))
df
id code
1 1 C410
2 2 D486
3 3 D485
4 4 D501
5 5 D600
6 6 D899
I want to attribute causes to each id depending on the range they fall into in column 2. For this, I use... | Retrieve every value between an alphanumeric range in R using ifelse | Yo need to add a third digit:
df$cause <- ifelse(df$code >= "C000" & df$code <= "D489", "cause 1",
ifelse(df$code >= "D500" & df$code <= "D899", "cause 2", NA))
> df
id code cause
1 1 C410 cause 1
2 2 D486 cause 1
3 3 D485 cause 1
4 4 D501 cause 2
5 5 D600 cause 2
6 6 D899 cause 2
|
76390791 | 76390956 | I am trying to join an underscore into a string, but when running the code I get 4 times the character i used
str = potetoBox
for indx in range (len(str)):
if str[indx].isupper():
#split before indx and input an underscore
str = ''.join((str[:indx],'_',str[indx:]))
print(str)
I have tried to chan... | When using join in a string, I get too many characters in the string | Another solution without re that doesn't build a list:
result = ""
for c in my_str:
result += "_" * c.isupper() + c
|
76389352 | 76389617 | I have byte[] like this, the length of byte[] is 16, and I want to change some value of an item and add this to a new byte[]. For example, the value of byte[7] is 13, I want to change this value with a new value. After that, add into a new byte, the value of byte[7] will be changed plus one more unit.
| How to copy from byte[] to new byte[] with some changed element item? | You should perform the operations the other way round. First copy then change the value in the copied data. This way the original will stay unchanged.
Efficient:
var original = new byte[]{1,2,3};
var result = new byte[original.Length];
Array.Copy(original, result, original.Length); //first make a copy
result[2] = 42; ... |
76388142 | 76388285 | I want to delete the object where the name is "Sleep".
The code I am using:
const listName = "Holiday;
const item = new Item({
name: "Sleep"
});
User.updateOne({username : req.user.username}, {$pull:{"lists.$[updateList].items" : item}}, {
"arrayFilters": [
{"updateList.name" : listName}
]
}).... | I am trying to remove an item from my mongoDb object which is an object with an array of nested objects. But this code is not working | Try with
const listName = 'Holiday';
User.updateOne(
{ username: req.user.username, 'lists.name': listName },
{ $pull: { 'lists.$[].items': { name: 'Sleep ' } } }
)
.exec()
.then(function () {
console.log('Deleted successfully');
res.redirect('/list-' + listName);
});
|
76390964 | 76391015 | I'm trying to display all the questions from this data set however it's only working sometimes and then other times I receive 'questions is undefined'.
Why am I receiving this error?
const [questions, setQuestions] = useState<any>();
const [question, setQuestion] = useState<string>()
const [answers, setAnswers] = useSt... | questions is undefined in useEffect | import React, { useEffect, useState } from 'react'
const Component = () => {
const [questions, setQuestions] = useState<any>()
const [question, setQuestion] = useState<string>()
const [answers, setAnswers] = useState<[]>()
useEffect(() => {
fetch('/...')
.then(response => response.json())
.the... |
76389510 | 76389660 | I want to add one a column called "Opt-Numbers" to my data frame with the following values Opt-CMM and Opt-MM based on Numbers column. If the value in Numbers column are greater or equal to 4 then it should add Opt-CMM in the same row of that value or if it is less than 4 then add Opt-MM in the same row. I am also show... | Add a Column with a string value based on other column values R | We can do this with dplyr and case_when ()
library(dplyr)
#example data
data <- structure(list(S.NO = c("P1", "P2", "P3", "P4", "P5", "P6"), Numbers = c(2, 5, 2, 2, 3, 4)), class = "data.frame", row.names = c(NA, -6L))
create new column with filters
data <- data %>%
mutate(Opt-Numbers = case_when(
... |
76387972 | 76388288 | I want to use clip-path to implement effect like: svg with text clip-path, but open in browser it just display an empty
svg. I wrap the path with <g> tag, then it failed.
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32" fill="none" style="
width: 200px;
height: 200px;
">
... | How can I use clip-path to achieve a text effect on my SVG in the browser? | In your example (above) you may remove the wrapping group around the 2 paths and the text and it would work.
<clipPath id="text-path">
<!-- <g clip-rule="evenodd" fill-rule="evenodd"> -->
<path d="M0 0H14V2H2V13H22V10H24V13H32V27H24V32H0V0ZM2 30V27H22V30H2Z"/>
<path d="M16 0L24 8H16V0Z"... |
76390686 | 76391032 | <template>
<v-list-item v-for="(category, i) in categories" :key="i">
<v-item-group multiple @update:model-value="selectedChanged(category)">
<v-item></v-item>
</v-item-group>
</v-list-item>
</template>
<script>
function selectedChanged(category) {
return function(items) {
console.log(`s... | Vuejs. is it possible to pass a function returned from another function to event handler? | Like Estus said in the comments, it looks like what you want can probably be achieved by explicitly passing $event as one of your event handler arguments. (Here is a link to the relevant Vue 3 documentation on $event.) The code would look something like this:
<template>
<v-list-item v-for="(category, i) in categories... |
76389651 | 76389684 | I am trying to implement Job Shop Scheduling with CP-SAT, but I have more than 20000 tasks to schedule and finding optimal solution will take too much time. I'm using solver time limit, but sometimes it gives me feasible solution in assumed time and sometimes not. Could anyone show how to limit solver to find the first... | OR-TOOLS Job Shop Scheduling - stop when find first feasible solution | set the parameter: stop_after_first_solution to true.
See the definition.
|
76387879 | 76388302 | Using JSONATA, is it possible to exclude certain fields that are nested in a deep structure without using object construction? For example, with the following object
{
"collection": [
{
"id": "ABC",
"learningunit": {
"metadata": {
"show... | Is it possible to exclude certain fields using JSONATA? | You can make use of the transform operator and remove all 'value' and 'show' fields from the nested structure:
$$ ~> | ** | {}, ['show', 'value'] |
See it on the live Stedi playground: https://stedi.link/Usc1tpg
Note that if you need to clear those on a specific path only, you can also do it more surgically:
$$
~> |... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.