QuestionId
stringlengths
8
8
AnswerId
stringlengths
8
8
QuestionBody
stringlengths
91
22.3k
QuestionTitle
stringlengths
17
149
AnswerBody
stringlengths
48
20.9k
76390292
76392654
Dates ranges that are found in rule1 but 'not in' rule2 E.g., item_no item_type active_from active_to ruleid 10001 SAR 2022-01-01 2023-05-31 rule1 10001 SAR 2023-07-01 2099-12-31 rule1 10001 SAR 2023-01-01 9999-12-31 rule2 10001 SAR 2020-12-01 2021-12-31 rule2 In this case output will be the date rang...
Oracle Date ranges that are present in parent rows but not in child rows
Adapting my answer to your previous question, from Oracle 12, you can UNPIVOT the dates and then use analytic functions and MATCH_RECOGNIZE to process the result set row-by-row to find the consecutive rows where rule1 is active and rule2 is inactive: SELECT item_no, item_type, active_from + CASE ...
76394383
76394393
I need to add small bracket at the start and end of a Python list (Python 3) My list is list1 = ['1','2','3'] List needed is [('1','2','3')] I know the solution may be simple, but I am not getting it. Thanks in advance Tried fstring and join
Python List formatting with small bracket
Here's one way to print a list in that formatting with a combination of an f-string and str.join: >>> list1 = ['1','2','3'] >>> print(f"[({','.join(repr(i) for i in list1)})]") [('1','2','3')] Note that repr(i) adds quotes around the strings so that they print as '1' instead of 1. Note also that this is converting the...
76391866
76393314
I am an Emacs newbie transitioning from Neovim. I want something that will show me a list of all of my todos across all the files of the project. I've tried the following packages: hl-todo fixmee Both of them can highlight todos, and show a list of all the todos in the current buffer. But, what I need is a list of to...
How to show a list of all my todos across all the files of my project?
I'm not sure about todo modes, but using the rg (ripgrep) package, it is easy to add custom commands. For example, to define a command that searches for 'TODO' or 'FIXME' in the current project, (rg-define-search my-rg-todo :query "(TODO|FIXME)" :format regexp :dir project :files current) There are a lot of o...
76389311
76392934
I'm trying to configure a GitPod or GitHub Codespace so that the README.md gets automatically opened in preview mode at boot time. I managed to open the file as: code README.md but that opens the editor, I'd like to open it in preview only mode.
How can I open a Markdown file in preview mode by default in VS Code?
If you google "github vscode issues markdown open preview by default", you will probably find this issue ticket pretty high up in the search results: Option to automatically open markdown in preview #54776. Quoting Matt Bernier from their comment there: To change this, you can configure the default editor for .md file...
76391982
76393363
Trying to build a dissector in lua where in the ProtoField for one of the values, I map it to a table so that when passed some uint it can get said string from the list of outputs. The current issue is that I have some indexes of 1, 2, and 3, but I also need a range of numbers that correspond to one output string, and ...
Is there a way to represent a range of indexes in a lua table for a dissector?
Generically, a table can contain tables as indices. These tables could each be used to represent a range of indices. A cursory example (note that overlapping ranges are not stable): local range_mt = {} range_mt.__index = range_mt function range_mt:contains(value) return self.lower <= value and value <= self.upper ...
76391998
76393387
In a project with NodeJS and ExpressJS, using Sequelize, I'm attempting to implement server-side pagination and searching const products = await Product.findAll({ where: { [Op.and]: [ { status: { [Op.ne]: -1 }, },{ [Op.or]:[ ...
Sequelize - Is it possible to search all columns of a table with Op.or operator?
If all columns are string type, you can use CONCAT_WS function to search in a whole combined string. const searchCols = ['name', 'description', 'category'].map(sequelize.col); await Product.findAll({ where: { status: { [Op.ne]: -1 }, [Op.where]: Sequelize.where(Sequelize.fn('CON...
76394368
76394404
The command railway up takes your current local project and uploads it directly to railway without having to link a Github repo to your railway project. Does RailwayCLI take into account .gitignore file like Git does? if not what is the proper way to ignore files (not upload them) when using the command. I couldn't fin...
Does RailwayCLI ignore files defined in .gitignore?
No, RailwayCLI does not take into account the .gitignore file. If you want to ignore certain files when using the railway up command, you can use the --ignore-files flag. For example, to ignore all files with the .txt extension, you would use the following command: railway up --ignore-files .txt Update: The -ignore-fi...
76394390
76394420
string <- "this is a funny cat" I want to replace the first 15 characters of string with 'orange`. The desired output is 'orange cat' However, using substr gives me substr(string, 1, 15) <- "orange" > string [1] "oranges a funny cat" which is not the desired output.
How to replace a string defined by starting and ending index by another string in R?
The output of substr should be the pattern of sub. string <- "this is a funny cat" sub(substr(string, 1, 15), "orange", string) [1] "orange cat" Or directly replace the first 15 characters in sub. sub("^.{15}", "orange", string) [1] "orange cat"
76392186
76393456
I have this visual annoyance when I am using VS Code. Whenever a method or class is declared, the "reference" counting is causing the vertical lines that connects the curly braces to break. It is very annoying, I tried finding the settings in user preference but could not find anything. Could someone help me? I find th...
How can I stop codelenses from breaking up indent guides in VS Code?
This is a known issue and as far as I know, there's not much you can do about it for now except wait for it to get handled. If you google "github vscode issues codelens indent guide", you should easily find Indent Guides Have Breaks Where CodeLens UI is Rendered #9604. There, you'll see that one of the maintainers, @al...
76389877
76392983
I have Spring Boot 3.0 based project, Kotlin and Micrometer Tracing (which superseded Spring Cloud Sleuth) Trying to connect Micrometer tracing to OTLP collector, which is part of Jaeger. The configuration class: @Configuration class OpenTelemetryConfiguration( @Value("\${otel.exporter.otlp.traces.endpoint:http://l...
Micrometer Tracing, Spring Boot 3.0, OTLP exporter class not found error
OTel is not stable yet so not every version of the OTel SDK is compatible with every version of Micrometer Tracing due to breaking changes in the OTel SDK. You should delete all of your version definitions and let the Spring Boot BOM define versions for you, this is what you need: implementation 'org.springframework.bo...
76392156
76393483
I have a table contain reference time and a user check-in time. Both data is different in type. Sample data dtime = 2023-06-02 08:23:21 work_time = 08:00-18:00 And my code is... SELECT substring(dtime,-8,5) AS chkin, SUBSTRING(work_time, 1, 5) AS wt1, TIMESTAMPDIFF(MINUTE, substring(dtime,-8,5), SUBSTRING(work_time...
How to find different between two times with sql
Try this: SET @dtime = '2023-06-02 08:28:21'; SET @work_time = '08:00-18:00'; SELECT substring(@dtime,-8,5) AS chkin, SUBSTRING(@work_time, 1, 5) AS wt1, TIMESTAMPDIFF(MINUTE, @dtime, CONCAT(SUBSTRING(@dtime, 1,10), ' ', SUBSTRING(@work_time, 1, 5))) AS min_diff
76392180
76393491
I have a UIStackView that contains multiple arranged subviews. I want to dynamically hide certain views within the stack view when auto layout attempts to reduce the stack view's size. I'm looking for a way to achieve this behavior using auto layout and without manually manipulating the frame. I've tried setting the is...
Hide views in a stack view when auto layout attempts to reduce the stack view size?
When we set .isHidden = true on a stack view's arranged subview, that subview remains in the .arrangedSubviews collection but it is removed from the hierarchy and no longer has a valid frame. Another approach would be to set the .alpha to either 1.0 or 0.0 to "show / hide" the view. We create a custom view subclass - l...
76390199
76392996
The following order of events should happen in my Oracle APEX app: User clicks Submit button in a modal dialog. The configured validations are executed (mostly package functions). If validation is OK, the page is submitted (a package function is called). If no validation error or exception during submit happened, Java...
How to validate and submit a modal dialog, and, when succesful, execute some Javascript
This isn't an answer to your question, because I believe what you want is simply not possible. To understand why, you need to check how APEX processes work. A number of processes run in a pre-rendering phase. These are server-side processes (computations, pl/sql processes, form initialization, etc). The dom is rendere...
76394381
76394421
I am having a problem when I use react hook form + zod in my application, in short the inputs never change value and I get the following error in the console: Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()? my components: // Login.tsx i...
React Hook Form Error on custom Input component
I think what's happening is the {...register("username")}, which gets picked up as ...props in the Input component's props, is using a ref under the hood (this is how the react-hook-form library identifies inputs). You should be able to fix this by converting the Input component to use a forwardRef like this: export co...
76391609
76393867
I am making multiple ajax calls as shown below. Below code works fine If all the calls succeed. But, let's say urlId 3 and 4 failed for some reason. Is it possible to get all the failed urlId's in the fail function? var urlId = [1, 3, 4, 7] let requests = []; for (let i = 0; i < urlId.length; i++) { requests.push($...
Multiple AJAX calls ; get all the failed calls
You would not be able to reliably get all of the failed IDs in the .fail handler because it will fire as soon as any of the deferreds becomes rejected, regardless of the state of the other deferreds. If you want to keep track of which requests succeeded and which failed, I think your best option would be to attach a ca...
76392242
76393891
I have a singleton class: class Singleton { private static instance: Singleton; private constructor() { // Private constructor to prevent instantiation outside the class } public static getInstance(): Singleton { if (!Singleton.instance) { Singleton.instance = new Singleton(); } return S...
Get the instance type of a singleton class in TypeScript
TypeScript assumes that class constructors have a prototype property whose type is the same as the class instance type. This isn't actually true in practice, since generally speaking class fields won't actually be present on the prototype. But TypeScript makes that assumption as an approximation intentionally, and ha...
76394041
76394431
I am attaching some code in here, I have recently added in a link to my portfolio website and the paragraph link is doing something weird, it seems to be aligning funky and I'm not sure what the issue is. I'm wondering if it might be stemming from some other a stylings in the CSS (like nav_links) but I'm unsure how to ...
Why is this one paragraph link showing up funky?
You're making a mistake in your CSS, doing things like this: .nav_link li, a You need to remove those commas. I assume here you're trying to style an a within an li within an element with a class of .nav_link. But that's NOT what you're doing. Instead, this selector is applying a bunch of styles to .nav_link li and se...
76391772
76393963
I'm working on a TypeScript project and I have a generic class AbstractDAL with a generic type parameter T_DEFAULT_RETURN. Inside the AbstractDAL class, I'm trying to extract a nested type that is specified within the T_DEFAULT_RETURN generic type parameter, but I'm facing some challenges. Here's the simplified code st...
Extracting a nested type from the generic parameter of a generic class in TypeScript
The problem is that BaseEntity<T> does not depend on T structurally, and thus inference from BaseEntity<T> to T is, at best, unreliable. TypeScript's type system is largely structural and not nominal. That means types are compared by their structure or shape, and not by what they are named or where they are declared....
76390366
76393192
I am working on multi filter checkbox in react and redux. How to add extra price filter logic when: The price range is less than 250 The price range is between 251 and 450 The price range is greater than 450 Below is the code for the filter reducer. Tried this if else condition but the problem is if multiple check...
How can I include price filter logic in a React filter?
Change the conditions from exclusive OR to inclusive OR by changing from if - else if - else to if - if - if. Example: Start with initially empty filtered result set, and for each filtering criteria filter and append the original state.products array. case actionTypes.FILTER_PRODUCT: ... let filteredData = []; ...
76390529
76393668
I have some content in tinymce 6 editor. I moved the cursor and placed it inside the content and executed tinymce.activeEditor.insertContent(`<span class='dummy'> <div><span style="font-style:italic;font-weight:bold;text-decoration:underline;">This Text is BOLD</span></div> ...
TinyMCE insertHTML modifies some HTML tags
The default behavior is to remove certain elements, such as <div>, when they are inserted using the insertContent method. But you can override this behavior by customizing the editor's schema and adding a rule to allow the <div> element: tinymce.init({ selector: '#your-selector', // other configurations... setup:...
76394423
76394444
I was going through a course in OpenAI's API using an in-browser jupyter notebook page but wanted to copy some example code from there into a local IDE. I installed Python and the jupyter extention in VS Code and the OpenAI library. My code is below: import openai import os # from dotenv import load_dotenv, find_doten...
Do I need any environment variables set to execute some code, call openai's api, and return a response?
Usually, you load your API KEY from your .env file but, as you are hardcoding it, you don't need anything else. The error you are getting might be related to the absence of the topic_list and story definitions.
76385353
76393734
I am trying to test a SQLAlchemy 2.0 repository and I am getting the error: sqlalchemy.exc.IntegrityError: (psycopg2.errors.UniqueViolation) duplicate key value violates unique constraint "professions_name_key" So, although I am mocking the test, it inserts data into the database. What should I do to the test not inser...
SQLAlchemy 2.0 mock is inserting data
This solution don't need to pass the session as parameter. The solution was to mock the Session and not its methods separately. As an advantage, the test is more concise now! import uuid import pytest from src.domain.entities.profession import Profession from src.infra.db_models.profession_db_model import ProfessionsDB...
76383075
76393989
As stated in my question, I would like to access the Fisher weights used in PIRLS model fitting for GLMMs from my glmer() fit in the R package lme4. For such a simple task, I was surprised that I couldn't find any information in the documentation or on the internet at all. By looking at the structure of the glmer fit, ...
How to access the Fisher Weight matrix W from glmer() fit?
This is a harder question to answer than it should be, but let's try. There is a draft paper describing the implementation of glmer (an unpublished sequel to the Bates et al. JSS paper available via vignette("lmer", package = "lme4") in this directory (PDF here), but — although it is useful as background reading — it d...
76394283
76394445
I'm working on Ruby on Rails and I'm trying to put a logo.png image in a bootstrap navbar. so i used this code in app/views/home/_header.html.erb <nav class="navbar navbar-expand-lg bg-primary " data-bs-theme="dark"> <div class="container-fluid"> <!-- <a class="navbar-brand" href="#">Estrutecnia</a> --> <a class...
Why does my logo not appear in the Bootstrap navbar when using Ruby on Rails?
Images are normally placed in the app/assets/images directory. When you render a view using the ActionView image_tag helper, Rails automatically populates the image source for you: image_tag('logo.png') # => <img src='/assets/icon.png> This would be the idiomatic way to handle images in Rails, but of course there's no...
76394394
76394468
I'm relatively new to React and NextJS. I've spent a good 8 hours and a fair amount of research trying to figure this out with no luck! I'm trying to set up a component that picks a word at random from an array, fades this in, then after a delay fades it out and fades in a new word. After hacking together several of my...
React/NextJS Timer-based fade in/fade out of text not working
You are in the right path. But you need to fix a few things. Instead of doing: <span className={`styles.${fadeProp}`}> {WORDS_TO_ANIMATE[wordOrder]} </span> Try it with <span className={fadeProp}> {WORDS_TO_ANIMATE[wordOrder]} </span> The reason being is that you were not setting your css class name s...
76394396
76394477
I am trying to persist some data in my nestjs server so I can then use that data in my client app through http requests. I have created a products.service.ts file with the function getAllData() that fetch some data and creates a new array that is assigned to the variable products (which is the data I'm trying to persis...
store data in memory with nestjs
Don't add the ProductsController and ProductsService to the AppModule. You essentially have two "versions" of the ProductsController and ProductsService being instantiated, and Nest is calling the one that didn't run the onModuleInit from the ProductsModule. Remove them from the AppModule it and should all work.
76390606
76393898
I want to add chatter for Tags. But odoo does not support tracking of many2many fields. What should i do? Any Suggestions. I tried to put tracking=true on tag_ids field but it does not work. I am stuck here. Please give your suggestions.
How can I add a chatter for many2many fields (tags) in Odoo 16?
You can override the _track_mail function to track x2many fields. Check the code just after # Many2many tracking comment in the project module Example: if len(changes) > len(tracking_value_ids): for changed_field in changes: if tracked_fields[changed_field]['type'] in ['one2many', 'many2many']: ...
76392212
76394011
As I was trying to extract the return type of a request that is intersected, I came across the this mismatch of the return type and the inferred type. Here is the shortened url https://tsplay.dev/mAxZZN export {} type Foo = (() => Promise<string>) & (() => Promise<any>) ; type FooResult = Foo extends () => Promise<i...
Typescript return type of intersected functions is mismatched with the inferred type
An intersection of function types is equivalent to an overloaded function type with multiple call signatures. And there are known limitations when dealing with such types at the type level. Unless you're trying to use overloads and have a strong need for them, you should consider refactoring to use a single call signa...
76394330
76394486
I have a question regarding installation of MobSF on my windows 11. its been countless times i tried without any luck. i appreciate the expert here to point out what is my problems.I have downloaded latest MobSF from git C:\Users\User\Documents\Mobile-Security-Framework-MobSF>setup [INSTALL] Checking for Python version...
MobSF unable to install on windows 11
The error message says: The 'decorator==4.4.2' distribution was not found So have you tried simply running pip install decorator==4.4.2? According to this github issue, installing the missing package fixed a similar problem.
76390794
76394082
I would like a function (let's call it detect_undefined) which detects variables used in a function, which are not defined inside the function without running it. Examples: import numpy as np def add(a): return np.sum(a) print(detect_undefined(add)) Output: ["np"] def add(a): import numpy as np return np...
How to detect variables defined outside the function (or undefined) without running the function in python
I'll provide two solutions, the first one doesn't work exactly, but I'll leave the information in case someone sees this post a few years later. Solution1 inspect.getclosurevars or func.__code__.co_names is exactly what it is for. And it should be preferred over the 2nd solution. b = 3 def add(a): return a + b ...
76385145
76393995
I have a weird behavior happening in my code. I've created a Place entity and a SubCategory entity. Because it is a many to many relationship, I created a PlaceSubCategory entity with a composite key. Now, here's what its creation looks like in the DbContext: public DbSet<PlaceSubCategory> PlaceSubCategories { get; set...
Weird behavior in linking table creation in EF Core, adding it in the DbContext but shows two versions in the migration file
The reason was that by creating this linking entity I was doing what EF Core would do anyway which is to create a linking entity in the background that would be showing in the migration file. So my entity got created and EF Core's as well without warning. I deleted my entity and the EF Core's automatically created link...
76391247
76394272
I am working on a React eCommerce website. The designs given to me show a flow for checking someone's credit for approval. When the user hits the "Submit Application" button, it takes them to a page that says "Reviewing Application" with a progress bar that takes about 12 seconds to load. When the bar is complete, the ...
Accessibility Rules Check for Progress Bars
There two WCAG checkpoints at play here. The first is dynamic content added to the page. "Reviewing application..." and then "you're approved (or not)". That falls under WCAG 4.1.3 Status Messages. Just make sure the "reviewing application" indicates that the process is running. I'm guessing you have some kind of anim...
76394452
76394488
I have the problem is that,When i press remove button,whole list is deleted, for example,i add ABC and DEF,this 2 parts, I press one time and ABC also gone! how can i fix it? <!DOCTYPE html> <html> <head> <title>To-Do List</title> </head> <body> <h1>To-Do List</h1>` <input type="text" class="task" pla...
about the remove() function,how can i del the last element only?
The issue you're facing is because in the event handler for the Remove button, you are calling remove() on the taskList, which is the ul containing all your tasks. This will remove the entire ul element from the DOM, thereby deleting all tasks. Instead, you should remove only the last task added to the list. Here's how...
76389619
76394033
Fatal error: Maximum execution time of 300 seconds exceeded on line 171 I am new in the world of drupal My port no.80 is assigned to my ASP server so I changed my Apache server from 80 to 8080 in httpd.conf , BTW I am using XAMPP server I got Error "Fatal error: Maximum execution time of 300 seconds exceeded in C:\xamp...
How to solve Fatal error: Maximum execution time of 300 seconds exceeded in Drupal installation on line 171?
Maybe you're doing it first time. So, you have confused Apache port with mysql port. You can see, I have started Xampp, here I am running Apache, with http and https, in ports (80, and 443) now according to the availability of ports in your pc, you can change them Now, comes the database i.e. MySQL, whose port is norm...
76383192
76394700
I have a D3js Plot wrapped inside a React component (v7). For example a Bar Plot with a data table and a parameter for which column to plot. On change of the plotting variable, I do not want to re-render the whole plot but instead execute a D3 transition animation to the new variable. Right now I have tried it followin...
How can I create a D3 transition animation to update a React component without re-rendering the whole plot?
Here is an example of animated bar chart using React with D3. Just add a useEffect on the SVG element ref and build the chart when ref is valid (when the component is mounted) const MAX_VALUE = 200; const BarChart = ({ data, height, width }) => { const svgRef = React.useRef(null); React.useEffect(() => { co...
76390441
76394100
My understanding is that we can pass the information about which procedure should be used inside a Fortran procedure, either using an argument and declaring it to be a procedure name through a specific interface, or using an argument declared to be a procedure pointer. I do not think I have grasped all pros and cons of...
Procedure pointer vs procedure name as argument of Fortran procedures
A dummy procedure pointer, when contrasted with a non-pointer dummy procedure, may (depending on argument intent and the like): be passed in as disasssociated or undefined, have its association status tested, have its association status changed, pass out information to the calling context. If these capabilities are u...
76394304
76394489
I have a big confusion on what is meant by the general method of converting recursive functions (tail and non tail) to iterative ones using stack. I made this simple example to illustrate the point: int sigma1(int n) { if(n == 0) return 0; else return n + sigma1(n-1); } which of the following versions re...
Confusion regarding converting recursion to iteration using stack
Be sure to post a minimal, reproducible example when you ask a question. That helps everyone understand the question and generate and test potential answers. If you had created such an example, it would be evident that version 1 of your iterative solution never returns and version 2 always returns 0 making neither a go...
76392206
76395043
New to Django here. I have developed a minimum working django website with Postgres as database back-end and nginx/gunicorn as web server on Ubuntu linux. Currently all the files are on my laptop in ~/workspace/djangoapp/src$ in my home directory. I want to now deploy the project to GCP. Which directory, on the product...
Where to host Django project files on deployment server
If you want to deploy your project on Google Cloud Platform, you should follow GCP guidelines. There are step by step guide on how to deploy and run Django app on GCP as for example running "Django on App Engine standard environment". It would be easier to follow the GCP guides for your production server.
76384215
76394322
I have a deployment of Kubeflow. During creation of Jupyter Notebook, we have image name tags that are longer than that can be displayed in the Docker image name list. See the image list in the attached image. Here the names are short, but for our customer the repository URL is a long fqdn of the harbor registry URL....
How to increase Kubeflow Jupyter notebook image name to see the complete path
As I understand it, you'd like to display the repository prefix for your Jupyter images. For this, you can set to false the hideRegistry key in the Jupyter Web App ConfigMap. By default, the value of this key is true, which hides the image repository in the user interface. Search this ConfigMap in kubeflow namespace. I...
76394292
76394541
I have a Pandas DataFrame in the following format. I am trying to fill the NaN value by using the most recent non-NaN value and adding one second to the time value. For example, in this case, the program should take the most recent non-NaN value of 8:30:20 and add one second to replace the NaN value. So, the replaceme...
Filling NAN values in Pandas by using previous values
You can convert your data to_timedelta, ffill and add 1 second: df['col1'] = pd.to_timedelta(df['col1']) df['col1'] = df['col1'].ffill().add(df['col1'].isna()*pd.Timedelta('1s')) Output: col1 0 0 days 08:30:18 1 0 days 08:30:19 2 0 days 08:30:20 3 0 days 08:30:21 4 0 days 08:30:22 Used input: df = pd.Da...
76383655
76395132
I have a docker-compose file version 3.3 describing a Postgres (PostGIS) database instance and a GeoServer (HTTP backend). I run them with no dependencies, but in the same docker network. Later once PostGIS has done its thing and GeoServer has done its thing as well, I configure a GeoServer datastore with the Postgres ...
docker compose 3.3 cannot reach other containers
Are you sure that this command connects to the same docker container ? # this works PGCONNECT_TIMEOUT=2 psql "postgresql://adm_pg_user:1234abcd@localhost:6666/fgag_db" --command "SELECT NOW();" Are you sure that you have correctly configured the container to expose port 6666 ? export MYPG_PORT=6666
76390662
76395154
I'm trying to use the UiKit API PHPickerViewController using KMM and Compose for iOS. import androidx.compose.runtime.Composable import androidx.compose.ui.interop.LocalUIViewController import platform.PhotosUI.PHPickerConfiguration import platform.PhotosUI.PHPickerViewController import platform.PhotosUI.PHPickerViewCo...
Can't use PHPickerViewController delegate with KMM
Since pickerDelegate is NSObject, it's lifecycle follows ObjC rules, not KMM memory model. So as soon as the execution leaves composable block, this objects gets released - as setDelegate takes it as weak reference. You can fix it by storing it using remember. Also using your function is dangerous because you're gonna ...
76388968
76394534
I'm trying to install a package via conda on an M1 mac. This package has a lot of dependencies, some of which seem to be un-satisfiable due to lack of pre-built packages in conda-forge. I know I can trigger building of packages in conda-forge by issuing a PR like shown here, but I'd prefer sending one big PR with all t...
print all unmet dependencies in conda
Trival case: directly missing package First, let's note that this question only has a non-trivial answer when the package in question is noarch. A noarch designation means the package itself is already compatible with osx-arm64. But if it cannot be installed with a plain mamba install, then some non-noarch (compiled) d...
76394525
76394579
I have two arrays Arr1 = [1,1,1,2,2,2,3,3] and Arr2 =[1,1,2,1] Comparing both arrays should return True as there are same occurrences of no. 1. However If Arr2 = [1,1,2] it should return false as the no. Of occurrences of 1 or 2 don't match with the no. Of occurrences of 1 and 2 in Arr1 Even Arr2 = [1,1,2,3,1] should ...
Count exact occurrences of number in array and return True or False
I believe I understand what you want to accomplish. You want to see if the number of occurrences in the second array matches the first. If that's the case, I've used this answer as a basis function allElementsPresent(first, second, matchAll = false) { if (first.length > 0 && second.length === 0) return false; var...
76391948
76395205
I have an API protected by IdentityServer with an associated allowed scope. I have two Identity Server clients with permission to access that allowed scope - one accepts client_credentials (for machine-machine operations), and the other accepts authorization_code (for user-machine operations). Within the API itself, ho...
IdentityServer - how to get grant_type from within a Protected API?
you can have different clientID and client definitions for the different use cases (Authorization code flow cs. client credentials flow). Then in the client definition for each one, you can add Client Claims, that will be included in the access token and will be included for any user. See https://docs.duendesoftware.co...
76390032
76394730
I have Reactive Component which passes data from one screen to another..., trying to call second component via Navigate(name,params) method. but it gives an error saying "undefined method is not a method". Copying component code below. Guid me to clear the error. import React from 'react'; import { StyleSheet, Text...
React Native Component + Navigation with Paramameters not working error undefined is not a method
Destructure navigation from function parameter: import React from 'react'; import { StyleSheet, Text, View, Pressable, } from 'react-native'; import { NavigationContainer } from '@react-navigation/native'; export default function ScreenA({navigation}) { // wrap navigation with curly brackets const onPress...
76388515
76394624
I have a Python function that uses the HuggingFace datasets library to load a private dataset from HuggingFace Hub. I want to write a unit test for that function, but it seems pytest-mock does not work for some reason. The real function keeps getting called, even if the mock structure should be correct. This is the mai...
Why mocking HuggingFace datasets library does not work?
The official Python documentation has this part: where-to-patch. If your module is called my_module, and it does from datasets import load_dataset then you should patch mocker.patch('my_module.load_dataset' so that your module is using the mock. Patching datasets.load_dataset might be too late, since if the import in y...
76390333
76394804
I have an application that displays images using 8-bit ANSI-art. This is handy for viewing images on a remote machine via SSH. When the viewer starts, it replaces all the 8-bit palette values from 16-255 with my standard values. This runs fine on the Mac terminal, but the xterm display flickers because it is trying to ...
Is there an escape code to pause the terminal screen refresh?
Not what the title asks for, but enabling the alternative screen buffer is a fix. Print "\e[?1049h to enable when the program starts and and "\e[?1049l to disable. The Wikipedia entry says little more than that, so it is easy to ignore. Enabling the alternative screen buffer means the application works with a terminal-...
76391329
76395290
I am working on a NER problem—hence the BIO tagging—with a very small dataset, and I am manually splitting it into train, validation, and test data. Thus, to make the first of two splits, I need to sort lists of tuples into two lists based on the count of 'B' in data. I am shuffling data, so the output varies, but it t...
How do you sort lists of tuples based on the count of a specific value?
One possible solution is to get the distribution of the 'B' among indexes of your data. Let's say data was shuffled already, make use of: dict com prehension: https://peps.python.org/pep-0274/ enumarate: https://python-reference.readthedocs.io/en/latest/docs/functions/enumerate.html def get_distribution(data): re...
76391771
76395312
I imported this table from Excel into Jupyter. I was using pandas for this. But now I want to mark markers with cities from table below on my map with popups with the data from colognes A1,A2,A3 and I don't know how to do this. Example: I press on a definite marker and after this the popup appears with this data from ...
How to add the data of this table in markers (pop-up) on map?
To display the pop-up in tabular form at each location, a loop process is performed on each row of the data frame, converting one row from a series to a data frame, and then transposing it. I also adjust the width of the data frame. import pandas as pd import io import folium data = ''' Name A1 A2 A3 LAT LON "Malibu B...
76391309
76395320
Context I'm converting a PNG sequence into a video using FFMPEG. The images are semi-transparent portraits where the background has been removed digitally. Issue The edge pixels of the subject are stretched all the way to the frame border, creating a fully opaque video. Cause Analysis The process worked fine in the pre...
ffmpeg - stretched pixel issue
The issue is related to the video player. Most video players doesn't support transparency, and ignores the alpha (transparency) channel. The video player displays the rgb content of the background even if the background is supposed to be hidden (background pixels are fully according to their alpha value). Apparently, r...
76389179
76395808
i have an excel sheet the has column A which the search value will be in , and it should retrieve results from column B,the code should whenever I enter a value in textbox (txtreg) get results in Listbox (txtledglist) which might be 1 result or more up to 6 . the code that I have is this: whenever I type the search val...
find values on a user form from text box and results shown on a List box
First of all, you should save the first cell you found, so that you don't have to call .Find again, which would restart the search. Also, you don't need to compare against Nothing in the loop condition. Second, I don't clearly understand the line with the comment "Adjusting for header row". Anyway, there is no adjustme...
76391148
76395439
i want to create a navigation bar for my website that includes some links and a company logo upon it. The links should have customize spacing in them and means some at first and some at last of right edge . i also want to include an transformation that when the links are hovered the font size of the links increases wit...
How to avoid links shifting on hover while increasing font size in a navigation bar?
In the example below, there many ascetic changes which are optional. The following CSS is required: li { /* Start vertically and horizontally center of `<li>` when transforming */ transform-origin: center center; /* Original state is at normal size */ transform: scale(1.0); /* When state changes, stretch the...
76394497
76394646
This is my activity: SearchView on top, RecyclerView on middle, and a Button at bottom <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:...
RelativeLayout problem: how to set RecyclerView not to overlap a Button on bottom
Just add following line in recyclerView android:layout_above="@id/btnAddCustomer"
76395850
76395863
I am trying to save links to photos in a topic on an internet forum in a txt file. I tried many ways, but the links of one page are saved in a txt file, and when the loop goes to the next page of the topic, the previous links are deleted and new links are replaced! I want to have all the links together. This is my code...
Writing a large collection of lists to a txt file in Python
You need to append to the file. This can be achieved by using 'a' instead of 'w' as an argument to open(). When using 'w' a file will be created if it does not exist and it will always truncate the file first, meaning it will overwrite its contents. With 'a' on the other hand the file will also be created if it does no...
76394508
76394648
The code I am developing is for mobile site and the animation I expect is as following: Firstly a bigger circle appears such that it covers the whole screen looking like a splash screen and afterwards the bigger circle will transition into smaller circle towards bottom left. Along with that image inside the bigger circ...
How to transition text along with a circle in CSS animation?
A problem is that some properties do not have an initial value set so there is nothing for them to transition from. So you get a sort of jump effect. This snippet removes the flex used for centering the image and instead uses left and bottom in conjunction with translation to center it initially. <!DOCTYPE html> <htm...
76383756
76395526
I want to change database dynamically based on request origin. I create a globalMiddleware which is called on every routes. // middlwares/global.middleware.js import DBController from "../controllers/db.controller.js"; import { db1, db2 } from "../prisma/prismaClient.js"; export default (req, res, next) => { const...
change database based on request origin using expressjs & prisma
finally I modify global.middleware.js file and modify request instead of setting database in a high-level controller : import { prisma_aramgostar, prisma_karen } from "../prisma/prismaClient.js"; export default async(req, res, next) => { const domain = await req.get("x-forwarded-host"); switch (domain) { ...
76388569
76394654
My problem is that I have a modal and the input contains the value from the database. When I press the update button, the unique name validation check if the name already exists in the database. However, if I don't change it, it also checks the unique name validation, which I don't want to happen. Here is the form. <fo...
Codeigniter 4 unique name validation
When using unique values, you check them in this way: (this assumes your AutoIncrement/Primary is roleID For updating values change this: ['rules' => 'is_unique[user_role.role_name]']])) { to this: ['rules' => 'is_unique[user_role.role_name,roleID,{roleID}]])) { More information on placeholders can be found here: htt...
76395784
76395864
Trying to reverse the array. And then print it I am trying to reverse the array by indenting from last to first element of array and copy it to another array. arra will be the reversed array : Here's my code : #include <stdio.h> #include <stdlib.h> int main() { int num, *arr, i; scanf("%d", &num); arr = (i...
Reversing array in C with pointers
For starters this declaration int arra[] = {}; is invalid in C and C++. You should define the array also allocating dynamically memory for it as for the first array or in the worst case you could define a variable length array (provided that the compiler supports VLAs) like int arra[num]; This for loop for(int k = 1;...
76391514
76395561
I have to write algorithm that will generate all possible combinations of different binary strings but under some conditions. The combinations are created by: Replacing binary "1" with "00" Other conditions: Input binary string, if contains 0, they are in pairs always, so "00" The output also can contain 0 only in pai...
Generate all possible combinations basing on binary string and under some conditions
Fundamentally your combinations are built up like a tree. The units are either (0) (1) / \ or / \ 0 1 00 where (.) signifies what was in the original binary string and the strings at the bottom are what you would add as a result. So, like any binary search tree you...
76394580
76394668
Duplicate buttons are in my xml file which is fragment_employee2 I'm only creating one xml file to list out all the list in one xml Here is the code in my https://gist.github.com/Umen14/8d1a205f016fa970369d37f37d4bf15d And here are the images:- enter image description here I tried by removing here and there but the cod...
Duplicate Buttons in xml file using android studio java
This is showing duplicate because you are using same xml in recyclerView item as well as activity layout. which R.layout.fragment_employee2 in your case. You need to define different layout in EmployeeAdapter without button. This will resolve you issue.
76389676
76395916
I am trying to get a WebSocket connection going in my WASM application. I have followed the MSDN tutorial and enabled WebSockets in my Program.cs: app.UseWebSockets(); After that, I added a new controller like this: [AllowAnonymous] [ApiController] [Route("[controller]")] internal class ShellyPlusDataController : Cont...
Cannot connect to WebSocket controller in .Net Core Blazor WASM application
So I had to figure it out on my own. There were 2 things that needed to be fixed: Local WebSocket connection doesn't work. I don't know what needs to be configured to enable WebSockets in local debug mode, but when I deploy the application to a remote IIS server, I can establish a connection. My controller class was i...
76395827
76395933
Why the button event is not avalible with pysimplegui? This is my Code. import os import threading import PySimpleGUI as gui from rsa_controller import decryptwithPrivatekey, loadPublicKey, loadPrivateKey id = 0 target_id = 0 prikey = None def popout(title): gui.popup(title) def read_keys(): print("Opening...
PySimpleGUI button event not working in Python code - why?
layout2 = [ [gui.Text('Connecting with'), gui.Text(str(target_id), key='target_id'), gui.Text("Establishing contact")], [gui.Button('Accept and share my public key', key='accept', enable_events=True), gui.Button('Deny connection invitation', key='denied', enable_events=True)] ] ...
76391959
76395790
my splash code this class App extends StatelessWidget { const App(); @override Widget build(BuildContext context) { Get.put(SplashController()); Get.put(ThemeController()); Get.put(HomeController()); Get.put(LocaleController()); var localeController = Get.find<LocaleController>(); print('...
Flutter: How to update locale in GetxController
As documentation mentioned you need to call; getx Get.changeLocale(Locale("pt")); You need to call this method with expected Locale. Additionally, current locale can be checked with; Get.locale;
76395847
76395972
I have a code like below. var t = [1, 2]; t[2] = t; This creates a circular array. What is the algorithm applied to create this circular array in javascript.
What is the algorithm applied to create a circular array in javascript?
There's no algorithm involved. It's just that your array refers to itself. When a variable or property refers to an object (arrays are objects), what's held in the variable is an object reference, which is a value that tells the JavaScript engine where that object is elsewhere in memory. You can think of it as a number...
76394621
76394679
I am writing code to upload file on file server along with two other string variables as part of HTTP post request. Idea to use multi interface here is to upload multiple file in future. Libcurl version being used here is: 7.44 Here is my program: #include <iostream> #include <string> #include <curl/curl.h> const auto...
curl_formfree not working properly return error: SegFault
The first issue resulting in UB is in WriteCallback: static_cast<std::string*>(userp)->append(static_cast<char*>(buffer), 0, numBytes); You have chosen the overloaded member function basic_string& append( const basic_string& str, size_type pos, size_type count ) that creates std::string from a n...
76391583
76395798
I've a rest controller and one of the endpoint looks like this: @PostMapping(value = "/myapi/{id}", produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE) public ResponseEntity<MyEntity> myApi( @Valid @PathVariable("id") @NotBlank String id, @Valid @RequestBody MyRequestPayload myRequ...
Spring Rest Controller not able to validate path variable when request body is also passed in addition to path variable
@Valid validates complex objects, containing fields annotated with constraint annotations. For this case, you need to use @Validated: The @Validated annotation is a class-level annotation that we can use to tell Spring to validate parameters that are passed into a method of the annotated class. So mark your controlle...
76394660
76394688
I have the following algebraic data type: data Tree a = Empty | Node a (Tree a) (Tree a) deriving (Show, Eq) Also, I have this code snippet: fromJust :: Maybe a -> a fromJust (Just val) = val fromJust Nothing = error "Cannot unpack Nothing." getTreeMinimum :: Ord a => Tree a -> Maybe a getTreeMaximum :: Ord a => Tr...
Fixing a function checking whether the input binary tree is ordered
Since if is an expression in Haskell each if has to have exatly one then and one else but this getTreeMaximum (Node value l r) = if l == Empty && r == Empty then Just value else if l == Empty && r /= Empty then if value < fromJust (getTreeMinimum r) then (getTreeMaximum r) else if l /= Empty && r == Empty then if...
76395953
76395988
I'm trying to parse a To email header with a regex. If there are no <> characters then I want the whole string otherwise I want what is inside the <> pair. import re re_destinatario = re.compile(r'^.*?<?(?P<to>.*)>?') addresses = [ 'XKYDF/ABC (Caixa Corporativa)', 'Fulano de Tal | Atlantica Beans <fulano.tal@at...
Regex to catch email addresses in email header
You may use this regex: <?(?P<to>[^<>]+)>?$ RegEx Demo RegEx Demo: <?: Match an optional < (?P<to>[^<>]+): Named capture group to to match 1+ of any characters that are not < and > >?: Match an optional > $: End Code Demo Code: import re re_destinatario = re.compile(r'<?(?P<to>[^<>]+)>?$') addresses = [ 'XKYDF/A...
76396013
76396051
I have two tables in MySql i.e., subjects and photos and I wished to count the number of photos on each subjects SELECT a.id, a.name, count(a.id) as `refcount`, FROM `subjects` a LEFT JOIN `photos` b ON (a.id = b.subject_id) GROUP by a.id ORDER BY a.name"; returns 1 even when the rowcount()=0. How to fix it I tried...
MySql count with GROUP BY returns 1 even when count is 0
You will need to count photos.id (b.id), if no photos are found for the given subject, the query will return null, count(null) = 0. SELECT a.id, a.name, count(b.id) as `refcount` FROM `subjects` a LEFT JOIN `photos` b ON a.id = b.subject_id GROUP by a.id, a.name ORDER BY a.name;
76383009
76396573
I would like to construct a type from this object: const isSynchronized: Record<SynchronizableField, boolean> = { /* synchronized */ surveyMacroEnvironments: true, coordinateReferenceSystemCrs: true, transactionType: true, epsgTransformation: true, startingAgreementDate: true, expirationAgre...
Building a Type from an object with properties of type Boolean?
As a first step we have to remove that type annotation on isSynchronized; we need the compiler to infer its type and then use that inferred type to compute the key set you're looking for. You could use the satisfies operator instead to make sure the property types are checked against and constrained to boolean: const ...
76394387
76394754
I have a string like this: $str = '[{"action": "verify_with_source","created_at": "2023-05-30T01:39:54+05:30","status": "in_progress","type": "license"}] {"address":null,"badge_details":null,"card_serial_no":null,"city":null,"cov_details":[{"category":"NT","cov":"MCWG","issue_date":"2021-03-30"},{"category":"NT","cov":...
Need help in string replacement in PHP
I would suggest to make it a bit easier instead of replacing all the braces. explode can handle that for you and split the string at a place you want. So just split it at the position ] { where the license ends and the objects starts and add the missing braces afterwards to that strings. <?php $str = "<your long strin...
76395778
76396057
await testCollection.insertMany(testArray, { ordered: false }); I have this code. I found that putting { ordered: false } will prevent getting E11000 error code. But, it looks like, it does not. Is there any way that I can avoid this error? I want to skip and do not insert a doc that has the same _id code.
MongoDB insertMany skip the same _id field to avoid 'code: 11000,'
You can't avoid error, but you can proceed with inserting. See here. For example: MongoDB Enterprise replset:PRIMARY> db.products.insert( ... [ ... { _id: 20, item: "lamp", qty: 50, type: "desk" }, ... { _id: 21, item: "lamp", qty: 20, type: "floor" }, ... { _id: 21, item: "lamp", ...
76391858
76397188
Thanks a lot in advance . trouble in how to generate relationship between two enumerate . %------------------------------- enum weeks = {w1,w2,w3,w4}; array[weeks] of 1..10 : weekShiftQty = [4,5,7,4]; % total shift = 20 enum shift = _(1..20); array[shift] of weeks : shiftWeek = [ % how to generate shiftWeek relationsh...
how to generate relationship between two enumerate with double cycle
Here's a solution, i.e. using [ w | w in weeks, _ in 1..weekShiftQty[w]] to generate the shiftWeek array: enum weeks = {w1,w2,w3,w4}; array[weeks] of 1..10 : weekShiftQty = [4,5,7,4]; % total shift = 20 enum shift = _(1..20); array[shift] of weeks: shiftWeek = [ w ...
76394627
76394768
I am attaching my txt file, graph, and code. Can you please tell me what to change in this code, or why this third straight line is coming in my graph, because I only need two curve lines. In other software like xmgrace it's showing two curves only. import numpy as np import matplotlib.pyplot as plt deformation, poten...
Why are the curves of the data samples connected by a line?
It's simply because you are plotting one line for one set of x,y data, not two lines; hence the one line has to join all points. Try p.scatter(deformation, potential, s = 2, color='b') and see your data as it should be shown. As these are data points this is more appropriate anyway.
76396037
76396113
User input scores of subjects and I need to check if these scores are valid (0->10, step is 0.1 because for exp: 5.25 or 5.1 is acceptable). Below is my code: def Task_22(): mathematics = float(input("Input mathematics score: ")) literature = float(input("Input literature score: ")) english = float(inp...
Check in range of multiple float variables
The range() function lets you create an iterator so you can loop over some integers. When you use i in range(0, 11), you're essentially asking "will range(0, 11) eventually iterate over i", not "is i within the upper and lower bounds of range(0, 11)". Because range() only works with integers, a float will be iterator o...
76396082
76396144
I'm trying to do a search by title and by content, but it gives an error Typeorm select p.*, from post p left join vote v on p.id = v.post_id and v.user_id = $1 where p.is_published = true AND p.title ilike OR p.context::text ilike $2 limit 5 offset $3 const posts = await AppDataSource.query(` select p.*, from p...
I'm trying to do a search by title and by content, but it gives an error syntax error at or near \"OR\
There's a matching pattern missing: p.title ilike OR p.context::text ilike $2 ^ HERE
76390635
76397231
I am testing out scipy.interpolate.RectBivariateSpline for a project where I want to upscale some data to achieve better resolution. My attempt at using both scipy.interpolate.RectBivariateSpline and scipy.interpolate.interp2d results in no interpolation actually happening to the data; I just end up with a bigger matri...
resampling/"upscaling" using scipy.interpolate.RectBivariateSpline no diffrence
Note x_new = np.arange(2*n) : you are evaluating the interpolant outside of the original data range ([0, 9] x [0, 9]) and you get all zeros for the extrapolation. Use x_new = np.arange(2*n) / 2 or some such to actually interpolate between the data points.
76396174
76396198
I have a Service method to update a user from the database: const updateUser = async (user) => { const {firstName, lastName, email, password, phone, dob, countryid, gender, address, role, id} = user; const sql = `UPDATE user set user_firstName = ?, user_lastName = ?, user_email = ?, user_password = ?, user_phon...
Why is my SQL query not updating user properties other than 'user' in Node.js and MySQL?
The user argument you're printing out isn't an object representing a user, it's an array with a single such element. In addition, the object itself doesn't have the firstName and lastName properties you're trying to use, it has firstname and lastname (notice the lowercase ns). Since they aren't there, they get undefine...
76394699
76394770
**I have a mongo document as below. ** { "metadata": { "docId": "7b96a" }, "items": { "content": "abcd", "contentWithInfo": "content with additional info" } } I want to project content field based on the condition whether contentWithInfo field is present or not. If contentWithInfo is present, it's ...
Conditionally project a field value in mongodb
Approach 1 Instead of checking items.contentWithInfo is null, check whether the items.contentWithInfo is missing with $type operator. db.collection.aggregate([ { "$match": { "metadata.docId": { "$in": [ "7b96a" ] } } }, { "$unwind": "$items" }, { "$project...
76396065
76396319
I have this error when launching g4dn.xlarge instance You have requested more vCPU capacity than your current vCPU limit of 0 allows for the instance bucket that the specified instance type belongs to. Please visit http://aws.amazon.com/contact-us/ec2-request to request an adjustment to this limit. However my Service ...
"You have requested more vCPU capacity", when launching G instance
Ensure you are requesting a spot instance when you configure the launch of your vm. There is a check box under the Advanced section of the launch wizard.
76390618
76397387
I am building an Azure Devops Release pipeline and I have a WIX config file in my source code with the following structure <?xml version="1.0" encoding="utf-8"?> <Include> <?define Key ="MyValue"?> </Include> I would like to replace "MyValue" with "MyNewValue" using the Replace Tokens package (link here) Following t...
How to perform XML Element substitution in config.wxi using Replace Tokens?
Why not just pass the preprocessor variable via the .wixproj or command-line (whichever way you are building). That way you avoid the include file completely and have a much simpler solution. I cover this technique in Episode 12 of the Deployment Dojo - All the Ways to Change. Variables and Variables. Directories and P...
76394516
76394776
I am attempting to build a function that processes data and subsets across two combinations of dimensions, grouping on a status label and sums on price creating a single row dataframe with the different combinations of subsets of the summed prices as output. edit to clarify, what I'm looking for is to subset on two dif...
creating a function looping through multiple subsets and then grouping and summing those combinations of subsets
Maybe you can try to use a dict for data instead of a list. Something like: def crossubsetsprice(df): labels = ["SDAR", "NSDCAR", "PSAR"] time_intervals = [7, 30, 60, 90, 120, None] group_dfs = df.loc[ df["Association Label"].isin(labels) ].groupby(["Association Label", 'Status Labelled']) ...
76397512
76397558
I'm running ggplot2 v3.4.1. I created this 2 legend plot that by default it is placing the year2 size legend below the cty color legend. However, I would like the size legend to be on top. library(tidyverse) mpg$year2 = factor(mpg$year) values = c(2,4); names(values) = c("1999", "2008") p = mpg %>% ggplot(aes(x = ct...
ggplot - ordering legends with guides changes continuous legend to discrete
It's simply p + guides(size = guide_legend(order = 1), color = guide_colorbar(order = 2))
76396169
76396390
Is there a more efficient method to convert an integer, in the range 0..255 (in C uint8), to one byte? x = 100 x.to_bytes(1, "big")
python3, converting integer to bytes: which are the alternatives to using to_bytes() for small integers?
More efficient method for a single integer? Probably not. Here's a comparison of the common ones: python -m timeit -s "import struct" "struct.pack('<B', 100)" 2000000 loops, best of 5: 101 nsec per loop python -m timeit "(100).to_bytes(1)" 5000000 loops, best of 5: 81.1 nsec per loop python -m time...
76394463
76394795
Lets t be the time tick i.e. 1,2,3,4,5.... I want to calculate and plot a cumulative decaying function f(inits[],peaks[],peak-ticks,zero-ticks). Preferably in python Where : - inits[] is a list of points at time/tick t where a new 'signal' is introduced - peaks[] is a list of values which must be reached after peak-tic...
Simulate decaying function
For the base case you mentioned, it is actually pretty simple, you just need to define a triangular function that returns the contribution of a specific singal at the current tick t. Then, just sum the contribution of all signals at tick t, that is your answer. In the code below, I implemented the decaying function as ...
76396125
76396459
I have Rails 7 project where I've got tables Pipelines class Pipeline < ApplicationRecord has_many :states, inverse_of: :pipeline, dependent: :destroy end States class State < ApplicationRecord belongs_to :pipeline, inverse_of: :states has_many :items, inverse_of: :state end Items class Item < ApplicationRec...
Rails 7 - Accessing joined model generate new query
but once I call states from pipeline it generates new query without limitation yeah, that's how joins work, it doesn't do more than that so the docs even don't bother adding more information. If you want to access the states within a single query (really it'll end up being 2 queries) you could use includes instead; A...
76397544
76397591
I wanted to know if when you inject your DbContext with DI in a class, within the methods calling that context, should you use the using scope as well ? Or does DI knows about disposal after the method has been executed and/or does transient by default and it's safe ?
When injecting the DbContext using DI and using its private field in a query, should you still use the "using" scope?
When you inject a DbContext using dependency injection (DI), you generally don't need to use the using scope explicitly within the methods calling that context. In the case of a transient registration for your DbContext, a new instance of the context will be created for each method call, and the DI container will auto...
76395882
76396461
I am making a web service with sveltekit and firebase. By the way, when users save images on firebase storage and other users try to use these images, I want to create a signed url and show it on the page to prevent Hotlink. I searched and found that there is a function called getSignedUrl that generates a signed url, ...
How can I generate signed URLs for accessing Firebase Storage images?
The Firebase SDK for Cloud Storage uses a different type of URL, called a download URL. You can generate a download URL by calling getDownloadURL with/on a reference to the file, as shown in the documentation on downloading data through a URL.
76396176
76396467
<image-cropper [imageChangedEvent]="imageChangedEvent" [maintainAspectRatio]="true" [aspectRatio]="4 / 4" format="jpg" (imageCropped)="imageCropped($event)" roundCropper = "true"> </image-cropper> [screenshot attached for your reference] I used roundCropper = "True". But its not working and throwing the error: Ty...
ngx-image-cropper , roundCropper = "true" not working , its showing this error - Type 'string' is not assignable to type 'boolean'
Try to surround roundCropper with [] [roundCropper] = "true"
76387496
76394801
I have error in the fifth line when asp.net try to connect db. 2023-06-02 09:36:59 warn: Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository[60] 2023-06-02 09:36:59 Storing keys in a directory '/root/.aspnet/DataProtection-Keys' that may not be persisted outside of the container. Protected da...
ASP.Net Core can't connect to MySql database in docker
I solved my problem by configuring the connection string like this: "ConnectionStrings": { "ClothingShopConnection": "server=dbClothingShop;port=3306;user=root;password=root;Pooling=true;Max Pool Size=200;database=clothingshop1", "IdentityConnection": "server=dbIdentity;port=3306;user=root;password=root;database=identi...
76396262
76396484
I am creating a bar graph using plotly express inside dash application. The graph is getting displayed but I am having an issue with height.Currently I am using default height and width. Now for eg: dataframe having field column contain 3 entires, the graph looks ok. dataframe having field column contain 10 entires, ...
Plotly: auto resize height
It is possible to define a dynamic width and height based on the dataframe: The number of categories can be found with dataframe['field'].nunique() (assuming you are using pandas). It will impact the height of the figure (since the bar chart is horizontal) The number of entries can be found with dataframe.shape[0] and...
76397539
76397621
I am trying to render a polygon using the GL_TRIANGLES mode for pyglet.graphics.draw but have been running into issues. I have been attempting to render it like I've seen people do in many other places def draw(self): pyglet.graphics.draw( size=int(len(self.coords) / 2), mode=pyglet.gl.GL_TRIANGLES, ...
Rendering a Polygon in Pyglet using GL_TRIANGLES - KeyError 'v' Error
v2f is the old format specification. In Pyglet Version 2.0, this has changed. See the documentation of draw(size, mode, **data). The first parameter is the number of vertices and each vertex has to have 3 components. The format is just f for float. e.g.: self.coords = [x0, y0, z0, x1, y1, z1, ...] pyglet.graphics.draw...
76394514
76394813
Everything here works just fine but I haven't found a way to make it so that when I press the start button it withdraws the Main Menu screen and displays the next one. It already creates the second screen when I run the code and it withdraws the MainMenu Screen before I even click the start button. https://replit.com...
Switching between Tkinter screens with withdraw() method on button click
work on how you ask questions, as this can lead to your account being blocked. I've seen this happen before, so it's good advice. Now, you can do this by using the tkraise() method of the Frame widget. To learn more, please visit this website: https://www.pythontutorial.net/tkinter/tkraise/
76396417
76396495
In the following example: template<typename T> struct MyList { typedef std::list<T> type1; }; template<typename T> class MyList2 { typename MyList<T>::type1 type2; }; I thought that both type1 and type2 are dependent name since both of their types depend on the template parameter. However, why is the first on...
Dependent names vs non-dependent names
A dependent name is, in C++ terms, a name whose grammatical properties are dependent on a template parameter. Names can mean a lot of different things in C++, and the grammatical location where a name can be used depends on certain properties of that name. In order to understand what X x; is trying to do, the compiler ...
76397594
76397628
I am currently working on a c++ project that interacts with the JVM, more specifically I have a block of code that will run before some Java function ( lets call it funcABC ) runs, within this block of code I am able to read/write the registers and stack of the JVM. I am able to get a JavaThread* ptr out of a register,...
Get parameters from JavaThread* before a call takes place
In the JVM, the method parameters are typically passed on the stack or stored in registers, depending on the platform's calling convention. However, the exact layout and location of these parameters can be complex and implementation-dependent. As you have observed, the layout may change during runtime, making it challe...
76394498
76394825
I am using Angular 14 and making a post request to my json server using the pattern like this: myApiCall(data:any): Observable<any> { return this.http.post<any>(url, data).pipe(catchError(this.handleError)); } ( as specified in https://angular.io/guide/http) And then wanted to add 401 (unauthorized) handling to hand...
handling 401 in angular, how does pipe work really?
Try this: myApiCall(data:any): Observable<any> { return this.http.post<any>(url, data).pipe( catchError((err) => if (err.status===401){ // Redirect if unhautorized this.router.navigate(['login']); } ... ); } Note the lambda syntax of the error handler declaration. ...
76396165
76396510
How to create a gridline of 7*7 sqkm using Latitude and Longitude values. These values should be the centroid value of a single square in the grid. I am not sure if I am doing it in the right way. I tried st_make_grid from sf (Simple Features) library but that shows me an empty plot. MyGrid <- st_make_grid(DF, cellsize...
How to create a spatial gridlines using Latitude and Longitude in R
from the documentation of st_make_grid: Create a square or hexagonal grid covering the bounding box of the geometry of an sf or sfc object so you need to convert your dataframe of point coordinates to an sf-object "the_points" (and reproject to a projection accepting metric length units): library(sf) the_points <-...
76397550
76397649
basically I'm creating a flashcards kind of application, where you can either go through the flashcards (which is an array) or you can edit them. in the editing phase, 2 input boxes get rendered with a button next to them where you can edit the text or you can delete that entire index. the problem lies with deletion, o...
incorrect array index being rendered using react tsx upon deletion of an index
It's deleting the right element, your issue is that you're using the array index as they key in React (<div key={index}>), which is a no-no. You're seeing this issue because of a combination of the array key as an index and defaultValue. TL;DR chose a different key, like const flashcards = [ ["key", "a", "1"], ...
76395825
76396539
I have several matrices and I would like to apply something like class(matrix) <- "numeric" to all of them at once, i.e. the class of all matrices should be changed to numeric. Do you know how to do this? dput(matrix[1:3,]) results in structure(c(285.789361223578, 282.564165145159, 273.633228540421, 256.789452806115, ...
Efficient way to change the class of several matrices in R
In this examples all matrix variables of the current environment are converted to numeric. See the warning in the case where matrix cannot be converted to numeric. var1 <- matrix(1:10, 5, 2) var2 <- matrix(as.character(5:13), 3,3) var3 <- letters[1:5] var4 <- matrix(letters[1]) print(sapply(mget(ls()), typeof)) #> ...