2023-12-31

Capybara Element returned by Find method is taking a wrong coordinate

I have running a System Test with Ruby On Rails and Minitest, but an error is shown.

Error: enter image description here

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="click->input-tag-box#itemsClick"></a>

My Test:

tags_list = find("#request__tags-list")
puts tags_list.rect
tags_list.click  # click on link

I tried using click_link method but it didn't work either. The same error is shown.

I noticed that "tags_list.rect" prints coordinates that do not correspond to the tags_list coordinates.

#<struct Selenium::WebDriver::Rectangle x=316.6037902832031, y=31.733491897583008, width=739, height=20>

when in reality, the Y coordinate is much further down the page, 480 approximately.

Some idea what is happening.

Thanks!

SO: Windows 11

Ruby Version: ruby 3.2.2 (2023-03-30 revision e51014f9c0) [x64-mingw-ucrt]

Rails Version: Rails 7.0.8



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)
{
    FuncString = 'b';
    FuncChar = 'b';
    x = 2;

    //FuncChar[1] = '\0';
}

int main()
{
    std::string LocString = "a";
    char LocChar = {'a'};
    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-a-2.

I've read a lot about pointers, but didn't find the exact reason for this.



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 btn-primary" (click)="addProperty()">+</button>

      <div class="d-flex flex-column">
        <ng-container *ngFor="let attribute of properties.entries()">
          <span></span>
        </ng-container>
      </div>

I'd greatly appreciate any insight into the issue, thanks in advance.

I've tried using both an ngFor as well as Angular's new @for option, the only difference between the two is that when using the @for the new data isn't displayed in addition to the console error. I've also attempted calling the change detector manually but it had no impact.



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 {
    @Id
    @Column(nullable = false)
    private String code;
...
}

Now my apis need to display all municipalities (with all municipality postal codes) with a given province code, so i have a repository class like this:

@Repository
public interface MunicipalityJpaRepository extends JpaRepository<MunicipalityEntity, String> {
    List<MunicipalityEntity> findAllByProvinceCode(String province);

    @Query("select m from MunicipalityEntity m left join m.postalCodeList postalCodeList where m.province.code = ?1")
    List<MunicipalityEntity> findByCode(String code);
}

The two methods do the same thing and I tried in both way (an the result is the same) because when i call getPostalCodeList() the query is very slow because it make a select for every result of municipality (to retrive the postal codes).

How can I improve the performances? Also, since I always search municipalities by code, is a good idea to make the index like in the code? Thank you!

I tried both using jpa repository and custom query. I was expecting a fast query execution time but the execution is very slow because after the join query the application make a query for each resulted municipality, to fetch the postal codes.



2023-12-28

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.



2023-12-26

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



2023-12-20

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; }
    public string PayeeName { get; set; }
    public string CheckNumber { get; set; }
    //public List<string> InvoiceNumbers { get; set; }
    public DateTime PaymentDate { get; set; }
    public string Status { get; set; }
    public string StatusDescription { get; set; }
    public decimal Amount { get; set; }
}

This is the Grapql Query

public class BatchesQuery
{
    // Resolver
    [UsePaging(IncludeTotalCount = true)]
    [UseProjection]
    [UseFiltering]
    [UseSorting]
    public IQueryable<Batch> Batches([Service] PaymentDbContext paymentDbContext, string tenantId, IResolverContext context)
    {
        var paymentBatchesQueryable = paymentDbContext.PaymentBatches
            .Where(pb => pb.TenantId == tenantId)
            .OrderByDescending(pb => pb.CreatedTimestamp)
            .AsNoTracking();
        var paymentRequests = paymentBatchesQueryable.SelectMany(pb => pb.PaymentRequests);
        var payments = paymentRequests.Select(pr => new Payment()
        {
            Id = pr.PaymentRequestExternalId,
            PayeeName = pr.Payee.Name,
            CheckNumber = pr.Number,
            //InvoiceNumbers = pr.RemittanceDetails.Select(rd => rd.Number).ToList(),
            PaymentDate = pr.RequestDate,
            Status = pr.PaymentRequestStatusType.ToString(),
            StatusDescription = pr.PaymentRequestStatusType.ToString(),
            Amount = pr.RemittanceDetails.Sum(rd => rd.Net)
        });

        var paymentBatches = paymentBatchesQueryable
            .Select(pb => new Batch(pb.PaymentBatchExternalId,
                pb.TenantId,
                pb.PaymentRequests.Count,
                pb.PaymentRequests
                    .SelectMany(pr => pr.RemittanceDetails)
                    .Sum(rd => rd.Net),
                pb.PaymentBatchStatusType.ToString(),
                pb.PaymentBatchStatusType.ToString())
            {
                Payments = payments.ToList()
      
            });
       

        return paymentBatches;
    }
}

This is my Setup in Program.cs

builder.Services.AddGraphQLServer()
    .AddQueryType<BatchesQuery>()
    .AddProjections()
    .AddFiltering()
    .AddSorting()
    .RegisterDbContext<PaymentDbContext>();

I get the following error when I run this query:

query{
  batches(tenantId: "yKYrJLSUrE6XDWkrQC0e"){
    nodes{
      batchId
      payments{
        id
      }
    }
  }
}

Response:

{
  "errors": [
    {
      "message": "Unexpected Execution Error",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "batches"
      ],
      "extensions": {
        "message": "The LINQ expression 'p1 => new Payment{ Id = p1.Id }\r\n' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.",
        "stackTrace": "   at Microsoft.EntityFrameworkCore.Query.RelationalSqlTranslatingExpressionVisitor.VisitLambda[T](Expression`1 lambdaExpression)\r\n   at Microsoft.EntityFrameworkCore.Query.RelationalSqlTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)\r\n   at Microsoft.EntityFrameworkCore.SqlServer.Query.Internal.SqlServerSqlTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)\r\n   at Microsoft.EntityFrameworkCore.Query.RelationalSqlTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)\r\n   at Microsoft.EntityFrameworkCore.SqlServer.Query.Internal.SqlServerSqlTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)\r\n   at Microsoft.EntityFrameworkCore.Query.RelationalSqlTranslatingExpressionVisitor.TranslateInternal(Expression expression, Boolean applyDefaultTypeMapping)\r\n   at Microsoft.EntityFrameworkCore.Query.RelationalSqlTranslatingExpressionVisitor.TranslateProjection(Expression expression, Boolean applyDefaultTypeMapping)\r\n   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.Visit(Expression expression)\r\n   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.VisitMemberAssignment(MemberAssignment memberAssignment)\r\n   at System.Linq.Expressions.ExpressionVisitor.VisitMemberBinding(MemberBinding node)\r\n   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.VisitMemberInit(MemberInitExpression memberInitExpression)\r\n   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.Visit(Expression expression)\r\n   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.Translate(SelectExpression selectExpression, Expression expression)\r\n   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.TranslateSelect(ShapedQueryExpression source, LambdaExpression selector)\r\n   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)\r\n   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)\r\n   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.Translate(Expression expression)\r\n   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.Translate(Expression expression)\r\n   at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutor[TResult](Expression query)\r\n   at Microsoft.EntityFrameworkCore.Storage.Database.CompileQuery[TResult](Expression query, Boolean async)\r\n   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](IDatabase database, Expression query, IModel model, Boolean async)\r\n   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass12_0`1.<ExecuteAsync>b__0()\r\n   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)\r\n   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteAsync[TResult](Expression query, CancellationToken cancellationToken)\r\n   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.ExecuteAsync[TResult](Expression expression, CancellationToken cancellationToken)\r\n   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1.GetAsyncEnumerator(CancellationToken cancellationToken)\r\n   at System.Runtime.CompilerServices.ConfiguredCancelableAsyncEnumerable`1.GetAsyncEnumerator()\r\n   at HotChocolate.Types.Pagination.QueryableCursorPagination`1.ExecuteAsync(IQueryable`1 query, Int32 offset, CancellationToken cancellationToken)\r\n   at HotChocolate.Types.Pagination.CursorPaginationAlgorithm`2.ApplyPaginationAsync(TQuery query, CursorPagingArguments arguments, Nullable`1 totalCount, CancellationToken cancellationToken)\r\n   at HotChocolate.Types.Pagination.QueryableCursorPagingHandler`1.ResolveAsync(IResolverContext context, IQueryable`1 source, CursorPagingArguments arguments, CancellationToken cancellationToken)\r\n   at HotChocolate.Types.Pagination.CursorPagingHandler.HotChocolate.Types.Pagination.IPagingHandler.SliceAsync(IResolverContext context, Object source)\r\n   at HotChocolate.Types.Pagination.PagingMiddleware.InvokeAsync(IMiddlewareContext context)\r\n   at HotChocolate.Utilities.MiddlewareCompiler`1.ExpressionHelper.AwaitTaskHelper(Task task)\r\n   at HotChocolate.Execution.Processing.Tasks.ResolverTask.ExecuteResolverPipelineAsync(CancellationToken cancellationToken)\r\n   at HotChocolate.Execution.Processing.Tasks.ResolverTask.TryExecuteAsync(CancellationToken cancellationToken)"
      }
    }
  ],
  "data": {
    "batches": null
  }
}

I tried doing the recommendations provided in the response but none of them worked. This error goes away when I remove UseProjections annotation.

I am not sure what's happening. Could someone please explain ?



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 is no way to scrape or forward the traces, only for the app to create some network outbound calls, which we cannot do.

Is there a way for Spring Boot apps to not send the traces directly?



2023-12-17

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

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="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>

Each file component in this 'list of files' is composed of a p tag inside a div1. To make things responsive, the div should have a length that is determined by the bootstrap grid classes col-sm-12 col-md-6 col-lg-4, depending on the size of the screen. At certain breakpoints, the items in the divs occupy a different number of columns, until they are eventually stacked on top of each other. At all times, the p tag should fit inside the div width, cutting off any text that falls outside the div.

For example, if the text is short (or the div is wide enough), it is all visible:

Short name

But, if it is long (or the div is narrow), we get:

Long name

Now, this works pretty well as it is. For a wide screen:

Wide screen

And for a really narrow screen:

Narrow screen

The problem appears when I try to put all this inside a CSS grid layout:

.file-component {
  border: 1px solid red;
}

.file-component .file-name {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.grid-container-component .grid-central-container {
  grid-area: cnt;
  border-left: solid 2px;
  border-right: solid 2px;
}

/* Medium sized screens (900px < width < 1400px) */
.grid-container-component {
  display: grid;
  border: solid 2px;
  grid-template-columns: 1fr 7fr 1fr;
  grid-template-rows: 1fr;
  grid-template-areas: "lt cnt rt";
  margin-top: 30px;
}

/* Wide screens (> 1400px wide) */
@media (min-width: 1400px) {
  .grid-container-component {
    grid-template-columns: 1fr 5fr 1fr;
    grid-template-areas: "lt cnt rt";
  }
}

/* Small Screens (< 900px wide) */
@media (max-width: 900px) {
  .grid-container-component {
    grid-template-columns: 1fr;
    grid-template-areas: "cnt";
  }
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>

<div class="grid-container-component">
  <div class="grid-central-container">
    <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="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>
  </div>
</div>

When the screen is wide, all works as expected. For example (CSS grid is shown in black):

Large screen CSS grid

However, for very narrow screens, it seem the p tag does not let the div.file-component become shorter than the text it contains. Therefore, the div.file-component overflows on the right of the grid and a horizontal scroll bar appears on the bottom:

Overflow

Overflow 2

The four lower file components are outside the grid, and behaving as expected, to see the comparison. Any idea why this could be happening?? Any alternative ways of doing this are welcome too!


1In reality there are more things inside this div, but for the simple example this is good enough.



2023-12-15

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"], check=True)
                    output = subprocess.run(["./a.out"], capture_output=True).stdout.decode()
                    self.output_bar.delete("1.0", tk.END)
                    self.output_bar.insert('1.0',output)
                except subprocess.CalledProcessError as e:
                    error = e.stderr.decode() if e.stderr else str(e)
                    self.output_bar.delete("1.0", tk.END)
                    self.output_bar.insert('1.0', error)

            elif current_file.endswith(".py"):
                file_path = self.tab_manager.tab(current_file_index)["text"]
                try:
                    output = subprocess.check_output(["python3", file_path], stderr=subprocess.STDOUT).decode()
                    self.output_bar.delete("1.0", tk.END)
                    self.output_bar.insert('1.0', output)
                except subprocess.CalledProcessError as e:
                    error = e.output.decode() if e.output else str(e)
                    self.output_bar.delete("1.0", tk.END)
                    self.output_bar.insert('1.0', error)
            else:
                messagebox.showerror("Error", "Only C and Python files can be executed!")
                self.output_bar.delete("1.0", tk.END)
                self.output_bar.config(state='disabled')
        else:
            self.output_bar.config(state='normal')
            self.output_bar.delete("1.0", tk.END)
            self.output_bar.insert("1.0", "No file found")
            self.output_bar.config(state='disabled')

i tried moving the text_area outside the function new_file and puting it on the same level as the other widgets but that didnt work then i tried a bunch of other stuff i forgot about



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


2023-12-14

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.out.println("Give me another name");
                names[i]=lector.nextLine();
                i=position;
                found=false;
                if (names[i].equals("exit")) {
                    break;
                }
                do {
                    if (names[position].equals(names[i-1])) {
                        found=true;

                    }
                    index++;
                } while (position>=0 && !found);
                
            }
        }
        System.out.println("Repeated words: "+index);

So I have to use the scanner and let the user write three words under the previous rules.

I'm talking about arrays as it's the first and only way I find to solve the problem, but there may be others.
I'm getting an out of bounds error and I honestly have no idea what can I do. There are probably other easier and more optimal ways to do it, but as I said the academy expect an answer from us using the "basic" knowledge we have at this point. However, every approach will be a huge help.



2023-12-13

Github bot - Unexpected token ; - Glitch

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:

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:

Smee.io - Start new channel

  • Click Start a new channel

    • Webhook Proxy URL = https://smee.io/2TJ4whCGVUpsHdRr
    • Webhook Secret = bJpKnpXCsnhoJYU6O9Z5CEy6eSZ45tdP (random string 1)
  • Now move to the project. Copy .env.example as .env and paste the WEBHOOK_PROXY_URL and WEBHOOK_SECRET

  • Visit the Apps page under your Github Organization (https://github.com/organizations/ORGNAME/settings/apps) and click New GitHub App

New Github app

Here are all other instructions I did (and wrote down while doing them)

But for some reason my Glitch app won't start, and gives the following error:

Glitch app for github bot

There's no WEBHOOK_PROXY_URL, but a WEBHOOK_URL here (as per instructions).

/rbd/pnpm-volume/725725db-f67a-46e6-9310-065c08ff5138/node_modules/.registry.npmjs.org/lru-cache/9.1.2/node_modules/lru-cache/dist/cjs/index.js:27
        onabort;
               ^
SyntaxError: Unexpected token ;
    at Module._compile (internal/modules/cjs/loader.js:723:23)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Module.require (internal/modules/cjs/loader.js:692:17)
    at require (internal/modules/cjs/helpers.js:25:18)
    at Object.<anonymous> (/rbd/pnpm-volume/725725db-f67a-46e6-9310-065c08ff5138/node_modules/.registry.npmjs.org/@octokit/auth-app/4.0.13/node_modules/@octokit/auth-app/dist-node/index.js:65:24)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)

Note that the generated bundle is already CommonJS

Node on Glitch

What's causing this. I noted somewhere that Glitch seems to be using Node 10, but since everything is locally built that shouldn't be a problem?

Also, is the SMEE-channel still used when deployed to Glitch, or is this only for development?



2023-12-12

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 when it was clicked outside of the popover?
With TipKit, a lot of the work is done for you so there's little code for creating that TipUIPopoverViewController itself.
So when researching this issue, since few people have already adopted the new TipKit, I found similar questions being asked for dismissing a regular popover ViewController and I tried to adapt some of the answers I found there, but without success - see below.

Here's the code I have and how I tried to solve this issue.
First I created 2 structs, one for each Tip, the 1st one is called PauseTip and the 2nd one is FreezeTip. In FreezeTip I set a rule with a boolean called pauseTipDisplayed so that that 2nd tip will only show if that boolean is true.
This rule is set up inside the 2nd struct as follows:

struct FreezeTip: Tip {
     
       @available(iOS 17.0, *)
       @Parameter
       static var pauseTipDisplayed: Bool = false
     
       @available(iOS 17.0, *)
       var rules: [Rule] {
           #Rule(Self.$pauseTipDisplayed) { $0 == true }
       }
       [...]
}

So now all I need to do is set pauseTipDisplayed to true when the first tip was dismissed and this 2nd tip will show up.

In my ViewController I added the following properties:

private var pauseTip = PauseTip()
private var pauseTipObservationTask: Task<Void, Never>?
private weak var pauseTipPopoverController: UIViewController?
     
private var freezeTip = FreezeTip()
private var freezeTipObservationTask: Task<Void, Never>?
private weak var freezeTipPopoverController: UIViewController?

Then I wrote 2 functions to handle each tip popover and I'm calling them where needed (I didn't put them in viewDidAppear as shown in the 2 examples I learned from because that would have been too early for my needs).
Here's the 1st function:

@available(iOS 17.0, *)
func handlePauseTip() {
    pauseTipObservationTask = pauseTipObservationTask ?? Task { @MainActor in
        for await shouldDisplay in pauseTip.shouldDisplayUpdates {
            if shouldDisplay {
                let pauseTipContoller = TipUIPopoverViewController(pauseTip, sourceItem: pauseButton)
                pauseTipContoller.popoverPresentationController?.backgroundColor = .purple
                     
                DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                    self.present(pauseTipContoller, animated: true)
                }
                     
                pauseTipPopoverController = pauseTipContoller
                     
            } else {
                if presentedViewController is TipUIPopoverViewController {
                    dismiss(animated: true)
                    pauseTipPopoverController = nil
                    FreezeMazeTip.pauseTipDisplayed = true  // This will affect the rule to show the 2nd tip popover
                         
                    }
            }
        }
    }
}

You can see that the last row in the else statement is changing the boolean flag to allow showing the 2nd tip popover.
The function for the 2nd tip is identical just using different names, except for setting the boolean flag so I won't copy it again.

Finally, when I deinit the ViewController I run the following or else the whole VC will remain in memory and cause a memory leak:

pauseTipObservationTask?.cancel()
pauseTipObservationTask = nil
        
freezeTipObservationTask?.cancel()
freezeTipObservationTask = nil

As I wrote above, all of this works fine if the user dismisses the first tip by clicking on the X on top of the popover.
But if the user clicks outside the popover and that popover closes, the 2nd tip never shows up.

Here are several things I tried to resolve this issue:

  1. I tried checking isBeingDismissed. I added this check in the else clause at the end of the function so that part would then look like this:
            } else {
                if pauseTipPopoverController != nil {
                    if pauseTipPopoverController!.isBeingDismissed {
                        FreezeTip.pauseTipDisplayed = true  // This will affect the rule to show the 2nd tip popover
                    }
                }
                     
                if presentedViewController is TipUIPopoverViewController {
                    dismiss(animated: true)
                    pauseTipPopoverController = nil
                    FreezeTip.pauseTipDisplayed = true  // This will affect the rule to show the 2nd tip popover
                         
                    }
            }

But that didn't help. Checking with the debugger I found that when the user dismisses by clicking outside the popover, this else statement is never even reached.
Should I put this check elsewhere in my code?

  1. I tried using the following delegate method: presentationControllerDidDismiss. For that to happen I made the following changes. I made my ViewController conform to the following:
class ViewController: UIViewController, UIPopoverPresentationControllerDelegate {
...

Then in viewDidLoad I set the following:

pauseTipPopoverController?.presentationController?.delegate = self

TipUIPopoverViewController has a presentationDelegate, but I wasn't successful to access it because I defined pauseTipPopoverController as a UIViewController and this presentationDelegate requires a TipUIPopoverViewController.
I can't define a TipUIPopoverViewController property or else the whole class will require iOS 17.0 and I can't limit my whole app like that (just having the Tips in iOS 17.0 is ok).

Then I added the following method:

func presentationControllerDidDismiss(_ presentationController: UIPresentationController) {
    if #available(iOS 17.0, *) {
        if presentationController is UIPopoverPresentationController {
            FreezeTip.pauseTipDisplayed = true
        }
    } else {
        // Fallback on earlier versions - do nothing
    }
}

Here again, that didn't help and it seems like this method is never called when the user dismisses the popover by clicking outside of it.
Did I declare the delegate incorrectly?

I tried many more things that I researched, but they all gave me constant errors.

I did implement a simple workaround for now. In handlePauseTip I added the following line:

pauseTipContoller.isModalInPresentation = true

That would disable dismissing the popover when clicking outside of it and the only way to dismiss it is to click on the X. Doing so everything works correctly and the 2nd popover shows up right on time. But I think it's a lesser user experience as I wouldn't want to force the user to dismiss one way only.
So I do want to catch it when the user clicks outside of the popup.

Any ideas would be very welcome. Thanks!



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 Converting the column Year N to:

Year 01: Has 1110

Year 02: Has 2110

Year 03: Does not have (1110; 2110; 3110)

So that the program will print out something like this:

ID lName fName credit year
0100 Adams John PHD 01
02003 Alexander Amy MD 02
01400 Anderson Louise PHD 03

I have a resultset coded something like this:


String SQL = " SELECT id, lname, fname, credit, year, course "
           + " FROM records "
           + " WHERE id is NOT NULL "
           + " ORDER BY last_name, first_name; "
PreparedStatement printSQL = connection.prepareStatement(SQL);
ResultSet rs = printSQL.executeQuery();

while(rs.next()) {
     if(year.equals("N") && course.equals("1110")) {
          year = "01";
     }
     else if(year.equals("N") && course.equals("2110")) {
          year = "02";
     }
     else if(year.equals("N") && (!course.equals("1110") 
            && !course.equals("2110")&& !course.equals("3110"))){
          year = "03";
     }
}

But it only either checks the first or the last person and not all the row that either has 1110, 2110 or doesn't have 1110, 2110 and 3110. Any help is appreciated!



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;
  $order_line_items;
     
  //Get the order ID of processing orders
  $order_ids = $wpdb->get_results( $wpdb->prepare("SELECT ID FROM {$wpdb->prefix}posts where post_type = %s and post_status = %s;", 'shop_order', 'wc-processing' ));
 
  //Collect the order IDs and add products to the pick list
  foreach($order_ids as $an_order_id) {
 
        //Collect all order line items matching IDs of pending orders
        $order_line_items = $wpdb->get_results( $wpdb->prepare("SELECT * FROM {$wpdb->prefix}woocommerce_order_items where order_id = %d and order_item_type = %s;", $an_order_id->ID, 'line_item'));
         
       //Extract the order line item
        foreach($order_line_items as $line_item) {
 
           //Add it to the array
           $pair = array($line_item->order_item_name, $line_item->order_item_id);
              array_push($output_stack, $line_item->order_item_name); //Now we've got a list of line items
          array_push($output_stack_ids, $pair); //Now we've got a list of line ids
 
        }
    }
 
    //Count the number of occurances of each value
    $occurences = (array_count_values($output_stack));
 
    // Print output
    echo '<table><tr><td style="width: 100px;"><strong>Quantity</strong></td><td><strong>Product</strong></td></tr>';
     
    if(count($occurences)>0){
         
        $cumulative_count = 0;
         
        //Loop through each different product in our list
        foreach ($occurences as $product_name => $quantity) {
             
             //Go through the list of ALL line items from earlier 
            foreach($output_stack_ids as $the_line_item) {
                
                //We only want to cumulatively add the quantity if the line item name matches the current product name in the list of unique products
                if ($product_name == $the_line_item[0]) {
                     
                //Reset the quanitity to zero, because we don't need to know the number of instances if we're counting stock
                 $quantity = 0;
             
                //For each unique line item, we want to retrieve the quantity
                $order_line_item_quantity = $wpdb->get_results( $wpdb->prepare("SELECT meta_value FROM {$wpdb->prefix}woocommerce_order_itemmeta where meta_key = %s and order_item_id=%d", "_qty", $the_line_item[1]));
 
                 //We've now got the quantity for each line item. Add them all together.
                  foreach($order_line_item_quantity as $item_quantity) {
                       
                      //The total quantity is the combined _qty of each instance of a unique line item
                    $cumulative_count = $cumulative_count + ($item_quantity->meta_value );
                    
                  }
                  
                }
                   
            }
             
             $quantity = $cumulative_count;
             $cumulative_count = 0;
              
            $output_diplay_array[$product_name] = $quantity;
            arsort($output_diplay_array);
    }
      
      
     //Output the results in a table
     foreach ($output_diplay_array as $product_name => $quantity) {
          echo '<tr><td>' . $quantity . '</td><td>' . $product_name.'</td></tr>';
     }
      
     echo '</table>';
      
     //Some house cleaning
    $wpdb->flush();
     
    }
 
?>
 
<br /><a href="javascript:window.print()"><button type="button" class="orderprintbutton">Print</button>
      
</div>
 
<?php }
add_action('admin_menu', 'register_pending_order_summary_page',99); 
 
//Function to apply print styling to the page
add_action('admin_head', 'dashboard_print_view');
 
function dashboard_print_view() {
  echo '<style>
   @media print { 
 
    #adminmenu{display: none!important;} 
    div#adminmenuback {display: none!important;}
    #wpcontent {margin-left: 5%!important;}
    #wpfooter {display: none!important;}
    .orderprintbutton {display: none!important;"}
    #screen-meta {display: none!important;}
}
  </style>';
}

Can anyone please advice on how I could also show the SKU (or maybe even a custom attribute, like brand) for each product? Currently only Quantity and Product name is shown.

Code author: https://shanegowland.com/advanced-woocommerce/2021/list-the-products-needed-to-fulfill-all-pending-orders-in-woocommerce/



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!" })
    }

    const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET_KEY, {
      expiresIn: "24h",
    })

    const { password: userPassword, ...others } = user._doc

    res
      .cookie("access_token", token, {
        httpOnly: true,
        maxAge: 86400000,
        sameSite: "none",
      })
      .status(200)
      .json({ ...others })
  } catch (error) {
    return res.status(500).json(error.message)
  }
}

//verifyUser middleware

const verfiyToken = (req, res, next) => {
  const token = req.cookies.access_token
  if (!token)
    return res.status(401).json({ Error: "You are not authenticated" })

  jwt.verify(token, process.env.JWT_SECRET_KEY, (err, user) => {
    if (err) return res.status(403).json({ Error: "Token is not valid" })
    req.user = user
    next()
  })
}

//cors middleware

//Middleware
const corsOptions = {
  origin: process.env.CLIENT_URL,
  methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
  credentials: true,
  // exposedHeaders: ["set-cookie"],
}

app.use(cors(corsOptions))

//vercel configuration file

{
  "version": 2,
  "builds": [
    {
      "src": "index.js",
      "use": "@vercel/node"
    }
  ],
  "routes": [
    {
      "src": "/(.*)",
      "dest": "/"
    }
  ]
}

I'm stuck on this since last 2-3 days. I've tried searching for similare problems and also checked the vercel docs, didn't find the exact answer. I don't know if it is related to vercel configuration file, cors or any other issues. I'm happy to provide more code snippet if required.

I've added this images please do check.

// localhost response images

localhost network tab cookies image

localhost response headers image

localhost application tab->cookies image

// production response images

production network tab cookies image

production response headers image

production application tab->cookies image



2023-12-09

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 missing keyboard codes causes problems with e.g.:

  • selecting text in Tmux's scrollback buffer (ctrl-space is used for 'begin-selection')
  • begin marking text in Emacs (set-mark-command)

My guess is that the problem relates to Windows Terminal, so I'm looking for suggestions on how to fix it with respect to not sending 'ctrl-space'?

Note: I've tried removing key bindings in Windows Terminal, which took care of some other "blocked" keys, but not ctrl-space.

Note: I don't want to change key bindings for both Tmux and Emacs to work around bugs in Windows Terminal. And on all of the remote workstations...

Should I use another terminal emulator on Windows? (I don't have admin access to my Windows laptop, so it likely needs to be in the Windows Store.)



2023-12-06

ggplot colorbar align to top when using facets

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)?

example

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 picture on the left chart, the size is actually fine.

library(ggplot2)

df <- expand.grid(
  x = c(1, 2, 3),
  y = c(1, 2, 3),
  g = c("one", "two", "three", "four")
)

set.seed(1)
df$v <- runif(nrow(df), min = 0, max = 1)

make_fullsize <- function() structure("", class = "fullsizebar")

ggplot_add.fullsizebar <- function(obj, g, name = "fullsizebar") {
  h <- ggplotGrob(g)$heights
  panel <- which(grid::unitType(h) == "null")
  panel_height <- unit(1, "npc") - sum(h[-c(panel, (panel-1), grep("lines", h))])

  g + 
    guides(fill = guide_colorbar(barheight = panel_height,
                                 title.position = "right")) +
    theme(legend.title = element_text(angle = -90, hjust = 0.5))
}

ggplot(df, aes(x = x, y = y, fill = v)) +
  facet_wrap(. ~ g, ncol = 2) +
  geom_tile(color = "black") +
  scale_y_discrete(expand = c(0,0)) +
  scale_x_discrete(expand = c(0,0)) +
  theme(panel.spacing.y = unit(1, "lines"),
        strip.text.x = element_text(size = 15, margin = margin(2,0,2,0, "cm")),
        strip.background.x = element_rect(
        colour = "black", linewidth = 1)) +
  make_fullsize()


2023-12-05

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(timer_name, context, timer):
    context['count'] += 1
    print('callback: ' + timer_name + ", count: " + str(context['count']))


async def timer2(timer_name, context, timer):
    context['count'] += 1
    print('callback: ' + timer_name + ", count: " + str(context['count']))

t1 = Timer(interval=1, first_immediately=True, timer_name="Timer Channel", context={'count': 0}, callback=timer1)
t2 = Timer(interval=3, first_immediately=False, timer_name="Timer Scroll", context={'count': 0}, callback=timer2)

try:
    loop = asyncio.get_event_loop()
    loop.run_forever()
except KeyboardInterrupt:
    t1.cancel()
    t2.cancel()
    print("clean up done")

and the second with an endless loop for checking events ...

while True:
for key, mask in selector.select():
    device = key.fileobj

    for event in device.read():
        ecode = event.code
        if event.type == evdev.ecodes.EV_KEY:
            match event.code:
                case 114:
                    print("Vol down")
                case 115:
                    print("Vol up")

Everything works as it should, but I don't know how to set it up so that everything runs independently without interfering with the other processes.

Best regards



2023-12-04

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?



2023-12-03

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);
        tcp::resolver::results_type endpoints =
        resolver.resolve(tcp::v4(), argv[1], argv[2]);

        tcp::socket s(io_context);
        boost::asio::connect(s, endpoints);

        using namespace std; // For strlen.
        std::cout << "Enter message: ";
        char request[max_length];
        std::cin.getline(request, max_length);
        size_t request_length = strlen(request);
        boost::asio::write(s, boost::asio::buffer(request, request_length));

        char reply[max_length];
        size_t reply_length = boost::asio::read(s,
        boost::asio::buffer(reply, request_length));
        std::cout << "Reply is: ";
        std::cout.write(reply, reply_length);
        std::cout << "\n";
   }
   catch (std::exception& e)
   {
        std::cerr << "Exception: " << e.what() << "\n";
   }

   return 0;
}

server.cpp

#include <cstdlib>
#include <iostream>
#include <boost/bind/bind.hpp>
#include <boost/smart_ptr.hpp>
#include <boost/asio.hpp>
#include <boost/thread/thread.hpp>

using boost::asio::ip::tcp;

const int max_length = 1024;

typedef boost::shared_ptr<tcp::socket> socket_ptr;

void session(socket_ptr sock){

    try{

        for (;;){
            char data[max_length];

            boost::system::error_code error;
            size_t length = sock->read_some(boost::asio::buffer(data), error);
            if (error == boost::asio::error::eof)
                 break; // Connection closed cleanly by peer.
            else if (error)
                throw boost::system::system_error(error); // Some other error.

            boost::asio::write(*sock, boost::asio::buffer(data, length));
        }
    }
    catch (std::exception& e){
         std::cerr << "Exception in thread: " << e.what() << "\n";
    }
}

void server(boost::asio::io_context& io_context, unsigned short port)
{
     tcp::acceptor a(io_context, tcp::endpoint(tcp::v4(), port));
     for (;;){
          socket_ptr sock(new tcp::socket(io_context));
          a.accept(*sock);
          boost::thread t(boost::bind(session, sock));
     }
}

int main(int argc, char* argv[])
{
    try{

        if (argc != 2){
            std::cerr << "Usage: blocking_tcp_echo_server <port>\n";
            return 1;
        }

        boost::asio::io_context io_context;

        using namespace std; // For atoi.
        server(io_context, atoi(argv[1]));
 }
 catch (std::exception& e)
 {
     std::cerr << "Exception: " << e.what() << "\n";
 }

return 0;
}


2023-12-02

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

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.

enter image description here

enter image description here

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>
        <v-icon class="px-2">mdi-apps</v-icon>
      </v-btn>
      <v-btn rounded depressed dark large @click="gotoSettings()">
        <h3>Settings</h3>
        <v-icon class="px-2">settings</v-icon>
      </v-btn>
      <v-btn rounded depressed dark large @click="gotoVerus()">
        <h3>Verus</h3>
        <v-icon class="px-2">mdi-apps</v-icon>
      </v-btn>
    </v-app-bar>
    <v-dialog v-model="dialog" fullscreen hide-overlay transition="dialog-bottom-transition">
      <v-card>
        <v-toolbar>
          <v-btn dark @click="dialog = false">
            <v-icon>mdi-close</v-icon>
          </v-btn>
          <v-toolbar-title>Markets</v-toolbar-title>
          <div class="flex-grow-1"></div>
          <v-toolbar-items>
            <v-btn dark text @click="dialog = false">back</v-btn>
          </v-toolbar-items>
        </v-toolbar>
        <v-list three-line subheader>
          <v-subheader>Go to markets</v-subheader>
          <v-list-item>
            <v-list-item-content>
              <v-list-item-title>Informational Section</v-list-item-title>
              <v-list-item-subtitle>Please wait for the available market links to load</v-list-item-subtitle>
              <AppMarkets v-on:gotoMarket="gotoMarket" :key="componentKey" />
            </v-list-item-content>
          </v-list-item>
        </v-list>
      </v-card>
    </v-dialog>
    <v-navigation-drawer
        v-model="drawer"
        location="left"
        temporary
      >
        <v-list
          :items="items"
        ></v-list>
      </v-navigation-drawer>
    <v-content>
      <router-view></router-view>
    </v-content>
  </v-app>
</template>


2023-12-01

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



2023-11-30

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 volumes, the overhead of maintaining the indexed view is not optimal.

Table A:

Column A UserId
x 1
y 2
z 3
w 4

Table B:

Column B UserId
a 1
b 3
c 5
d 6

Result (if no page size):

UserId
1
2
3
4
5
6

Result (if page size 3)

Page 1

UserId
1
2
3

Page 2

UserId
4
5
6


2023-11-29

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 "email" [has-type]

Here are details of my setup:

python version: 3.10.5
django version: 3.2.19
mypy version: 1.6.1
django-stubs[compatible-mypy] version: 4.2.6
django-stubs-ext version: 4.2.5
typing-extensions version: 4.8.0


2023-11-28

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-->
    <TextBox Text="Text"></TextBox>

    <!--Avalonia input does not work-->
    <interop:WpfAvaloniaHost  x:Name="AvaloniaHost" />
</Grid>

The fix in the autodesk thread:

public void Activate(ApplicationAddInSite addInSiteObject, bool firstTime)
{
    // Setup my WPF Window.
    var wpfWindow = new WpfWindow();
    wpfWindow.WindowStyle = System.Windows.WindowStyle.None;
    wpfWindow.ResizeMode = System.Windows.ResizeMode.NoResize;
    wpfWindow.Visibility = System.Windows.Visibility.Visible;

    // Get WPF Window's handle.
    var helper = new WindowInteropHelper(wpfWindow);
    helper.EnsureHandle();
    var handle = helper.Handle;

    // Create Dockable Window.
    var dockableWindow = InventorApplication.UserInterfaceManager.DockableWindows.Add(System.Guid.NewGuid().ToString(), "Test", "Test");
    dockableWindow.AddChild(handle);

    // Set key hook.
    HwndSource.FromHwnd(handle).AddHook(WndProc);
}

private const UInt32 DLGC_WANTARROWS = 0x0001;
private const UInt32 DLGC_WANTTAB = 0x0002;
private const UInt32 DLGC_WANTALLKEYS = 0x0004;
private const UInt32 DLGC_HASSETSEL = 0x0008;
private const UInt32 DLGC_WANTCHARS = 0x0080;
private const UInt32 WM_GETDLGCODE = 0x0087;

private static IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
    if (msg == WM_GETDLGCODE)
    {
        handled = true;
        return new IntPtr(DLGC_WANTCHARS | DLGC_WANTARROWS | DLGC_HASSETSEL | DLGC_WANTTAB | DLGC_WANTALLKEYS);
    }
    return IntPtr.Zero;
}

Fixes the problem for the input in WPF textboxes, but not yet for the embedded avalonia window.

This made me conclude that the problem lies elsewhere.

Somehow I need to pass the keypresses to the avalonia controls, but I have no clue how. Does anyone have any experience with this problem? Any advice is greatly appreciated!



2023-11-27

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)

WHAT DO I WANT TO GET? I need to find for the probability of Team A scoring exactly 2 goals to Team B, using Poisson distribution for example poisson.pmf(2, regression_result). As a lambda in the Poisson distribution, i will use the regression result​. I want to use regression for the purpose of relating team A's offense to team B's defense to find an ideal parameter to use in Poisson.

EXPLANATION: Team_A__goal_scored and Team_B__goal_conceded are the data of the last 5 rounds/matches played by the two teams against other opponents (Team A and Team B have never clashed). In the sixth round, the time will come for Team A and Team B to face each other and therefore I want to relate their data and calculate the probability that Team A scores 0 goals, 1 goal, 2 goals, 3 goals, etc. To be precise, i only need exactly 2 goals.

CLEAR SOMEONE'S DOUBT: Someone may say: "Why don't you directly use the Poisson distribution on the arithmetic mean of Team_A__goal_scored?" By doing this, I will have the probability that team A will score a certain number of goals, and it is a fair solution, but it is not what I want, because in this way the goals that team A scores will be calculated only ON THEMSELVES... and not related/influenced by the goals conceded by Team B in previous matches. I want to know how many goals Team A will score against Team B, considering the goals scored by Team A and also the Goals Conceded by Team B, because Team A's attack will be influenced by Team B's defense.

IMPORTANT EXAMPLE TO UNDERSTAND BETTER: I'll explain an example. If I have Team_A__goal_scored = [1, 3, 1, 2, 2] and Team_B__goal_conceded = [4, 5, 6, 5,4], it means Team B concedes a lot of goals.If instead Team_B__goal_conceded is [3, 0, 1, 1, 2], it means that team B concedes fewer goals and it will be more difficult for Team A to score goals for Team B. The goals that Team A will score, it will also be INFLUENCED by the goals that Team B concedes

I would like this final output:

The probability that Team A scores exactly 2 goals against Team B is: x %

UPDATE

I tried Poisson linear regression with one dependent variable and one independent variable. It's something similar to what I'm looking for, this is the one that comes closest to what I'm looking for, but obviously it's not good for the reasons stated above (lack of non-linearity and lack of two independent variables). The problem is that I can't find an algorithm that is useful for my case

import numpy as np
from sklearn.linear_model import PoissonRegressor

Team_A__goal_scored = np.array([1, 3, 1, 2, 2]).reshape(-1, 1)
Team_B__goal_conceded = np.array([3, 0, 1, 1, 2])

#Fit the model
clf = PoissonRegressor()
clf.fit(Team_A__goal_scored, Team_B__goal_conceded)

#Find the prediction (e.g. Team_A__goal_scored = 2)
lambda_pred = clf.predict(np.array([[2]]))[0]

#Poisson probability mass function to find the probability of scoring exactly 2 goals
from scipy.stats import poisson
probability_two_goals = poisson.pmf(2, lambda_pred)

print("Probability that team A scores exactly 2 goals against team B: ", probability_two_goals) 

Thank you



2023-11-26

Excel: Compounding matrix generation with array inputs

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, but the third is 2023 * 2024 * 2025 on each row (i.e. 1.25 * 1 * 1.2, for the first value of the third column). As such, the Output array has the same amout of columns as Input array B, with each column's values being a product of the current and the preceding columns of Input array B.

Note: The format of Input array A is irrelevant in the sense that the boolean values just need to indicate which elements of a particular row are multiplied together -> the array can be changed if needed, but Input array B should remain as provided.

Bruteforce solution: This task can be completed with MAKEARRAY() but it becomes exceedingly inefficient when Input array B has thousands of rows.

Solution found:

enter image description here



2023-11-25

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.



2023-11-24

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 email address may appear more than once)

The below syntax will highlight the right parts but will also select the aaa and bbb on the other rows that don't have the correct email address.

(aaa|bbb)?(rod\.p@yes\.com)?

so I realised that I need to define a start and end like ^ and $ but this is when I'm getting stuck and anything I do doesn't make it work.

^(aaa|bbb)?.*(rod\.p@yes\.com).*$

This matches the whole line of test2 (I guess this is because of the '.*') but I need to only match the individual parts so that I can replace them with the word anonymised. I've tried various things but haven't managed to work it working yet. Any guidance would be much appreciated. Thanks.

PS testing this using regexr.com/ with multiline and global flags enabled.



2023-11-23

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 = (const u8*)src;
    
    while (len-- > 0){
        *d++ = *s++;
    }
    return dst;
}

When I try to run these functions the system keeps rebooting. For example:

    clear_screen(COLOR(0,0,255));
    screen_swap();

A link to my github repo for more context



2023-11-22

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: I don't necessarily need a dict as the output; it can be an array of unique keys and an array of min values, and the order of keys doesn't matter.



2023-11-21

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 __new__ method, but I didn't find working solution yet



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

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()

enter image description here



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(() => {
    const myInterval = setInterval(() => {
      if (timer > 0) {
        setTimer(timer - 1);
        console.log(timer);
      }
    }, 1000);
    return () => clearInterval(myInterval);
  }, [startTime]);
  return timer;
}

export default CustomTimer;

Live Demo => please check the console



2023-11-20

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.