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