Posts

Showing posts from 2023

Capybara Element returned by Find method is taking a wrong coordinate

Image
I have running a System Test with Ruby On Rails and Minitest, but an error is shown. Error: edit : please copy and paste anything from a terminal rather than posting pictures -> Error: RequestsTest#test_Admin_User_should_create_request: Selenium: :WebDriver: :Error: :ElementClickInterceptedError: element click intercepted: Element <a id="request__tags-list" href="#" class="input-tag-items" dat a-action="click->input-tag box#itemsClick">...</a> is not clickable at point (686, 23). Other element would receive the click: <header class="request-panel-header" data-controller="request">…</header> (Session info: chrome=120.0.6099.130) test/system/requests_test.rb:480:in execute_test_new_request' test/system/requests_test.rb:54:in block in <class:RequestsTest>' HTML: <a id="request__tags-list" href="#" class="input-tag-items" data-action="cli...

C++ Why does a char variable as a function parameter defined with square brackets not need '&' sign? [duplicate]

I have a simple example. I am changing a variable in a function and then print it outside the function. For the integer and string, we do need & to "inherit" those changes (passing by reference). But for the char defined like below, we do not. Why? #include <iostream> #include <string> #include <stdio.h> void ChangeFunc(std::string &FuncString, char FuncChar[], int &x) { FuncString = 'b'; FuncChar[0] = 'b'; x = 2; FuncChar[1] = '\0'; } int main() { std::string LocString = "a"; char LocChar[2] = {'a','\0'}; int a = 1; ChangeFunc(LocString, LocChar, a); std::cout << LocString << std::endl; std::cout << LocChar << std::endl; std::cout << a << std::endl; } Result is b-b-2 . And if we throw away square brackets for the char : void ChangeFunc(std::string &FuncString, char FuncChar, int &x) { FuncStr...

Angular 17 - ExpressionChangedAfterItHasBeenCheckedError thrown despite calling detectChanges

I'm experiencing a slight issue with Angular and its change detection. I've got a very simple form that allows for additional input containers to be added, and yet every time I click the add button I get an ExpressionChangedAfterItHasBeenCheckedError thrown in the console. When using a standard ngFor the error is thrown in the console, but the new input is still displayed. However, when using Angular's new @for option I get the error thrown in the console, but it also isn't displayed. In both scenarios I made sure to call a detectChanges (also tried markForCheck), but it made no difference. public properties: Map<number, string> = new Map<number, string>(); public addProperty() { const id: number = this.properties.size ? Array.from(this.properties.keys()).reduce((a, b) => a > b ? a : b) + 1 : 1; this.properties.set(id, 'placeholder'); this.changeDetectorRef.detectChanges(); } <button class="btn bt...

Jpa @CollectionTable very slow query

I have this entity @Entity @Table(name = "GEO_MUNICIPALITY", indexes = { @Index(name = "idx_municipalityentity", columnList = "PROVINCE_CODE") }) ... public class MunicipalityEntity { @Id @Column(name = "MUNICIPALITY_CODE", nullable = false) private String code; @Column(nullable = false) private String name; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "PROVINCE_CODE") private ProvinceEntity province; @ElementCollection @CollectionTable(name = "GEO_MUNICIPALITY_POSTAL_CODE", joinColumns = @JoinColumn(name = "MUNICIPALITY_CODE"), indexes = { @Index(name = "idx_municipalityentity_postal_code", columnList = "MUNICIPALITY_CODE") }) @Column(name = "POSTAL_CODE") private List<String> postalCodeList; } @Entity @Table(name = "GEO_PROVINCE") ... public class ProvinceEntity { @...

Reading Glue Catalog from Lambda

Is it possible to connect lambda to glue data catalog to query the data within the catalog tables? If yes, how do I connect it? I am trying to connect Glue catalog to Lambda function to query the tables, but not able to find any information on it. It would be helpful if someone can provide any resource or code for it.

Can't connect to aws mysql rds from mysql workbench for some region

I created aws mysql rds for different region with public access configuration from my free tier account. Following were the regions: N. virginia Singapore Mumbai For the above regions, I can connect only to N. virginia region rds from my local mysql workbench. But for other two regions, I am not being able connect to the workbench. Is there any limitation for other regions? can anyone kindly answer? TIA

How to pass the current Spring Boot version to a custom property

I would like to get the current Spring Boot version and pass it to a custom property. Something like this: my.custom.property=${howtogetthecurrentspringbootversion?} I tried: my.custom.property=${spring-boot.version} my.custom.property=${spring-boot.formatted-version} Unfortunately, it is not resolving to anything, I get the whole ${xxx} without any value (expecting a version, such as 3.2.0). How to get the current Spring Boot version, and pass it to a custom property?

Adding UseProjection to Graphql Query Fails with Unexpected Execution Error in Linq Execution

I am new to Graphql and wanted to try it in an API written in c#. I am using HotChocolate, EFCore 8, dotnet 8. I have the following Classes public class Batch { public Batch() { } public Batch(string batchId, string tenantId, int paymentsCount, decimal totalAmount, string status, string statusDescription) { BatchId = batchId; TenantId = tenantId; PaymentsCount = paymentsCount; TotalAmount = totalAmount; Status = status; StatusDescription = statusDescription; } public string BatchId { get; set; } public string TenantId { get; set; } public int PaymentsCount { get; set; } public decimal TotalAmount { get; set; } public string Status { get; set; } public string StatusDescription { get; set; } [UseFiltering] [UseSorting] public ICollection<Payment> Payments { get; set; } } public class Payment { public Payment() { } public string Id { get; set; } ...

Possibility to "scrape" or "forward" traces (not logs, not metrics) for Spring Boot 3

I would like to find a way to scrape or forward the traces generated by Spring Boot 3 app. We have a Spring Boot 3 app that does not make outbound HTTP calls. The app only takes requests and saves data in DBs. When saving to DB, it generates traces, representing the interaction with DBs. This same app generates application logs. For those, we use promtail / splunk forwarder to tail and forward the logs to the log aggregation backend. This is transparent to the application layer. This same app generates application metrics. For those, we use prometheus, and expose an endpoint, so prometheus comes and scrapes the metrics. The application layer is not sending things on its own. In the above two cases, the app itself is not making any outbound calls to send the logs or the metrics. The application does not have any HTTP clients, and on the network layer, for security reasons, the app itself will not be able to communicate out. The issue arises when it comes to traces. It seems there ...

Overflow properties working differently on a div inside and outside a CSS grid

Image
I have the following structure, which I will call 'list of files' (using Bootstrap 4): .file-component { border: 1px solid red; } .file-component .file-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/> <div class="row"> <div class="col-sm-12 col-md-6 col-lg-4"> <div class="file-component"> <p class="file-name">Some long file name inside the grid that really does not fit inside the available space</p> </div> </div> <div class="col-sm-12 col-md-6 col-lg-4"> <div class="file-component"> <p class="file-name">Some long file name inside the grid that really does not fit inside the available space</p> </div> </div> <div class="c...

why do i recieve the output of an else statement yet the if is true

the problem is that i created an app to compile .c and .py files but whenever i open a pre written file it gives the output of the else which would mean that no file is found this is part of the code def new_file(self): text_area = tk.Text(self.tab_manager) text_area.pack() self.tab_manager.add(text_area, text="Untitled") self.files.append(None) this is the open function def run_file(self): current_file_index = self.tab_manager.index(self.tab_manager.select()) current_file = self.files[current_file_index] if current_file: self.output_bar.config(state='normal') self.output_bar.delete("1.0", tk.END) if current_file.endswith(".c"): file_path = self.tab_manager.tab(current_file_index)["text"] try: subprocess.run(["gcc", file_path, "-o", "a.out"], chec...

Excel VBA for Macbook hide ribbon

I have an Excel spreadsheet that runs on my Windows PC and have been easily able to use VBA to completely hide the Toolbar ribbon. I have not been able to find a way for doing this using VBA on my Macbook Air. I have carried out several searches on the Internet and have not yet found a solution. Is this just a limitation of VBA for Macbooks or is there a way of achieving this using VBA? See screenshots attached illustrating the difference between Macbook Air and PC. Macbook Air Windows 11 Current code: With Application .DisplayFullScreen = True .CommandBars("Full Screen").Visible = False .CommandBars("Worksheet Menu Bar").Enabled = False .DisplayFormulaBar = False End With

How can I check duplicated words within an Array and count them?

I just started programming with JAVA 2 months ago and currently I'm facing an exercise which I don't find the solution for. Until now I control (kind of) the following structures: if (else) , do while , while , for , basic array and matrix management, so the exercise is intended to be solved with some of them. And the exercise says: " Build a simple program that asks for three words and tells you the number of different words or how many are the same. The process will be repeated until one of the words is "exit". " So far this is what I got: String [] names = new String [3]; int index=0; boolean found=false; int position=0; for (int i=0; i<names.length; i++) { if (i==0) { System.out.println("User, give me name"); names[i]=lector.nextLine(); if (names[i].equals("exit")) { break; } } else { System...

Github bot - Unexpected token ; - Glitch

Image
I'm trying to build my own github bot to cherry-pick pull-requests into release branches. There are several examples in Javascript/Typescript and using/not using Probot ( Github ) available on github: Cherry-pick bot (Typescript + Probot) Here's some sort of guide At the moment I can successfully run my bot locally, but it's not working when deployed to Glitch. Here's what I did npx create-probot-app issue_greeter ? App name: issue-greeter ? Description of app: Replies with a greeting when someone opens an issue ? Which template would you like to use? basic-ts => Comment on new issues - written in TypeScript code issue_greeter I want this bot to reside under my organization. So while normally you would do the following: npm start # Visit http://localhost:3000 > Register Github app # Visit https://github.com/settings/apps/manifest I'm doing this manually : Visit smee.io Click Start a new channel Webhook Proxy URL = https://smee.io/2TJ4whCGV...

Detect Tip Popover ViewController being dismissed when clicked outside the tip popover - using iOS 17's TipKit with UIKit

I'm implementing the new iOS 17 TipKit to show some tip popovers the first time a user plays the game I'm developing right now, knowing that those tips will only show for users who have upgraded to iOS 17. Since my app uses UIKit, I've learned most of TipKit's UIKit implementation from Ben Dodson's article and I've updated my code based on Apple's documentation on TipUIPopoverViewController as otherwise I would have been left with a memory leak that Apple's code resolved. In my main ViewController I want to show the first tip popover and then when that one gets dismissed show the second tip popover on another sourceItem . If the user dismisses the popover by clicking the X in the corner then everything works correctly and the second popover shows up. But if the user clicks outside of the popover, it will also dismiss, but that isn't caught by my code so the 2nd tip won't show up. So the question is, how to detect that the tip was dismissed...

Converting and printing resultset from SQL

I'm quite new in SQL and Java and have a question regarding a sample exercise I am doing. I am trying to convert this table: SELECT id, lname, fname, credit, year, course FROM records WHERE id is NOT NULL ORDER BY last_name, first_name; ID lName fName credit year course 01001 Adams John PHD N 1110 01001 Adams John PHD N 2001 01001 Adams John PHD N 2115 02003 Alexander Amy MD N 1002 02003 Alexander Amy MD N 1016 02003 Alexander Amy MD N 1019 02003 Alexander Amy MD N 1008 02003 Alexander Amy MD N 2110 02003 Alexander Amy MD N 2010 02003 Alexander Amy MD N 2030 02003 Alexander Amy MD N 2200 02003 Alexander Amy MD N 2201 02003 Alexander Amy MD N 2310 01400 Anderson Louise PHD N 2311 01400 Anderson Louise PHD N 2361 01400 Anderson Louise PHD N 2062 01400 Anderson Louise PHD N 2008 01400 Anderson Louise PHD N 2002 into Converti...

List products with quantity, sku and brand from all WooCommerce processing orders

I have this code that creates a page in WordPress admin showing the products that are in Processing orders. function register_pending_order_summary_page() { add_submenu_page( 'woocommerce', 'Pending Order Summary', 'Pending Order Summary', 'read', 'pending_order_summary_page', 'pending_order_summary_page_callback' ); } function pending_order_summary_page_callback() { ?> <div class="wrap"> <h1>Pending Order Summary</h1> <p id="pendingordersubtitle">This is a list of all the products needed to complete all 'Processing' orders.<br /><hr /></p> <?php //Create an array to store order line items $output_stack = array(); //Create an array to store order line item ids $output_stack_ids = array(); //Array to display the results in numerical order $output_diplay_array = array(); //SQL code global $wpdb; $orde...

Cookies are sent on localhost but when deployed on vercel the cookies are not sent

I've created a MERN project wherein I'm sending a jwt token in cookies after user's successfull authentication which works fine on localhost and I can make add, remove, fetch API calls which has verifyUser middleware.When I've deployed the frontend and backend on vercel there is some issue I don't know what exactly but the cookies are not sent. //login controller const loginUser = async (req, res) => { const { email, password } = req.body try { // Validators if (!email || !password) { return res.status(400).json({ Error: "Missing fields!" }) } // Check for existing users with the same email const user = await User.findOne({ email }) if (!user) { return res.status(400).json({ Error: "Invalid email address" }) } const comparePassword = await bcrypt.compare(password, user.password) if (!comparePassword) { return res.status(401).json({ Error: "Incorrect Password!" }) } ...

Windows terminal is not properly sending ctrl-space, causing problems with tmux and emacs

When using Windows Terminal to connect to a remote workstation, the transmission chain doesn't pass on certain keyboard inputs such as ctrl-space. Below is a simple illustration of how I understand the transmission chain. The illustration includes the workstation running the command showkey to display any received keyboard codes: Windows laptop Windows Terminal PowerShell SSH client - outputs {keyboard codes} Workstation (Linux) SSH server bash $ showkey -a <- sink of {keyboard codes} I expect showkey to show the following when I, in sequence, type space, ctrl-space and ctrl-d (to end): $ showkey -a Press any keys - Ctrl-D will terminate this program 32 0040 0x20 ^@ 0 0000 0x00 ^D 4 0004 0x04 However, from Windows Terminal, the result is only: $ showkey -a Press any keys - Ctrl-D will terminate this program 32 0040 0x20 ^D 4 0004 0x04 Notice how the line with ^@ ... is missing - the ctrl-space was never received. The missin...

ggplot colorbar align to top when using facets

Image
I am using facetted plots via ggplot that contain a colorbar. I want to scale the colorbar to the size of the facetted plot. Following the ideas of @AllanCameron in this post regarding a single plot and tweaking the function to account for both the strip size and the space between plots, I am able to correctly work out the size of the legend. Thereby, the size of the legend is correctly specified irrespective of the ncol , panel.spacing.y , or strip.text.x specification. However, by default, the legend is centered between the two plots without strips. Adjusting the legend via legend.position or legend.justification did so far not help to correctly specify it. How can I properly align the legend with the top of the chart i.e., the top of the strip (see the plot on the right side for the exptected output)? I only aligned in the right chart the legend to the top without adjusting the size using an external graphics programme. Thus, while the legend height looks too small in the p...

python async with timer and endless loop

I have found two parts of code here for my planned project. The first with two timers ... class Timer: def __init__(self, interval, first_immediately, timer_name, context, callback): self._interval = interval self._first_immediately = first_immediately self._name = timer_name self._context = context self._callback = callback self._is_first_call = True self._ok = True self._task = asyncio.ensure_future(self._job()) print(timer_name + " init done") async def _job(self): try: while self._ok: if not self._is_first_call or not self._first_immediately: await asyncio.sleep(self._interval) await self._callback(self._name, self._context, self) self._is_first_call = False except Exception as ex: print(ex) def cancel(self): self._ok = False self._task.cancel() async def timer1(t...

python pyproject.toml enclose files in package dir

repo package directory: report: report.py template.dat template_testline.dat and in pyproject.toml I have: [tool.setuptools] packages = [ "report" ] but when I install the program the templatefiles are not enclosed in the package, only the report.py file: ls -l /Users/mobj/.pyenv/versions/report/lib/python3.12/site-packages/report/ total 24 drwxr-xr-x 3 mobj staff 96 Dec 1 17:18 __pycache__ -rw-r--r-- 1 mobj staff 11618 Dec 1 17:18 report.py How can I get them enclosed?

network settings for running a boost asio server on localhost

I wrote a client client.cpp and a server server.cpp and they compile well. But I don't know how to connect client.cpp to server.cpp in localhost I wrote the codes with Boost.Asio and they compile well, but I don't know how to make the network settings so that server.cpp always waits for new connections on a specific port. I wanted to connect the client code to the server on a specific port and get the information from the server.cpp, but I don't know the network settings. my OS is Windows 10 client.cpp: #include <cstdlib> #include <cstring> #include <iostream> #include <boost/asio.hpp> using boost::asio::ip::tcp; enum { max_length = 1024 }; int main(int argc, char* argv[]){ try { if (argc != 3){ std::cerr << "Usage: blocking_tcp_echo_client <host> <port>\n"; return 1; } boost::asio::io_context io_context; tcp::resolver resolver(io_context); ...

How to make a uniform margin for multiple components on a single view?

Image
I am porting an old vue2 project to vue3, the same goes for vuetify. I have my app bar in the App.vue . I have a few views on which I am using I am using multiple components. The problem is attached in the screenshots in my question. I want a proper way to align these components in a uniform margin with respect to the appbar in my entire project. This is my app.vue <template> <v-app class="container"> <v-app-bar color="green" class="app-bar"> <v-toolbar-title class="ml-0 pl-4"> <span class="hidden-sm-and-down"></span> </v-toolbar-title> <v-btn rounded depressed dark large @click="gotoHome()"> <h3>Dashboard</h3> <v-icon class="px-2">mdi-ballot</v-icon> </v-btn> <v-btn rounded depressed dark large @click="dialog = !dialog"> <h3>Markets</h3> ...

VSCode ipython cells are not clearing their output on running

I've only encountered this in VSCode: why I want to see only one, last output of the cell. There are no such problem if cell contains print(): with print Version: 1.84.2 (system setup) Commit: 1a5daa3a0231a0fbba4f14db7ec463cf99d7768e Date: 2023-11-09T10:51:52.184Z Electron: 25.9.2 ElectronBuildId: 24603566 Chromium: 114.0.5735.289 Node.js: 18.15.0 V8: 11.4.183.29-electron.0 OS: Windows_NT x64 10.0.22631 Jupyter v2023.10.1100000000 Python v2023.21.13341009

Pagination from two tables in SQL Server

I have two tables with the following schema: Table A : ColumnA, UserId, ... - rest of the schema omitted for brevity Table B : ColumnB, UserId, ... - rest of the schema omitted for brevity The tables can have duplicate values between them. For e.g - Table A row (<some-columnA-value>, 1, ...) and Table B row (<some-columnB-value>, 1, ...) , 1 being the UserId. Now, I have an API which is used to fetch all the UserId values from both tables. With increasing data, I want to now use pagination for this API and would like to modify the queries accordingly. There should also not be any duplicates over the pages or within a page. How do I achieve this? Also a requirement is that I need to use keyset pagination rather than offset pagination since offset pagination gets slower as and when the offset increases. So far, I have thought of using indexed views since there is only 1 column that I require to fetch but since the data keeps changing quite frequently and in large ...

Null checking with primary constructor in C# 12

I using C# 12. In C# 12 I can use primary constructor: public class UserService(IUnitOfWork uow) : IUserService { } Before C# 12 I used null checking for items that I inject in constructor: public class UserService : IUserService { private readonly IUnitOfWork _uow; public UserService(IUnitOfWork uow) { ArgumentNullException.ThrowIfNull(uow); _uow = uow; } } Now how can I do null checking in C# 12 ? Is it need to use fail fast with primary constructor ?

Django with mypy: How to resolve incompatible types error due to redefined field for custom `User` model class that extends "AbstractUser"?

I have an existing Django project which uses a custom User model class that extends AbstractUser . For various important reasons, we need to redefine the email field as follows: class User(AbstractUser): ... email = models.EmailField(db_index=True, blank=True, null=True, unique=True) ... Typing checks via mypy have been recently added. However, when I perform the mypy check, I get the following error: error: Incompatible types in assignment (expression has type "EmailField[str | int | Combinable | None, str | None]", base class "AbstractUser" defined the type as "EmailField[str | int | Combinable, str]") [assignment] How can I make it so that mypy allows this type reassignment? I don't wish to just use # type: ignore because I wish to use its type protections. For context, if I do use # type: ignore , then I get dozens of instances of the following mypy error instead from all over my codebase: error: Cannot determine type of ...

Avalonia window (textboxes) embedded in Autodesk Inventor not accepting input

I'm developing an Autodesk Inventor plug-in and I've chosen to use Avalonia for the UI. Inventor exposes the ability to create a dockable window. I'm not completely sure how it works behind the scenes but you can add a winforms / WPF control to it, by adding the control's handle as child to the dockable window. After looking at some samples I figured out how to add the avalonia control to the dockable window. Everything seems to be working fine, only keypresses are not accepted. (Just backspace & delete) When I run the app from a button press in the ribbon, there are no such problems. I've found some information on StackOverflow and on the Autodesk forum. I thought the problem might be related to Avalonia so I've used the sample here to embed the avalonia app in a WPF window, thinking this would fix the problem. It didn't. This thread on the autodesk forum describes the same problem, but for a WPF window. <Grid> <!--WPF input works--...

Use a Nonlinear Poisson Regression with two independent variables?

I'm looking for a way to use Nonlinear Regression with Poisson for predictive purposes. I would need something similar to Poisson regression , but with some modifications because: I have two data sets that are made up of randomly placed numbers and have no correlation; The two variables are both independent (and not one dependent and one independent); The purpose of the regression will be to obtain a parameter that can be used in the Poisson distribution to calculate probabilities (explained better later), such as in poisson.pmf(2, regression_result) ; Is there something i could use that satisfies the three points above? Any algorithm in some library like scikit learn , scipy , etc? I can't find an algorithm that is useful for my case. I would need something similar to sklearn.linear_model.PoissonRegressor , but for nonlinear regression and for both independent variables My data are: Team_A__goal_scored = [1, 3, 1, 2, 2] (x) Team_B__goal_conceded = [3, 0, 1, 1, 2] (y) ...

Excel: Compounding matrix generation with array inputs

Image
Task: To output an array of scalar products based on input array of boolean values and scalars. Requirements: The solution needs to be formulaic (i.e. contained in one cell) and done without the use of VBA -> the solution needs to be dynamic to accommodate different input arrays. Input array A (Boolean values) >= 2023 2024 2025 2026 2023 1 0 0 0 2024 1 1 0 0 2025 1 1 1 0 2026 1 1 1 1 Input array B (Scalar values) 2023 2024 2025 2026 1.25 1 1.2 1.05 1.35 1.1 1 1.2 1.25 1.15 1.05 1.05 1.3 1 1.1 1.15 1.25 1.1 1.4 1.35 Output array (Compounded scalars) 2023 2024 2025 2026 1.25 1.25 1.5 1.575 1.35 1.485 1.485 1.782 1.25 1.4375 1.509375 1.58484375 1.3 1.3 1.43 1.6445 1.25 1.375 1.925 2.59875 In practice: the columns of Output array are comprised of row-wise products of the Input array B . For example the first column is only the 2023 scalars, bu...

Local host redirecting too many times

I Keep getting this when ever I want to run localhost This page isn’t working localhost redirected you too many times. Try deleting your cookies. ERR_TOO_MANY_REDIRECTS I tried deleting third party cookies. What can I do solve this issue. I download snipe-it database but it does not seem to be working.

Regex, anonymise all matches, per line where there is 1 mandatory match with various optional matches

I've research this quite heavily now but nothing seems to be getting me close Below is an excerpt of a csv file. I need to anonymise certain lines where there is a match found for an email address. Once a match is found I need to also anonymise other certain fields that might also be present on the same line. I read about ? making preceding token's optional so though it would be relatively easy to specific an optional group and a mandatory group but I can't it to work. This is the example data: test1,rod.p@nono.com,bbb,123456789,987654321,aaa,121 test2,aaa,rod.p@yes.com,123456789,aaa,bbb,987654321,122,rod.p@yes.com,aaa,123456 test3,rod.p@yesyes.com,123456789,987654321,aaa,123 Based on the below syntax, I need the line test2 being matched only and specifically the parts aaa [optional as long as the email address has been matched on the same line] bbb [optional as long as the email address has been matched on the same line] rod.p@yes.com [mandatory] (please note the em...

OSDev -- double buffering rebooting system

Hello I'm trying to make a simple os, and I'm currently trying to do double buffering. I have two arrays in the size of the screen and a function that copy the array that currently is being used to the memory of the screen and then swap the being used array to the second one. And there is a function that clear the screen and set it to a specific color. screen.c static u8 *BUFFER = (u8*) 0xA0000; u8 buffers[2][SCREEN_SIZE]; u8 current_buffer = 0; #define CURRENT (buffers[current_buffer]) #define SWAP() (current_buffer = 1 - current_buffer) void screen_swap(){ memcpy(BUFFER, CURRENT, SCREEN_SIZE); SWAP(); } void clear_screen(u8 color){ // set all the memory of the screen to one color memset(&CURRENT, color, SCREEN_SIZE); } memory.c void memset(void* src, u8 val, u32 len){ u8* ptr = (u8*)src; while(len--){ *ptr++ = val; } } void* memcpy(void* dst, void* src, u32 len){ u8 *d = (u8*)dst; const u8 *s...

how to pass an assertion in if condition using cypress without halting the execution in case of assertion failure

I am trying to pass an assertion to if condition and execute a logic when the condition is met and another logic when condition is failed. Since the test is failing on failure of assertion i am not able to achieve the desired result. I tried the following... if(cy.get("div").length\>0) { cy.log("print this") } else { cy.log("print this") } or if(cy.get("div").should('have.length.greaterThan',0) { cy.log("print this") } else { cy.log("print this") }

Find the minimum value for each unique key without using a for loop

I have a numpy array with keys (e.g. [1, 2, 2, 3, 3, 2] ) and an array with values (e.g. [0.2, 0.6, 0.8, 0.4, 0.9, 0.3] ). I want to find the minimum value associated with each unique key without using a for loop. In this example, the answer is {1: 0.2, 2: 0.3, 3: 0.4} . I asked ChatGPT and New Bing but they keep giving me the wrong answer. So, is it really possible to do this without a for loop? Edit 1: What I'm trying to achieve is the fastest speed. Also, in my case, most keys are unique. I considered using np.unique to acquire every key and then compute the min value for every key, but clearly it requires a for loop and a quadratic time. I also considered sorting the arrays by keys and apply np.min on the values of each key, but I doubt its efficiency when most keys are unique. Additionally, according to the comments, pandas.DataFrame has a groupby method which might be helpful, but I'm not sure if it's the fastest (perhaps I'm going to try on my own). Edit 2:...

Python - extend enum fields during creation

Is it possible extend enum during creation? Example: class MyEnum(enum.StrEnum): ID = "id" NAME = "NAME And I need that after creating this enum contains the next fields: ID = "id" NAME = "name" ID_DESC = "-id" NAME_DESC = "-name" I need this to create custom ordering enum for FastAPI project Now I have the next way to create new enum NewEnum = enum.StrEnum( f"{name.title()}OrderingEnum", [ ( f"{ordering_field.upper()}_DESC" if ordering_field.startswith("-") else ordering_field.upper(), ordering_field, ) for ordering_field in itertools.chain( values, [f"-{field}" for field in values], ) ], ) But I need do this automatically, because each module with model have similar enum. Maybe this is possible to solve my problem using MetaClass for my enum class, or override ...

How to format bar chart yearly x-axis to not contain floats

Image
What causes the x-axis to have Year numbers in between the bars and the 0.5 attached to the Population Year ru = px.bar(wakel, x = "Population Year", y = "Population", color = "City") ru.show()

Custom hook with clear and update time not works as per expected

When update the default time with setInterval , it's not working as expected. Instead it's added as a new instance. How to clear the setInterval in the custom hook and update new value? app.jsx import React from 'react'; import './style.css'; import CustomTimer from './Custom'; import { useState, useEffect } from 'react'; export default function App() { const [intervalTime, setIntervalTime] = useState(200); const time = CustomTimer(intervalTime); useEffect(() => { setTimeout(() => { console.log('Hi'); setIntervalTime(500); }, 5000); }); return ( <div className="App"> <h1>Hello CodeSandbox</h1> <h2>Start editing to see some happen! {time} </h2> </div> ); } Custom.js import { useEffect, useState } from 'react'; function CustomTimer(startTime) { const [timer, setTimer] = useState(startTime); useEffect(() => { c...

Mediation analysis with a tobit regression is failing to find the outcome variable

I am trying to run a mediation analysis with the mediation package in R. My outcome variable needs to be modeled with a tobit model (censored data). When I try to run it, it claims that the outcome variable cannot be found, although it is in the dataframe. See reproducable example: library(mediation) test <- data.frame(mediator = c(0.333,0.201,0.343,0.133,0.240), DV = c(0.152,2.318,0.899,0.327,1.117), outcome=c(1.715,1.716,0.544,3.284,3.599)) mediator_model <- lm(mediator ~ DV, data = test) outcome_model <- vglm(outcome ~ mediator + DV, tobit(Upper = 4, Lower = -4), link = "identity",data = test) med <- mediate(mediator_model, outcome_model, treat = "DV", mediator = "mediator") When I run this, I get the error Error in eval(predvars, data, env) : object 'outcome' not found , even though the outcome model runs without a problem.