2023-07-31

Create web page using JavaScript with a different web address

I have created a custom element using JavaScript. This custom element has been added to my HTML page. When the user clicks on this element, the user should be directed to a new page. This page should be created dynamically using JavaScript.

I understand how to create this page by clearing the current page and adding the new elements. However, I want to change the web address and redirect the user to a brand new page.

I have created an Array of Objects. I want to write a single block of code and from this block, create a separate page for each object in the Array of Objects.

For example:

const myArray = [{object: "First Object",},{"Second Object"},{"Third Object"},{"Fourth Object"},{"Fifth Object"}];
const customElements = window.customElements;

class MyElement extends HTMLElement {
    constructor() {
        super();
        this.innerHTML = `<a href="page2.html">${myArray.object}</a>`;
    }}
customElements.define("header-element",MyElement);

In this example, I have written some JavaScript code. For each object in myArray, a link is created which shows the value of object currently being iterated through. However, the link is always page2.html, which I have created manually.

Instead of creating each link manually, I want the JavaScript program to create each page. I understand I can do this by clearing the current page using CSS and adding the new elements. However, this will mean the page will not change and only the content of the page.

I want the JavaScript program to create a page dynamically for each object in myArray with a different path.

I have found this question which is similar but regarding how to do this with a page using PHP: dynamically create HTML page from Javascript



ANTLR4 Python failed to install and cannot establish a connection

Hello I am trying to install the requirements of apache age python driver Whenever it comes to the installing of antlr4-python3-runtime it get struggling here: I install the packages through:

pip3 install -r requirements.txt

And it gets the following

Collecting antlr4-python3-runtime==4.11.1
  WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7f8ce27dfd90>: Failed to establish a new connection: [Errno 101] Network is unreachable')': /packages/e0/64/c548678120cccf784f555972ed37cedcf4f026abeec30ab0340c3af4ea07/antlr4-python3-runtime-4.11.1.tar.gz
  WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7f8ce27df2e0>: Failed to establish a new connection: [Errno 101] Network is unreachable')': /packages/e0/64/c548678120cccf784f555972ed37cedcf4f026abeec30ab0340c3af4ea07/antlr4-python3-runtime-4.11.1.tar.gz
  WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7f8ce27dee90>: Failed to establish a new connection: [Errno 101] Network is unreachable')': /packages/e0/64/c548678120cccf784f555972ed37cedcf4f026abeec30ab0340c3af4ea07/antlr4-python3-runtime-4.11.1.tar.gz
  WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7f8ce27def50>: Failed to establish a new connection: [Errno 101] Network is unreachable')': /packages/e0/64/c548678120cccf784f555972ed37cedcf4f026abeec30ab0340c3af4ea07/antlr4-python3-runtime-4.11.1.tar.gz
  WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7f8ce27df0d0>: Failed to establish a new connection: [Errno 101] Network is unreachable')': /packages/e0/64/c548678120cccf784f555972ed37cedcf4f026abeec30ab0340c3af4ea07/antlr4-python3-runtime-4.11.1.tar.gz
ERROR: Could not install packages due to an OSError: HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Max retries exceeded with url: /packages/e0/64/c548678120cccf784f555972ed37cedcf4f026abeec30ab0340c3af4ea07/antlr4-python3-runtime-4.11.1.tar.gz (Caused by NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7f8ce2818190>: Failed to establish a new connection: [Errno 101] Network is unreachable'))
  • OS: Ubunutu 22.04
  • Python version: 3.10.6

To reproduce:

# update and install
sudo apt-get update
sudo apt-get install python3-dev libpq-dev
# get apache age
git clone https://github.com/apache/age
# move to the drivers
cd age/drivers/python
# create virtual environment 
virtualenv venv
# active
source venv/bin/activate
# install
pip3 install -r requirements.txt

P.S When I have tried to download the package files from https://pypi.org/project/antlr4-python3-runtime/#files it has been downloaded

Has anyone got a similar issue?



2023-07-30

Tensorflow 2.0 model always predicting the same label

I am pretty new to ML and tensorflow, so I was working through the tutorials on tensorflow and copy/pasted one of their models with a custom training loop with a few modifications. Upon training it on the cifar10 dataset over 3 epochs, it achieved a 60 percent training acc and 54 percent validation acc. However, when I loaded it into another script to try and test it with images online, the logits had a nearly identical incorrect spread. 2 of the images tested were from online of a boat and airplane which looked similar to other cifar10 images while the other 2 were from the dataset itself, being a horse and boat. All produced nearly identical logits. What's really weird is that the logits always seem to peak at the fourth label (cat), no matter which model, architecture, or image I use. I've also tried switching optimizers to no avail. What am I missing (feedback regarding the problem itself or anything else about the code is greatly appreciated)?

Model:

import tensorflow as tf
import keras
from keras import layers
import numpy as np
import wandb
import datetime
from datetime import time
from PIL import Image

wandb.init(project='cifar10_seq', sync_tensorboard=True)

model = tf.keras.Sequential([
    layers.Conv2D(64, 3, activation='relu', input_shape=(32, 32, 3)),
    layers.BatchNormalization(),
    layers.Conv2D(64, 3, activation='relu'),
    layers.BatchNormalization(),
    layers.Conv2D(64, 3, activation='relu'),
    layers.BatchNormalization(),
    layers.Conv2D(64, 3, activation='relu'),
    layers.BatchNormalization(),
    layers.Flatten(),
    layers.Dense(128, activation='relu'),
    layers.Dense(10)
])

model.summary()

# Instantiate an optimizer.
optimizer = keras.optimizers.SGD(learning_rate=1e-3)
# Instantiate a loss function.
loss_fn = keras.losses.SparseCategoricalCrossentropy(from_logits=True)
# Prepare the metrics.
train_acc_metric = keras.metrics.SparseCategoricalAccuracy()
val_acc_metric = keras.metrics.SparseCategoricalAccuracy()

# dataset
batch_size = 64
(x_train, y_train), (x_test, y_test) = keras.datasets.cifar10.load_data()
# x_train = np.reshape(x_train, (-1, 784))
# x_test = np.reshape(x_test, (-1, 784))

# Reserve 10,000 samples for validation.
x_val = x_train[-10000:]
y_val = y_train[-10000:]
x_train = x_train[:-10000]
y_train = y_train[:-10000]

# Prepare the training dataset.
train_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))
train_dataset = train_dataset.shuffle(buffer_size=1024).batch(batch_size)

# Prepare the validation dataset.
val_dataset = tf.data.Dataset.from_tensor_slices((x_val, y_val))
val_dataset = val_dataset.batch(batch_size)


epochs = 3
training_on = True
if training_on:
    for epoch in range(epochs):
        print("Start of epoch %d" % (epoch+1,))

        # Iterate over dataset in batches
        for step, (x_batch_train, y_batch_train) in enumerate(train_dataset):
            with tf.GradientTape() as tape:
                # Run the forward pass of the layer.
                # The operations that the layer applies
                # to its inputs are going to be recorded
                # on the GradientTape.
                logits = model(x_batch_train, training=True)

                # Compute the loss value for this minibatch.
                loss_value = loss_fn(y_batch_train, logits)

            wandb.log({"loss": loss_value})
            wandb.log({"train_acc": train_acc_metric.result()})

            # Use the gradient tape to automatically retrieve
            # the gradients of the trainable variables with respect to the loss.
            grads = tape.gradient(loss_value, model.trainable_weights)

            # Run one step of gradient descent by updating
            # the value of the variables to minimize the loss.
            optimizer.apply_gradients(zip(grads, model.trainable_weights))

            # Update training metric.
            train_acc_metric.update_state(y_batch_train, logits)

            # Log every 200 batches.
            if step % 200 == 0:
                print(
                    "Training loss (for one batch) at step %d: %.4f"
                    % (step, float(loss_value))
                )
                print("Seen so far: %s samples" % ((step + 1) * batch_size))
        # Display metrics at the end of each epoch.
        train_acc = train_acc_metric.result()
        print("Training acc over epoch: %.4f" % (float(train_acc),))

        # Reset training metrics at the end of each epoch
        train_acc_metric.reset_states()

        # Run a validation loop at the end of each epoch.
        for x_batch_val, y_batch_val in val_dataset:
            val_logits = model(x_batch_val, training=False)
            # Update val metrics
            val_acc_metric.update_state(y_batch_val, val_logits)
            wandb.log({"val_acc": val_acc_metric.result()})
        val_acc = val_acc_metric.result()
        val_acc_metric.reset_states()
        print("Validation acc: %.4f" % (float(val_acc),))

log_dir = "logs/fit/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1)

model.save("cifar10_new.keras")

wandb.finish()

Test script:

from PIL import Image
import tensorflow as tf
import keras
from keras import layers
import numpy as np


def rescale_images(directory, size):
    im = Image.open(directory)
    im_resized = im.resize(size, Image.LANCZOS)
    im_resized.save(directory)


def prepare_image(directory):

    img = tf.io.read_file(directory)
    tensor = tf.io.decode_image(img, channels=3, dtype=tf.dtypes.float32)
    input_tensor = tf.expand_dims(tensor, axis=0)

    return input_tensor


model = keras.models.load_model("cifar10_new.keras")

rescale_images("random_images/car.png", (32, 32))
prediction = model.predict(prepare_image("random_images/car.png"))
prediction = tf.nn.softmax(prediction)
print(prediction)

The output of each image (softmax):

car: tf.Tensor( [[1.0266284e-03 7.7120079e-05 7.0860572e-02 8.8686663e-01 1.8580483e-02 1.7540520e-02 9.1350032e-04 8.7989774e-04 3.2326749e-03 2.1997652e-05]], shape=(1, 10), dtype=float32)

boat: tf.Tensor( [[1.0634739e-03 7.8063604e-05 7.0776239e-02 8.8636857e-01 1.8690629e-02 1.7929520e-02 8.5596397e-04 8.9970016e-04 3.3151936e-03 2.2658043e-05]], shape=(1, 10), dtype=float32)

horse: tf.Tensor( [[9.7531546e-04 6.9031390e-05 6.4809047e-02 8.9467043e-01 1.7074293e-02 1.7835772e-02 7.6558901e-04 8.5785246e-04 2.9216956e-03 2.0959489e-05]], shape=(1, 10), dtype=float32)

airplane: tf.Tensor( [[1.0483327e-03 7.7148259e-05 7.0324250e-02 8.8746655e-01 1.8424451e-02 1.7627772e-02 8.5348362e-04 8.9448754e-04 3.2609249e-03 2.2576383e-05]], shape=(1, 10), dtype=float32)

The images are drastically different so I do not believe it would be because the model actually thinks each of these images are a cat. Any help is appreciated.



2023-07-29

Display a stream from a server using QT

So i have a project that consist of two systems an ESP32 with camera and a QT App. I built the ESP32 to stream a video on a server hosted on the ESP32 board. I want now to get this video stream and show it on a QT app but I could not find a way to show the video. I used a GraphicsView to display the video but it think this approach is false. So any suggestions on how to do that?

Here is my code that I wrote to get the stream. I receive some data from the server but I could not display the streaming.

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent):QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // Create the QGraphicsScene and set it to the Graphics View
    scene = new QGraphicsScene(this);
    ui->VideoStreamer->setScene(scene);

    // Initialize the network manager
    networkManager = new QNetworkAccessManager(this);

    // Start the video streaming request
    QUrl videoUrl("http://192.168.8.228:81/stream");
    networkReply = networkManager->get(QNetworkRequest(videoUrl));

    // Connect the readyRead signal to the onVideoStreamReadyRead slot
    connect(networkReply, &QNetworkReply::readyRead, this, &MainWindow::onVideoStreamReadyRead);
}

MainWindow::~MainWindow()
{
  delete ui;
}

void MainWindow::onVideoStreamReadyRead()
{
   // Read the incoming video data and display it in the QGraphicsView
   if (networkReply->error() == QNetworkReply::NoError)
   {
      QByteArray data = networkReply->readAll();
      qDebug() << "Received data size:" << data.size(); //Add this line for debugging

      QPixmap pixmap;
      pixmap.loadFromData(data);
      scene->clear();
      scene->addPixmap(pixmap);
   }
   else
   {
      qDebug() << "Network error:" << networkReply->errorString(); // Add this line for debugging
   }
}

And this is the ESP32 code that creates the stream on the local server. The server can be opened in the browser if the computer is connected to the same wifi as the esp32 board.

//Configurations for the stream
#define PART_BOUNDARY "123456789000000000000987654321"
static const char* _STREAM_CONTENT_TYPE = "multipart/x-mixed-replace;boundary=" PART_BOUNDARY;
static const char* _STREAM_BOUNDARY = "\r\n--" PART_BOUNDARY "\r\n";
static const char* _STREAM_PART = "Content-Type: image/jpeg\r\nContent-Length: %u\r\n\r\n";

httpd_handle_t cameraHttpd = NULL;
httpd_handle_t streamHttpd = NULL; // Two servers for the stream and main one

esp_err_t HttpServerHandler::streamHandler(httpd_req_t *req){
  camera_fb_t * fb = NULL;
  esp_err_t res = ESP_OK;
  size_t _jpg_buf_len = 0;
  uint8_t * _jpg_buf = NULL;
  char * part_buf[64];

  res = httpd_resp_set_type(req, _STREAM_CONTENT_TYPE);
  if(res != ESP_OK){
    return res;
  }

  while(true){
    fb = esp_camera_fb_get();
    if (!fb) {
      Serial.println("Camera capture failed");
      res = ESP_FAIL;
    } else {
      if(fb->width > 400){
        if(fb->format != PIXFORMAT_JPEG){
          bool jpeg_converted = frame2jpg(fb, 80, &_jpg_buf, &_jpg_buf_len);
          esp_camera_fb_return(fb);
          fb = NULL;
          if(!jpeg_converted){
            Serial.println("JPEG compression failed");
            res = ESP_FAIL;
          }
        } else {
          _jpg_buf_len = fb->len;
          _jpg_buf = fb->buf;
        }
      }
    }
    if(res == ESP_OK){
      size_t hlen = snprintf((char *)part_buf, 64, _STREAM_PART, _jpg_buf_len);
      res = httpd_resp_send_chunk(req, (const char *)part_buf, hlen);
    }
    if(res == ESP_OK){
      res = httpd_resp_send_chunk(req, (const char *)_jpg_buf, _jpg_buf_len);
    }
    if(res == ESP_OK){
      res = httpd_resp_send_chunk(req, _STREAM_BOUNDARY, strlen(_STREAM_BOUNDARY));
    }
    if(fb){
      esp_camera_fb_return(fb);
      fb = NULL;
      _jpg_buf = NULL;
    } else if(_jpg_buf){
      free(_jpg_buf);
      _jpg_buf = NULL;
    }
    if(res != ESP_OK){
      break;
    }
  }
  return res;
}

void HttpServerHandler::startServer()
{
    httpd_config_t config = HTTPD_DEFAULT_CONFIG();
  config.server_port = 80;
  httpd_uri_t stream_uri = {
    .uri       = "/stream",
    .method    = HTTP_GET,
    .handler   = streamHandler,
    .user_ctx  = NULL
  };
  if (httpd_start(&cameraHttpd, &config) == ESP_OK) {
    httpd_register_uri_handler(cameraHttpd, &index_uri);
    httpd_register_uri_handler(cameraHttpd, &cmd_uri);
  }
  config.server_port += 1;
  config.ctrl_port += 1;
  if (httpd_start(&streamHttpd, &config) == ESP_OK) {
    httpd_register_uri_handler(streamHttpd, &stream_uri);
  }
}

Streaming server opened in browser.



How to read response data from a custom type of json in android studio

I have a group of classes in the API, and I want the results of the request to be semi-uniform, for example, I created a class that contains 3 fields as follows below :

 public class resultDataClass
    {
        public Boolean state { get;set; }
        public string message { get; set; }
        public object data { get; set; } //this field 

    }

The third field returns different data from all classes may be type op users class or department class or another class -- below show data json in my response type

my be :

{
"state": true,
"message": " data description",
"data": [
          {
             "id": 1,
             "UserName": "",
             "password": "",
             "email": "",
             "phone": ""
          },
          {
             "id": 2,
             "UserName": "",
             "password": "",
             "email": "",
             "phone": ""
          }
        ]
}

and my be from another class and different fields:

{
"state": true,
"message": " data description",
"data": [
          {
             "id": 1,
             "title": "",
             "content": "",
             "description": "",
             "image": ""
          },
          {
             "id": 1,
             "title": "",
             "content": "",
             "description": "",
             "image": ""
          }
        ]
}

now , How can I build another Unified Class in Android Studio Java to fetch data from this json data

how to set response class this :

public class ResponseClass {
    public boolean state;
    public String message;
    // here how to define object like api class in up 
    public List<??>

    public boolean isState() {
        return state;
    }

    public String getMessage() {
        return message;
    }
}

I am written this code to fetch data for one class .

String myMessage="";
Call<ResponseData> call=api.getPosts(userId);
    call.enqueue(new Callback<ResponseData>() {
        @Override
        public void onResponse(@NonNull Call<ResponseData> call, @NonNull Response<ResponseData> response) {
                    if(response.isSuccessful()) {

                        if(response.body.isstate)
                            {
                             
                        try {
                            for(int i = 0; i< response.body().getData().size(); i++)
                            {
                                //here fetch data from desired class

                                //It could be a user class or any other class
                                mylist.add(row);
                            }
                            
                            adapter=new MyAdapter(getContext(),mylist);
                            recyclerView.setAdapter(adapter);
                            pd.dismiss();
                        }catch (Exception exception)
                        {
                           
                        }
                    } else myMessage=response.body.getmessage();}
                    else {
                        
                    }
        }

        @Override
        public void onFailure(@NonNull Call<ResponseContentData> call, @NonNull Throwable t) {
            Toast.makeText(getContext(), "message :"+ t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();

        }
    });


2023-07-28

Need help! Facing issues with Open AI where I have overlapping of data

I have built a chatbot which can do a search on my data by creating an embedding solution. But if I have overlapping data then answers are not accurate. Is there any way that I can send a recommend/follow-up question back to the user through a chatbot to be more specific with the document? For example- The user query is “share scope of work”. I have 10 documents where I have scope of work then what should be in a prompt to send a recommendation to the user to be more specific with the vendor’s name to get the right answer.



2023-07-27

How to get last non null values and aggregated non null values by timestamp from event sourcing JSONB column in PostgreSQL?

I'm working with event sourced data where all of the important fields are combined to a JSONB column and many of the keys are missing from most of the database rows.

I would want to get:

  1. Aggregated combined values of included arrays in the JSONB field (see ingredients in the example)
  2. Latest non-null value according to timestamp

I tried this on my own and I was able to produce a example which generates exactly what I would want to achieve here but it looks rather ugly and I'm wondering how to make following query better.

Schema (PostgreSQL v15)

CREATE TABLE events (
    id SERIAL PRIMARY KEY,
    identifier VARCHAR(255),
    timestamp TIMESTAMP WITH TIME ZONE,
    event_data JSONB
);
INSERT INTO events (identifier, timestamp, event_data)
VALUES
    ('12345', '2019-01-01T00:00:00.000Z', '{"target": "99999999"}'),
    ('12345', '2019-01-01T12:00:00.000Z', '{"ingredients": ["Banana", "Strawberry"]}'),
    ('12345', '2019-01-03T00:00:00.000Z', '{"target": "12345678", "user": "peterpan"}'),
    ('12345', '2019-01-04T00:00:00.000Z', '{"ingredients": ["Melon"], "user": "robinhood"}'),
    ('67890', '2019-01-03T00:00:00.000Z', '{"target": "0000", "user": "mickeymouse"}'),
    ('67890', '2019-01-04T00:00:00.000Z', '{"ingredients": ["Potato"]}');

Query #1

WITH events_flattened AS (
    SELECT
        identifier,
        timestamp,
        event_data->>'target' AS target,
        event_data->>'user' AS user,
        elem.part
    FROM events
    LEFT JOIN LATERAL jsonb_array_elements(event_data->'ingredients') elem(part) ON true
    ORDER BY timestamp DESC
)

SELECT
    identifier,
    (ARRAY_REMOVE(ARRAY_AGG(e.target),NULL))[1] as target,
    (ARRAY_REMOVE(ARRAY_AGG(e.user),NULL))[1] as user,
    ARRAY_REMOVE(ARRAY_AGG(part),NULL) as ingredients,
    MAX(timestamp) as latest_update
FROM events_flattened e
GROUP BY identifier;

For the answer to be helpful it should produce exactly same result as seen on this table:

identifier target user ingredients latest_update
12345 12345678 robinhood Melon,Strawberry,Banana 2019-01-04T00:00:00.000Z
67890 0000 mickeymouse Potato 2019-01-04T00:00:00.000Z

View on DB Fiddle

I'm trying to determine which kind of query and indexes would be beneficial to get exactly this kind of data out from this table?



2023-07-26

How to check if one wildcard expression (AKA glob) contains another wildcard expression?

I have two wildcard expressions g1 and g2, and I would like to know whether g1 contains g2. For example:

g1 = "*.txt"
g2 = "hello*.txt"

In this case g1 contains g2.



2023-07-25

What are the modifications required on dts file to migrate from 5inch MIPI DSI display to 10.1 inch MIPI DSI display on imx8 board?

I am trying to bring up 10.1 inch mipi dsi display with compulab ucm-imx8mp board. The development board will work with default 5 inch mipi display. Now I wanted to change the display size to 10.1 inch. The 10.1 inch display has same pin configurations as 5 inch display. Please guide me on, what are the major changes I need to perform on my ucm-imx8m-plus.dts file to make this 10.1 inch display work?

The below changes I have made so far, please review it and give your inputs.

[10.1' display timing parameters][1]

modified ucm-imx8m-plus.dts for 10.1' startek mipi display

&mipi_dsi {
    status = "okay";
    panel: panel@0 { 
            compatible = "startek,kd101wxfid025";
            reg = <0>;
            reset-gpio = <&pca9555 4 GPIO_ACTIVE_LOW>;
            dsi-lanes = <4>;
            status = "okay";
            clock-frequency = <67000000>;
            hactive = <1280>;
            vactive = <800>;
            hback-porch = <38>;
            vback-porch = <10>;
            hfront-porch = <16>;
            vfront-porch = <8>;
            hsync_width = <4>;
            vsync_width = <4>;
    };
};

The startek display controller IC is ILI9881C. And the mipi host controller driver is imx_sec_dsim_drv. I have added 10.1' startek display serial number also in ili9881c driver code as below,

static const struct of_device_id ili9881c_of_match[] = {
{ .compatible = "startek,kd050hdfia020" },
{ .compatible = "startek,kd101wxfid025" },
{ }
};

Is this right way of bring up this 10.1' startek display? Any input on this would be really helpful. [1]: https://i.stack.imgur.com/YHHX6.png



PyPi: twine missing METADATA, but it exists in .whl file

I was trying to upload an update to my package on PyPi but I noticed they have changed it so you have to use a pyproject.toml file. So I did follow steps on PyPi

  1. Created pyproject.toml
  2. Ran py -m build with no errors or warnings
  3. Ran twine check dist/* and both files passed
  4. Ran twine upload dist/* to upload, but got this error after the first file was uploaded:
Wheel '***_Ashenguard-3.2.0-py3-none-any.whl' does not contain the required METADATA file: ***_ashenguard-3.2.0.dist-info/METADATA

(*** = My package)

Then I opened the .whl file (Changed its suffix to zip and opened it) and checked the files inside and I saw the METADATA file in the path specified...

I tried searching but the only similar question I found was solved by adding the pyproject.toml



matMenuTrigger openMenu not showing the menu when called with *ngFor

Good evening, I have this component:

HTML

<button mat-menu-item
  #leagueMenuTrigger="matMenuTrigger"
  [matMenuTriggerFor]="leagueMenu"
  (mousedown)="onMouseDown(leagueMenuTrigger)">
   
</button>

<mat-menu #leagueMenu="matMenu">
<button mat-menu-item>
Club Home 
</button>
<button mat-menu-item>
Events    
</button>
<button mat-menu-item>
Player Roster    
</button>
<button mat-menu-item>
Results and Standings
</button>
<button mat-menu-item>
Ledger
</button>
<button mat-menu-item>
Club Settings
</button>
</mat-menu>

TS

import { OnInit, Component, Input, AfterViewInit } from '@angular/core';
import { MatMenuTrigger } from '@angular/material/menu';
import { Group } from 'src/app/objects/group';

@Component({
  selector: 'wagl-league-menu',
  templateUrl: './league-menu.component.html',
  styleUrls: ['./league-menu.component.scss']
})
export class LeagueMenuComponent implements OnInit  {
  @Input() group: Group; 

  constructor() {}

  ngOnInit() {}

  onMouseDown(leagueMenuTrigger: MatMenuTrigger) {
    // This method can be used for any specific mouse down logic if needed.
      console.log(leagueMenuTrigger.menuOpen);
      leagueMenuTrigger.openMenu();
      console.log(leagueMenuTrigger.menuOpen);
  }
}

if I simply call it like this:

<wagl-league-menu [group]="league"></wagl-league-menu>

It will work, but when I call it like this:

    <wagl-league-menu *ngFor="let league of leagues" [group]="league"></wagl-league-menu>

It does not work, I can't seem to put my finger on what I'm doing wrong. I'm using angular 7.



Matrix visual result values not pulling for the data

I have three tables. Table 1 CheckNo No of Covers

Table 2 Data Tabe with Check Id, Location Id, date Revenue Table 3 Liaction ID and Location name

Table 1 is linked to Table 2 One to Many relationships on Checkl No Table 3 is liked to Table 2 one to many relationships on Location ID

Trying to get a matrix visual with Location Name, Month, No of Covers and Sum of Revenue for each location. Tried the matrix with Location in Row , Month in Column and Sum of Revenue and Covers in Values The revenue is coming clean but on covers i am getting the total covers from Table 1 for each location for each month. I am a beginner, Any heal will be greatly appreciated. Hem



2023-07-24

Trouble to MongoDB Single Node Replica Set in Docker Container

I am trying to run MongoDB in a Docker container and apply a Single Node Replica Set in an Oracle Cloud Ubuntu environment without using docker-compose.

When I execute rs.initiate() in mongosh, members are automatically created with the container's ID (/etc/hosts). However, when trying to connect externally using Compass, I get the error message "getaddrinfo ENOTFOUND $CONTAINER_ID" and cannot establish a connection.

I have tried changing the host information in rs.initiate() arguments to 'localhost', '127.0.0.1', and external IP, but none of them work. I have also tried changing Docker's ports, but the issue persists.

Currently, only port 27017 is open in the cloud, and it functions properly.

I am seeking assistance in identifying the problem.

Just in case, I'm adding my options (nothing special)

In Dockerfile

mongod --bind_ip_all --replSet rs --port 27017

Container Execution

docker run -d \
  -p 27017:27017\
  --name $NAME \
  -v $VOLUME_DIR:/data/db \
  $IMAGE_NAME

Attempted Replica Set with IP or ID expected to connect, but failed. I hope to be connected to the Replica Set(single node, primaey only).



2023-07-23

How to change the background color of TextEditor like TextField

struct TextView: View {
    @State private var textInput2: String = ""
    var body: some View {
        ScrollView{
            VStack(spacing: 24){
                TextField("", text: $textInput2)
                    .font(.body)
                    .foregroundColor(.gray)
                    .padding()
                    .frame(height: 142)
                    .background(Color("3"))
                    .cornerRadius(20)
                    .overlay(
                        RoundedRectangle(cornerRadius: 20)
                            .stroke(Color.gray.opacity(0.5), lineWidth: 2)
                    )
                
                TextEditor(text: $textInput2)
                    .textFieldStyle(PlainTextFieldStyle())
                    .font(.body)
                    .foregroundColor(.gray)
                    .padding()
                    .background(Color("3"))
                    .frame(height: 142)
                    .cornerRadius(20)
                    .overlay(
                        RoundedRectangle(cornerRadius: 20)
                            .stroke(Color.gray.opacity(0.5), lineWidth: 2)
                    )
            }
            .padding(.horizontal)
        }
    }
}

I want to change the background color of a TextEditor, I tried:

  • .foregroundColor changed the text color instead of the background color;
  • .background only changed the surroundings' background color and not the whole TextEditor as seen in the image below:

enter image description here



How to update Android UI on Firestore result?

I am trying to write a database query in Cloud Firestore in Kotlin.

The request itself is working but I am having some problems with the async workflow.

My goal is to make a database request that fetches a lot of data and puts this into an object. Once this is complete for all objects, the normal workflow of the app should continue. (because I need to display some of this data in my UI).

My database structure: I have a collection of users -> Each user has a collection of their own recipes. -> In each recipe there is a collection of Steps to complete and a collection of ingredients

My goal is to get the data and show it on my app screen (code below), but with my current code, the app starts the request and continues to show the app screen (which means there is no data loaded up to this point).

Is there a way to make my database request more efficient (as I have 3 requests per recipe) and also to make it work async? So that when the data gets loaded the UI will recognize a change and show this to the UI later on or the UI waits till all the requests are complete?

Sorry if this is a basic question about coroutines, but I am pretty new to this topic and could not find any info in the Firebase documentation.

My Code:

in My Main Activity:

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        loadRecipes()//should load the information from the Database
        initUiElements()//should show the Information in a Recycler View
    }

-> load Recipies calls the following Class with the loadloadRecipes() function

Class: FirebaseRecipes:

fun loadRecipes(){

        //First DB Request to get the Recipe Names and Durations
        Log.d("FirebaseRecipes", "loadRecipes()")
        db.collection("users").document(userID.toString()).collection("Recipes").get()
            .addOnSuccessListener { result ->
                for (document in result) {
                    val duration = document.data["duration"].toString()
                    val name = document.data["name"].toString()
                    var recipe = Recipe(name, duration)
                    RecipesList.add(recipe)

                    //Second DB Request to get the Ingredients
                    db.collection("users").document(userID.toString()).collection("Recipes").document(document.id).collection("ingredients").get()
                        .addOnSuccessListener { result ->
                            for (document in result) {
                                val amount = document.data["amount"].toString()
                                val name = document.data["name"].toString()
                                val barcode = document.data["unit"].toString()
                                val ingredient = Ingredient(name, amount, barcode)
                                recipe.ingredients.add(ingredient)
                            }
                        }

                    //Third DB Request to get the Steps
                 db.collection("users").document(userID.toString()).collection("Recipes").document(document.id).collection("steps").get()
                        .addOnSuccessListener { result ->
                            for (document in result) {
                                val step = document.data["text"].toString()
                                recipe.steps.add(step)
                            }
                        }
                }
            }
    }

Solution:

with the answers of @AlexMamo, @UsmanMahmood and @NguyễnMinhKhoa I was able to get the following solution to my problem:

I Created a ViewModel that contains my List:

private val _recipeList =
        MutableLiveData<CustomResponse<List<Recipe>>>(CustomResponse.Loading())
    val recipeList: LiveData<CustomResponse<List<Recipe>>>
        get() = _recipeList

    fun shareRecipe(recipes: List<Recipe>) {
        _recipeList.value = CustomResponse.Success(recipes)
    }

in the class that should retrieve the data from Firebase I created the following function, to retrieve the data and store it to the View Model:

fun loadRecipes(activity: Activity) {
        val model =
            ViewModelProvider(activity as ViewModelStoreOwner)[ViewModel::class.java]

        db.collection("users").document(userID.toString()).collection("Recipes").get()
            .addOnSuccessListener { result ->
                val recipesList = ArrayList<Recipe>()
                for (document in result) {
                    val duration = document.data["duration"].toString()
                    val name = document.data["name"].toString()
                    var recipe = Recipe(name, duration)
                    recipesList.add(recipe)

                    recipe.steps = document.data["steps"] as ArrayList<String>

                    val ingredients =
                        document.data["ingredients"] as ArrayList<HashMap<String, Any>>
                    for (ingredient in ingredients) {
                        val name = ingredient["name"].toString()
                        val amount = (ingredient["amount"] as Long).toInt()
                        val ingredient = Ingredient(name, amount)
                        recipe.ingredients.add(ingredient)
                    }
                    model.shareRecipe(recipesList)
                }
            }
    }

A Custom Response:

sealed class CustomResponse<T>(val  data: T? = null, val errorMessage:String? =null) {                                    ;
    class Loading<T> : CustomResponse<T>()
    class Success<T>(data: T? = null) : CustomResponse<T>(data = data)
    class Error<T>(errorMessage: String) : CustomResponse<T>(errorMessage = errorMessage)
}

and in the fragments I can call it like this:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val model = ViewModelProvider(requireActivity())[RecipesViewModel::class.java]
model.recipeList.observe(viewLifecycleOwner) { response ->
            when (response as CustomResponse<List<Recipe>>) {
                is CustomResponse.Loading -> {
                    rvRecipes.visibility = View.INVISIBLE
                    progressBar.visibility = View.VISIBLE
                }
                is CustomResponse.Success -> {
                    rvRecipes.visibility = View.VISIBLE
                    progressBar.visibility = View.GONE

                    Log.d("FirebaseRecipes", "Recipes loaded within Fragment")

                    adapter.content = response.data as ArrayList<Recipe>
                    adapter.notifyDataSetChanged()
                }
                is CustomResponse.Error -> {
                    response.errorMessage?.let {
                        rvRecipes.visibility = View.INVISIBLE
                        //TODO: Display error message
                    }
                }
            }
        }


2023-07-22

Needed sample code for DAVE™ IDE to drive L9825 Driver IC with daisy chain connectivity

enter image description here

Needed sample code for DAVE™ IDE to drive L9825 Driver IC with daisy chain connectivity, Outputs are not coming, unable to set register's bits of driver IC module. Anyone can help with sample code for DAVE IDE & XMC-4100 series MCU with L9825 Driver IC module.

Thanks in advance



2023-07-21

RegEx - Search for Word and Output Last Decimal Number on Line

I'm trying to use RegEx to parse the Total Hours working in a pay period from a PDF timesheet.

For example:

Total Overtime Hours: Total Hours: 2.2 1.0 1.0 3.5 5.0 12.7 Signature:

(?<=Total Hours:*(?:.*?( )+){6}).*

The Total Hours will always be the last number on the line that starts with "Total Hours:"

The above RegEx code works for most employees who work 5 days a week but breaks if they work more or less than 5 days as in the example below:

Total Overtime Hours: Total Hours: 2.2 1.0 1.0 3.5 5.0 6.3 19.0 Signature:

regexr.com/7hci1

Any thoughts on the adjustments I can make to always grab the last decimal number of the row that starts with "Total Hours:"?

Thanks!



Trouble with TTK Scrollbar

I'm working on building a GUI using ttk. One component involves dynamically adjusting the number of rows of Entry objects with a Scale / Spinbox. During the range of acceptable values, the number of fields exceeds the size of the window, so a scroll bar and canvas are used to accommodate. The issue arises with when the frame gets updated from one that had a scrollbar to another that has a scrollbar.

In this version, no matter if there is a scrollbar/canvas or not, the entries are placed in an innerFrame within the entriesFrame. When the number of entries is updated, there was a scrollbar, and there still needs a scrollbar the scrolable region only ever shows 8 Entries.

The current debug readouts are the objects in the innerFrame if there's a scrollbar after attempting to delete them all, the number of entries from the scale / spinbox, and the objects in the innerFrame if there's a scrollbar.

from tkinter import Canvas, Tk, LEFT, BOTH, RIGHT, VERTICAL, X, Y, ALL, IntVar, TOP
from tkinter.ttk import Frame, Scale, Entry, Scrollbar, Spinbox, Style

def validateSpin(P):
    if (P.isdigit() or P =="") and int(P) > 0 and int(P) < 11:
        return True
    else:
        return False
def updateScale(event):
    def inner():
        spnVal = spin.get()
        if spnVal != "":
            scale.set(float(spnVal))
            entries.set(float(spnVal))
            refreshEntries()
    root.after(1, inner)
def updateSpin(event):
    def inner():
        reportVal = round(float(scale.get()))
        spin.set(reportVal)
        entries.set(reportVal)
        refreshEntries()
    root.after(1, inner)
def scrollbarNeeded():
    if entries.get() > 7:
        return True
    else:
        return False
def makeScrollbarAndCanvas():
    scrollingCanvas = Canvas(entriesFrame, width = 200, highlightthickness=0)
    scrollingCanvas.pack(side=LEFT,fill=X,expand=1)
    
    scrollbar = Scrollbar(entriesFrame, orient=VERTICAL,command=scrollingCanvas.yview)
    scrollbar.pack(side=RIGHT,fill=Y)
    
    scrollingCanvas.configure(yscrollcommand=scrollbar.set)
    scrollingCanvas.bind("<Configure>",lambda e: scrollingCanvas.config(scrollregion=scrollingCanvas.bbox(ALL)))
    
    innerFrame = Frame(scrollingCanvas)
    scrollingCanvas.create_window((0,0),window= innerFrame, anchor="nw")
    
    return innerFrame
def scrollbarFound():
    for child in entriesFrame.pack_slaves():
        if isinstance(child, Canvas):
            return True
    return False
def populateEntries(frm):
    print(entries.get())
    for i in range(entries.get()):
        E = Entry(frm, width=15)
        E.grid(column=0, row = i, pady=2)

def refreshEntries():
    def searchAndDestory(obj):
        if hasattr(obj, 'winfo_children') and callable(getattr(obj, 'winfo_children')):
            for child in obj.winfo_children():
                searchAndDestory(child)
            obj.destroy()
        elif isinstance(obj, list):
            for child in obj:
                searchAndDestory(child)
        else:
            obj.destroy()
    if scrollbarNeeded():
        if scrollbarFound():
            for child in entriesFrame.winfo_children():
                if isinstance(child, Canvas):
                    frm = child.winfo_children()[0]
                    searchAndDestory(frm.grid_slaves())
                    #searchAndDestory(child.winfo_children()[0])
                    #frm = Frame(child)
                    #child.create_window((0,0),window= frm, anchor="nw")
            for child in entriesFrame.winfo_children():
                if isinstance(child, Scrollbar):
                    child.update()
        else:
            searchAndDestory(entriesFrame.winfo_children()[0])
            frm = makeScrollbarAndCanvas()
        print(frm.grid_slaves())
        populateEntries(frm)
        print(frm.grid_slaves())
    else:
        searchAndDestory(entriesFrame.winfo_children())
        innerFrame = Frame(entriesFrame)
        populateEntries(innerFrame)
        innerFrame.pack(fill=BOTH)

root = Tk()
root.resizable(False,False)
root.geometry("275x250")

outerFrame = Frame(root, padding = 10)

entries = IntVar()
entries.set(5)

topFrame = Frame(outerFrame, padding = 10)

spin = Spinbox(topFrame, from_=1, to=10, validate="key", validatecommand=(topFrame.register(validateSpin), "%P"))
spin.grid(column=0, row=0)
spin.set(entries.get())
spin.bind("<KeyRelease>", updateScale)
spin.bind("<ButtonRelease>", updateScale)
spin.bind("<MouseWheel>", updateScale)

scale = Scale(topFrame, from_=1, to=10)
scale.grid(column=1, row=0)
scale.set(entries.get())
scale.bind("<Motion>", updateSpin)
scale.bind("<ButtonRelease>", updateSpin)

topFrame.pack(side=TOP, fill=BOTH)

entriesFrame = Frame(outerFrame)
sty = Style()
refreshEntries()
entriesFrame.pack(fill=BOTH)
outerFrame.pack(fill=BOTH)

root.mainloop()

The Scale and Spinbox work together fine and I've been able to make them control the number of fields. I've verified that with a constant number of entries, the scroll bar and Entry objects are completely operational. Additionally, the correct number of entries are being created and displayed, (you can verify by changing the root.geometry() term to "275x350"). I'm not quite grasping what needs to change to get the scrollbar to expand its range of motion.



2023-07-20

how to use send_message() in python-telegram-bot

i want to send a message to user, without waiting for user triggered my bot. using send_message(), i've been read the documentation but i'm not really understand. Here's my code

from dotenv import load_dotenv
from telegram.ext import *
from telegram import InputFile, Bot
import os
import re

command = ['start']

load_dotenv()

tokenize = os.getenv("TELEGRAM_BOT_TOKEN")

async def start_commmand(update, context):
    umsg = update.message
    await umsg.reply_text("Welcome, i'll help u with ur schedule")


if __name__ == "__main__":
    application = Application.builder().token(tokenize).build()

    application.add_handler(CommandHandler(command[0], start_commmand))

    # Run bot
    application.run_polling(1.0)

i tried to send a message to bot user using send_mesage(), i hope it's send a message without waiting any message from user. because i'm not really understand after read the documentation, i don't know how to do it



How to call MS Graph via sp_invoke_external_rest_endpoint with a large access token?

I'm using sp_invoke_external_rest_endpoint in T-SQL to call Microsoft Graph endpoints. This is one of the use cases that Microsoft advertises. The headers parameter of sp_invoke_external_rest_endpoint is an nvarchar(4000) so you are limited to 4000 characters. How do you call MS Graph when you have an access token that is larger than that?

I've implemented sp_invoke_external_rest_endpoint in two different environments and in one of them the access token was short enough (around 3400 characters) to fit but in the other it's over 4000 characters.



2023-07-19

Guice and MVP pattern: decouple the view from the presenter

I'm writing an application in Swing and I'd like to make use of Model–view–presenter pattern. I found a sample application using this pattern and alter it to use Guice. I was able to make it work with albeit with one problematic piece of code. Let me first show my code and later on the piece I find problematic.

Application starting point:

@RequiredArgsConstructor(onConstructor = @__(@Inject))
public class Main {

    private final View view;

    public static void main(final String[] args) {

        final Main main = Guice.createInjector().getInstance(Main.class);

        SwingUtilities.invokeLater(main.view::createUI);
    }
}

Model:

public class Model {

    public String getPassword() {
        return "password";
    }
}

Presenter:

@RequiredArgsConstructor(onConstructor = @__(@Inject))
public class Presenter {

    private final View view;
    private final Model model;

    public void login(final String password) {

        final String result = model.getPassword().equals(password)
                ? "Correct password" : "Incorrect password";

        view.updateStatusLabel(result);
    }
}

Until this point everything seems to be fine. In the View constructor I manually create instance of Presenter using this (due to some coupling involved in MVP pattern) instead of letting Guice does it job.

EDIT

How do I overcome this problem? As per comments, I'd like to rewrite the code so that the view could be injected into the presenter via dependency injection.

Guice has this somewhat covered it its documentation, however, I find it really difficult to understand hence this question of mine.

public class View {

    private final Presenter presenter;

    private JLabel statusLabel;
    private JTextField inputField;

    public View() {
        // manually adding this, should be DI
        this.presenter = new Presenter(this, new Model());
    }


    public void createUI() {
        // removed
    }

    //called by the presenter to update the status label
    public void updateStatusLabel(final String text) {
        statusLabel.setText(text);
    }
}


Python Function - Drawing a Triangle with a python fucntion

I've create the following program to draw two triangles in Python 3, one half the size of the other with the robot driving away with pen down.

This is all good and have the solution in place

Working solution

However I'm obsessed in making my code shorter using a python function.

Guidance notes

I have added an optional variable in like the content advises: additional variable

This so I can draw add an argument against the function whenever I call the function to make different sizes of the triangle easily.

Can you see where I'm going wrong here?

Call the function but add an argument against another variable (SIDE_LENGTH) to make smaller or larger versions of the shape



4000% Performance Decrease in SYCL when using Unified Shared Memory instead of Device Memory

In SYCL, there are three types of memory: host memory, device memory, and Unified Shared Memory (USM). For host and device memory, data exchange requires explicit copying. Meanwhile, data movement from and to USM is automatically managed by the SYCL runtime implicitly.

Unfortunately, during the process of implementing GPU acceleration for a numerical kernel using SYCL, I found an up-to 4000% decrease of performance just by switching from sycl::malloc_device() to sycl::malloc_shared() - even if all I do is repeatedly resubmitting the same SYCL kernel, without any attempt to access data from the host.

When building the code with sycl::malloc_device() with OpenSYCL targeting AMD HIP GFX906 (Radeon VII / Instinct MI50), the program finishes in 0.27 seconds:

$ time ./fdtd.elf 
simulate 16974593 cells for 10 timesteps.

real    0m0.271s
user    0m0.253s
sys     0m0.020s

When building the same code with sycl::malloc_shared(), the program takes 10.6 seconds to complete:

simulate 16974593 cells for 10 timesteps.

real    0m10.649s
user    0m15.172s
sys     0m0.196s

This is a 3925% slowdown.

After enabling "Above 4G Decoding" and "Re-sizable BAR" support in BIOS, now it takes 3.8 seconds instead of 10.6 seconds. But this doesn't fix the actual problem of needless memory tranfers - a 1300% performance hit is still pretty significant.

I also tested a similar kernel using the Intel DPC++ compiler previously, and saw similar results on the same hardware.

I suspect that the slowdown is caused by needless host and device copying, but I'm not sure. What heuristics does a SYCL runtime use to determine whether copying is needed?

The sample code is attached below.

ArrayNXYZ.hpp: 4-dimensional array (n, x, y, z) wrapper class.

#include <sycl/sycl.hpp>

template <typename T>
struct ArrayXYZN
{
    ArrayXYZN() {}

    inline T& operator() (const unsigned int n, const unsigned int x, const unsigned int y, const unsigned int z) const
    {
        size_t offset = n * n_stride + x * x_stride + y * y_stride + z;
        return array[offset];
    }

    unsigned long n_stride, x_stride, y_stride, size;
    T *array;
};

template <typename T>
ArrayXYZN<T>* CreateArrayXYZN(sycl::queue Q, const unsigned int* numLines)
{
    unsigned int n_max = 3;
    unsigned int x_max = numLines[0];
    unsigned int y_max = numLines[1];
    unsigned int z_max = numLines[2];

    unsigned long n_stride = x_max * y_max * z_max;
    unsigned long x_stride = y_max * z_max;
    unsigned long y_stride = z_max;

    if (n_stride % 128 != 0)
    {
        n_stride += 128 - (n_stride % 128);
    }

    // allocate 1D linear buffer
    size_t size = n_stride * n_max;

#ifdef USM
    T *buf = sycl::malloc_shared<T>(size, Q);
#else
    T *buf = sycl::malloc_device<T>(size, Q);
#endif

    // zero memory
    Q.submit([&](sycl::handler& h) {
        h.memset(buf, 0, size * sizeof(T));
    });
    Q.wait();

    // allocate wrapper class
    ArrayXYZN<T>* array = new ArrayXYZN<T>();
    array->n_stride = n_stride;
    array->x_stride = x_stride;
    array->y_stride = y_stride;
    array->size = size * sizeof(T);
    array->array = buf;

    return array;
}

fdtd.cpp:

#include <sycl/sycl.hpp>
#include "ArrayNXYZ.hpp"

/*
 * UpdateVoltages
 *
 * Using Finite Difference Time Domain (FDTD) method,
 * calculate new electric field array "volt" based on
 * magnetic field "curr" and two electromagnetic field
 * operators "vv" and "vi", precalculated from the
 * physical materials before starting up simulation.
 */
void UpdateVoltages(
        const ArrayXYZN<float>& volt,
        const ArrayXYZN<float>& curr,
        const ArrayXYZN<float>& vv,
        const ArrayXYZN<float>& vi,
        int x, int y, int z
)
{
    // note: each (x, y, z) cell has three polarizations
    // x, y, z, these are different from the cell's
    // coordinates (x, y, z)

    //for x polarization
    float volt0 = volt(0, x, y, z);
    volt0 *= vv(0, x, y, z);
    volt0 +=
        vi(0, x, y, z) * (
        curr(2, x, y  , z  ) -
        curr(2, x, y-1, z  ) -
        curr(1, x, y  , z  ) +
        curr(1, x, y  , z-1)
        );

    //for y polarization
    float volt1 = volt(1, x, y, z);
    volt1 *= vv(1, x, y, z);
    volt1 +=
        vi(1, x, y, z) * (
        curr(0, x  , y, z  ) -
        curr(0, x  , y, z-1) -
        curr(2, x  , y, z  ) +
        curr(2, x-1, y, z  )
        );

    //for z polarization
    float volt2 = volt(2, x, y, z);
    volt2 *= vv(2, x, y, z);
    volt2 +=
        vi(2, x, y, z) * (
        curr(1, x  , y  , z) -
        curr(1, x-1, y  , z) -
        curr(0, x  , y  , z) +
        curr(0, x  , y-1, z)
        );

    volt(0, x, y, z) = volt0;
    volt(1, x, y, z) = volt1;
    volt(2, x, y, z) = volt2;
}

int main(void)
{
    const unsigned int numLines[3] = {257, 257, 257};
    const int timesteps = 10;

    sycl::queue Q;

    ArrayXYZN<float>& volt = *CreateArrayXYZN<float>(Q, numLines);
    ArrayXYZN<float>& curr = *CreateArrayXYZN<float>(Q, numLines);
    ArrayXYZN<float>& vv = *CreateArrayXYZN<float>(Q, numLines);
    ArrayXYZN<float>& vi = *CreateArrayXYZN<float>(Q, numLines);

    size_t size = numLines[0] * numLines[1] * numLines[2];
    fprintf(stderr, "simulate %ld cells for %d timesteps.\n", size, timesteps);

    for (int i = 0; i < timesteps; i++) {
        Q.submit([&](sycl::handler &h) {
            h.parallel_for<class Voltage>(
                sycl::range(numLines[0] - 1, numLines[1] - 1, numLines[2] - 1),
                [=](sycl::item<3> itm) {
                    /*
                     * The first cell on each dimension has data dependency
                     * outside the simulation box (boundary condition).
                     * Ignore them for now.
                     */
                    int x = itm.get_id(0) + 1;
                    int y = itm.get_id(1) + 1;
                    int z = itm.get_id(2) + 1;

                    UpdateVoltages(volt, curr, vv, vi, x, y, z);
                }
            );
        });
        Q.wait();
    }
}


How to use agda almost without data, only with postulates?

module sets where

postulate
    𝕊 : Set
    _∈_ : 𝕊 → 𝕊 → Set
infix 50 _∈_

data _and_ : Set → Set → Set where
    _∧_ : (x y : Set) → x and y
infixl 40 _and_
infixl 40 _∧_

data _≡_ : Set → Set → Set where
    _eq_ : (a b : Set) → a → b and b → a → a ≡ b
infixr 30 _≡_
infixr 30 _eq_

postulate
    _==_ : 𝕊 → 𝕊 → Set
    ==-def : (x y z : 𝕊) → ((z ∈ x ≡ z ∈ y) ≡ x == y)
infixr 50 _==_

postulate
    eq_ax : (x y : 𝕊) → (x == y) → (z : 𝕊) → (x ∈ z ≡ y ∈ z)
    ∃ : (x : Set) → (z : x → Set) → Set
    ∃-def : (x : Set) → (y : x) → (z : x → Set) → (z y ≡ ∃ x z)
    pair_ax : (x y : 𝕊) → ∃ 𝕊 λ { z → x ∈ z and y ∈ z }
    ∪ : 𝕊 → 𝕊
    ∪_def : (x y : 𝕊) → x ∈ ∪ y ≡ ∃ 𝕊 λ { z → x ∈ z and z ∈ y }
    _⊆_ : 𝕊 → 𝕊 → Set
    ⊆-def : (x y : 𝕊) → ((z : 𝕊) → z ∈ x → z ∈ y) ≡ x ⊆ y
infixl 50 _⊆_

first-proof : (x y : 𝕊) → x ⊆ y → (∪ x) ⊆ (∪ y)
first-proof x y z = {!!}

I am new to Agda. I try to find something that can verify my evidence. And so far Agda seems to be the best option (but still not enough convenient). I am implementing ZFC. And don't know, how to proof the last sentence.

I expect to proof without data, closest to the usual proof with quantifiers and connectives.



2023-07-18

Fixed Total Row When Sorting DataGridview

I have DATAGRIDVIEW CALLED ADVANCEDDATAGRIDVIEW
see this link
https://www.nuget.org/packages/DG.AdvancedDataGridView
okay ?
now I Filled this DGV FROM DATATABLE
Here the First Code : DT is A DATATABLE already has data

        With Form1.AdvancedDataGridView1
            .DataSource = DT
            Form1.BindingSource1.DataSource = .DataSource : Endwith  

So now this DGV HAS DATA FROM DT
And I added BindingSource FROM TOOLBOX into Form1 And i Filled it From DATAGRIDVIEW.DataSource

The AdvancedDataGridview has already Filters Icons Like excel in Microsoft Office
But to make it Work You have to Write this Code in FilteringChange Event like this

    Private Sub AdvancedDataGridView1_FilterStringChanged(sender As Object, e As EventArgs) Handles AdvancedDataGridView1.FilterStringChanged
    BindingSource1.Filter = AdvancedDataGridView1.FilterString : End SUB  

So now Added row in DT as like DT.rows.add() like this
so this ROW i Filled it By sum Of columns
ok.. Now look at the Image and see DGV NOW
THIS IS AdvancedDataGriddView NOW

So As You see there is Filter Icon up Wheni use it And filter data Like excel in MS its work fine
But the last row ( TOTAL ROW ) become Not exist after Filtering
I am sorry for my bad English and description


THIS IS WHAT I Have Tried


    Private Sub AdvancedDataGridView1_FilterStringChanged(sender As Object, e As EventArgs) Handles AdvancedDataGridView1.FilterStringChanged

    Dim A, B As String
    A = CStr(AdvancedDataGridView1.FilterString)
    B = CStr("Convert([ItemName],System.String) IN ('total')")
    BindingSource1.Filter = A Or B

Look Bro (A) Work Alone Fine Like (BindingSource1.Filter = A)
And (B) Work Alone Fine Like (BindingSource1.Filter = B)
But When I say (A Or B) together like this
this error Happened
Additional information: Conversion from string "(Convert([ItemAmount],System.Str" to type 'Long' is not valid.



2023-07-17

Restrict overlay in android

How can I restrict any app to draw it's overlay on our app

canDrawOverlays or TYPE_SYSTEM_OVERLAY || TYPE_SYSTEM_OVERLAY

How can I disable any app that hacks

I have a trivia quiz app . Some developers make app that uses OCR to read question from my app and give results

Developer implement a Service that allows them to write overlay on our app like this

I want to restrict this service or stop it from taking picture using OCR through our app.



2023-07-16

Plot equation / clustering of a plot

Is there any way to get the function or to get only the points in the top of the plot? Consider that the x variable is time (date, seconds) or samples/minute and that the amplitude of the "oscillation" is not fixed. Consider also that the period is not constant.

enter image description here

I was wondering if there is a built-in function in numpy/matplotlib/pandas libraries. Currently I am finding a math equation that could make it work.



PHP and PHPUnit: How to invoke method (or function) with wrong parameter type and then to success?

I want to test (with PHPUnit) a method that contains a foreach loop. I want the full path coverage. The original code is little too complex, so I created a minimal example below to illustrate my problem. There are 3 cases for the foreach loop in the PHP. (I use PHP 8.2.)

  1. Empty iterable something.
  2. Not empty iterable something.
  3. Not iterable something.
    public function dodo(array $a)
    {
        foreach ($a as $one) {
            return $one;
        }

        return null;
    }

It is easy to cover first two: a not empty array and an empty array. But how can I pass a not iterable something as the function argument? I have tried few ways, but I’ve got the TypeError.

$something->dodo(null); # TypeError

call_user_func([$something, 'dodo'], null); # TypeError

$rClass = new ReflectionClass($something);
$rMethod = $rClass->getMethod('dodo');
$rMethod->invoke($something, null); # TypeError

I don’t want to remove or change the type from the method definition. This would make the code a little less readable. Is there a way around? How can I write a test that will cover all cases of the foreach loop?

In other words: How i can call the dodo with an argument of a wrong type? I want to write test with very high code paths coverage.



2023-07-15

How to know if the mouse is on a image in SDL2?

What I need :

I want that when the mouse is on my image, something happen. You know like in HTML, when your mouse is on a link, HTML know it and what happen is that the cursor change to pointer. But unfortunatly, I already know that it is not to easy like in HTML and it is why I am asking you this question.

What I am expecting:

I am expecting that when the user of my game put is mouse on my button, the function that draw the button, will check if the mouse is on the button and if it is clicked like this:

void draw(SDL_Rect infoImage, SDL_Renderer* renderer) {
    bool isHover = 0, isClicked = 0;
    
    //This if is for the hover, or in other word, to see if the mouse is on my image
    if(/*I need this condition*/){
       isHover = 1;
       
       //To see if the image is clicked
       int x, y;
       if(SDL_MOUSEBUTTONDOWN && SDL_BUTTON(SDL_GetMouseState(&x, &y)) == SDL_BUTTON_LEFT){
           isClicked = 1;
       }
    }
    
    //To draw the image
    SDL_RenderCopy(renderer, this->texture, NULL, &infoImage);
    return isHover, isClicked;
}


how to use git diff --name-only with non ascii file names

I have a pre-commit hook that runs

files=`git diff --cached --name-only --diff-filter=ACMR | grep -E "$extension_regex"`

and performs some formatting on those files before committing.

However, I have some files that contain non-ascii letters, and realized those files weren't being formatted.

After some debugging, found that it was because git diff outputted those file names with escaped characters and surrounded with double quotes, for example:

"\341\203\236\341\203\220\341\203\240\341\203\220\341\203\233\341\203\224\341\203\242\341\203\240\341\203\224\341\203\221\341\203\230.ext"

I tried to modify the regex pattern to accept names surrounded with quotes, and even tried removing those quotes, but anywhere I try to access the file it can't be found, for example:

$ cat $file
cat: '"\341\203\236\341\203\220\341\203\240\341\203\220\341\203\233\341\203\224\341\203\242\341\203\240\341\203\224\341\203\221\341\203\230.ext"': No such file or directory

$ file="${file:1:${#file}-2}"

$ cat $file
cat: '\341\203\236\341\203\220\341\203\240\341\203\220\341\203\233\341\203\224\341\203\242\341\203\240\341\203\224\341\203\221\341\203\230.ext': No such file or directory

How do I handle files with non ascii characters?



2023-07-14

extract a dictionary from a string with keys in brace brackets

Is there a way in python to extract a dictionary from a string which includes brace brackets, having the keys of the dictionary referencing the words in the brace brackets?

as an example:

'my name is {name}'

the method would return the following dictionary:

{'name':{}}

This would be to later use the dictionary and populate the string through parameters using .format()

'my name is {name}'.format(**{'name':'salomon'})

The all objective is to read a text file, put brace brackets around words I'd like to transform in parameters, load the text file and extract a dictionary where I can input the desired values to then reinject in the text.

Thank you,



Search through the entire columns in datatable

I've tried several times but it seems like there is an issue with the code, I have a table and I've applied Datatable plugin by using Server Side processing, when I search through the entire table there is no problem except the idCustomer column, for example if I search for a name which is David, there is no result but if I search the id of David for example 10 there is no problem, It seems like the problem is with the idCustomer column from the below code since idCustomer is used as a value in order to retrieve the name of customers through another table, So I want also to be able to search through their names.

Here is my serverside processing code:

<?php
include "../views/lang/config.php";   
require_once "../controllers/customers.controller.php";
require_once "../models/customers.model.php";
 
// DB table to use
$table = 'sales';
 
// Table's primary key
$primaryKey = 'id';
 

$condition = "paymentMethod <> 'loaned'";                 
    if (isset($_GET['initialDate']) && isset($_GET['finalDate'])) { 
        $initialDate = $_GET['initialDate'];
        $finalDate = $_GET['finalDate'];


        if ($initialDate == $finalDate ) {
            $condition .= " AND (DATE(saledate) = '$initialDate' OR DATE(saledate) = DATE('$initialDate')) ";

        }else{

        $actualDate = new DateTime();                  
        $actualDate ->add(new DateInterval("P1D"));     
        $actualDatePlusOne = $actualDate->format("Y-m-d");

        $finalDate2 = new DateTime($finalDate);          
        $finalDate2 ->add(new DateInterval("P1D"));
        $finalDatePlusOne = $finalDate2->format("Y-m-d");

        if($finalDatePlusOne == $actualDatePlusOne){

            $condition .= " AND saledate BETWEEN '$initialDate' AND '$finalDatePlusOne'";

        }else{

            $condition .= " AND saledate BETWEEN '$initialDate' AND '$finalDate'";  

        }


        }



    }




// Array of database columns which should be read and sent back to DataTables.
// The `db` parameter represents the column name in the database, while the `dt`
// parameter represents the DataTables column identifier. In this case simple
// indexes
$columns = array(
    array( 'db' => 'id', 'dt' => 0, 'formatter' => function ($d, $row) {
        $code = $row['code'];
        return '<span data-search="'.$code.'"></span>';
    }),  

    array( 'db' => 'jobOrder', 'dt' => 1,
           'formatter' => function($d, $row){
            $jobOrder = $d;
            $remainingPaymentUSD = $row['remainingPaymentUSD'];
            $remainingPaymentIQD = $row['remainingPaymentIQD'];
            $totalPriceUSD = $row['totalPriceUSD'];
            $totalPriceIQD = $row['totalPriceIQD'];

            // check if the customer paid the total money or there is some money is remaining
            if (($remainingPaymentUSD == 0 && $remainingPaymentIQD == 0) && ($totalPriceUSD > 0 || $totalPriceIQD > 0) ) {
                $jobOrderStatus = '<button class="btn btn-success">'.$jobOrder.'</button>';
            }else{
                $jobOrderStatus = '<button class="btn btn-danger" style="background-color: #dc3545;">'.$jobOrder.'</button>';
            }
            return $jobOrderStatus;
    }),

    array( 'db' => 'code', 'dt' => 2 ),
    array( 'db' => 'idCustomer', 'dt' => 3, 
            'formatter' => function ($d) use ($lang){       // use ($lang) allowing it to access the $lang array
                $itemCustomer = "id";
                $valueCustomer = $d;
                $customerAnswer = ControllerCustomers::ctrShowCustomers($itemCustomer, $valueCustomer);
                if (empty($customerAnswer)) {
                    // Set default value here
                    $customerAnswer['name']= '<button class="btn btn-danger btn-xs">'.  $lang['Customer_is_not_exist']. '</button>';        
                }else{
                    $customerAnswer['name'] = '<a href="index.php?route=customers-profile&IdCustomer='.$valueCustomer.'">'.$customerAnswer['name'].'</a>';
                }
        
        return $customerAnswer['name'];                
    } ),

    array( 'db' => 'totalPriceUSD', 'dt' => 4, 'formatter' => function($d){
            $totalPriceUSD = number_format($d, 2);
            return $totalPriceUSD;
    } ),

    array( 'db' => 'totalPriceIQD', 'dt' => 5, 'formatter' => function($d){
            $totalPriceIQD = number_format($d, 2);
            return $totalPriceIQD;
    } ),

    array( 'db' => 'cashPaymentUSD', 'dt' => 6, 'formatter' => function($d){
            $cashPaymentUSD = number_format($d, 2);
            return $cashPaymentUSD;
    } ),

    array( 'db' => 'cashPaymentIQD', 'dt' => 7, 'formatter' => function($d){
            $cashPaymentIQD = number_format($d, 2);
            return $cashPaymentIQD;
    } ),

    array( 'db' => 'remainingPaymentUSD', 'dt' => 8, 'formatter' => function($d){
            $remainingPaymentUSD = number_format($d, 2);
            return $remainingPaymentUSD;
    } ),

    array( 'db' => 'remainingPaymentIQD', 'dt' => 9, 'formatter' => function($d){
            $remainingPaymentIQD = number_format($d, 2);
            return $remainingPaymentIQD;
    } ),

    array( 'db' => 'saledate', 'dt' => 10 ),
    array( 
        'db' => '',  
        'dt' => 11,
        'formatter' => function($row) {
            $idSale = $row['id'];
            $code = $row['code'];
            $buttonHtml = "<div class='btn-group'>
            <button class='btn btn-success btnPrintBill' saleCode='".$code."'>
            <i class='fa fa-print'></i></button>
            <button class='btn btn-info btnEditSale' idSale='".$idSale."'><i class='fa fa-eye'></i></button>
            <button class='btn btn-danger btnDeleteSale' idSale='".$idSale."'><i class='fa fa-times'></i></button>
            </div>";
            return $buttonHtml;
        }        
         ),



);

 
// SQL server connection information
$sql_details = array(
    'user' => 'aaaaa',
    'pass' => '',
    'db'   => 'bbbbb',
    'host' => 'localhost'
    ,'charset' => 'utf8' // Depending on your PHP and MySQL config, you may need this
);
 
 
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * If you just want to use the basic configuration for DataTables with PHP
 * server-side, there is no need to edit below this line.
 */
 
require( 'ssp.class.php' );
 

echo json_encode(
    SSP::complex($_GET, $sql_details, $table, $primaryKey, $columns, null, $condition) 
);



$(document).ready(function() {

  tableSales = $('#manage_sales_table').DataTable({
    processing: true,
    serverSide: true,
    ajax: 'serverside/sales_server_processing.php',
    language: {
      processing: '<div><div></div><div></div><div></div><div></div></div>'
    }
  });
});

I apperciate your help.



Error in prettyNum(.Internal(format(x, trim, digits, nsmall, width, 3L, : invalid 'nsmall' argument

When I run the negative binomial model with the function below, I get the above error code when I try to the following code.

model<- glm.nb(upvotes ~ Answer_Rate + Score + offset(log(patient_days)) + factor(Post_ID) - 1, control = glm.control(maxit = 500), data = na.omit(mock_data))

summary(model)

# Create the dataframe with NA values
df <- data.frame(
  Post_ID = c(3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18),
  Creation_Year = c(2002, 2003, 2004, 2005, 2008, 2009, 2012, 2013, 2015, 2016, 2021, 2022, 2023, 2027, 2030, 2037),
  Last_Activity_Year = c(rep(2022, 16)),
  Views = c(3868, 2390, 1727, 5456, 2667, 2623, 1084, 2963, 5228, 1833, 1945, 2038, 3856, 3170, 5626, 2058),
  Upvotes = c(364, 654, 151, 246, 341, 82, 0, 270, 569, 184, 291, 265, 366, 439, 628, 293),
  Downvotes = c(63, 40, 54, 44, 90, 75, 36, 105, 157, 55, 79, 79, 93, 119, 103, 94),
  Answer_Count = c(66, 41, 34, 27, 24, 11, 22, 35, 85, 19, 49, 108, 63, 99, 70, 74),
  Score = c(42064, 24958, 18124, 32560, 36219, 27458, 11496, 46426, 60378, 28678, 34798, 32836, 42100, 62402, 54574, 28638),
  View_Rate = c(3.116946, 3.013748, 3.00667, 2.503681, 3.325894, 2.838673, 3.050738, 3.018707, 3.118339, 3.030976, 3.152526, 3.086555, 3.161453, 3.121305, 2.781192, 3.152503),
  Comment_Count = c(0.228, 0.259, NA, 0.215, 0.113, NA, 0.096, 0.035, 0.25, 0.003, 0.337, NA, 0.147, 0.103, NA, 0.203),
  Answer_Rate = c(21.1, NA, 19.7, 18.1, 19.6, 14.8, 12.2, 15.0, 15.3, 16.5, NA, 14.3, 19.8, NA, 17.6, 17.7),
  Favorite_Rate = c(8.65348, 26.204023, 8.331494, 7.555283, 9.414948, NA, 0.0, 5.815707, 9.423962, NA, 8.36255, 8.070411, NA, 7.035031, 11.507311, 10.231161),
  Average_Answer_Rate = c(1.497718, NA, 2.979475, 1.351351, 2.484884, 2.731444, 3.131524, 2.261664, NA, 1.917846, 2.270245, 2.405896, NA, 1.90699, 1.887346, NA),
  Answer_Accept_Rate = c(1.5690377, 1.6427598, 1.8759656, NA, 0.6626356, 0.4006118, NA, 0.7538879, 1.4077975, NA, 1.4081269, 3.289073, 1.4964371, 1.5864876, NA, 2.5839793)
)

I tried to create a new data frame using na.omit in case either of my predictor variables were missing. The same error returned.

The model seems to provide an adequate output with p-value, though I get the error on the summary line code.

Packages for the Markdown:

library(tidyverse)
library(lubridate)
library(janitor)
library(knitr)
library(kableExtra)
library(lme4)
library(gtsummary)
library(data.table)
library(ggalluvial)
library(alluvial)
library(geepack)
library(conflicted)
library(MASS)
library(car)
library(lmtest)
library(vcd)
library(AER)
library(pscl)

conflicts_prefer(gtsummary::select)
conflicts_prefer(dplyr::filter)


2023-07-13

Grails how to change a metaclass Method

I'm trying to remove the square brackets that appear in toString off all collections in Grails. These square brackets are added in the toString of the java.util.AbstractCollection class. So the goal is to replace this toString method and I'm trying to use the ExpandoMetaClass.

I tried to use this code in the Bootstrap file:

 def init = { servletContext ->
     ExpandoMetaClass.enableGlobally()
     AbstractCollection.metaClass.toString << {-> "Test result" }
}

But the error occurs:

Caused by: groovy.lang.GroovyRuntimeException: Cannot add new method [toString] for arguments [[]]. It already exists!

I also tried with the = operator instead of <<. The error does not occur but it has no effect.

Does anybody know how to solve this?



2023-07-12

Using a cached property on a named tuple

from typing import NamedTuple
from functools import cached_property

class Rectangle(NamedTuple):
    x: int
    y: int

    @cached_property
    def area(self):
        return self.x * self.y

I thought this class definition would complain something about the __slots__ on Rectangle, but apparently the class definition is valid. It doesn't fail until too late, if/when the getter is actually accessed:

>>> rect = Rectangle(2, 3)
>>> rect.area
...
TypeError: Cannot use cached_property instance without calling __set_name__ on it.
>>> Rectangle.

Well, that's weird, but okay..

>>> Rectangle.area.__set_name__(Rectangle, "area")
>>> rect.area
...
TypeError: No '__dict__' attribute on 'Rectangle' instance to cache 'area' property.

Is there a better recipe for cached properties on named tuples? Requirements:

  • It should not appear to be a real field (x, y, area = rect should not be possible)
  • It should be lazy (not eagerly computed) and cached (not recomputed every time accessed)
  • Wherever the storage is should not leak memory (it should be deleted when the tuple instance itself is deleted)


2023-07-11

How to sort table data in Angular reactive forms

I am trying to sort table data using an example from StackBlitz.

I am not getting any errors in my code or console. However, the table itself is not doing any sorting at all.

HTML

<thead class="bg-info white">
    <tr>
        <th scope="col" sortable="grade.ccode" (sort)="onSort($event)">
            Code
            <i class="la la-sort float-md-end"></i>
        </th>
        <th scope="col" sortable="gradescription" (sort)="onSort($event)">
            Description
            <i class="la la-sort float-md-end"></i>
        </th>
        <th>Delete Grade</th>
    </tr>
</thead>


<tr *ngFor="let grade of paginationService.paginatedData| gradeSort:filter" (dblclick)="openUpdateModal(editGradeModal, grade)" >
    <!-- <tr *ngFor="let grade of paginationService.paginatedData| grade:filter" (dblclick)="openUpdateModal(editGradeModal, grade)" ></tr> -->
    <td>
        <a href='javascript: void(0);'><u><ngb-highlight [result]="grade.code" [term]="paginationService.searchTerm"></ngb-highlight></u></a>
    </td>
    <td>
        <ngb-highlight [result]="grade.description" [term]="paginationService.searchTerm"></ngb-highlight>
    </td>
    <td>
        <button id="btnDeleteGrade" type="button"
            class="btn btn-block btn-primary glow"
            style="width:100px" (click)="onDeleteGrade(grade)">
            Delete
        </button>
    </td>
</tr>

TypeScript

import { SortableHeaderDirective, SortEvent, compare} from 'src/app/core/directives/sortable-header.directive'

export class ListGradesComponent implements OnInit {
    @ViewChildren(SortableHeaderDirective) headers: QueryList<SortableHeaderDirective>;
    onSort({ column, direction }: SortEvent) {
        // resetting other headers
        this.headers.forEach(header => {
            if (header.sortable !== column) {
                header.direction = '';
            }
        });

        if (direction === ''|| column ==='') {
            this.grades = this.grades;
        } else {
            this.grades.sort((a, b) => {
                const res = compare(a[column], b[column]);
                return direction === 'asc' ? res : -res;
            });
        }

        //this.service.sortColumn = column;
        //this.service.sortDirection = direction;
    }
}

Sortable-header-directive.ts

import { Directive, EventEmitter, Input, Output } from '@angular/core';
import { Country } from './data';

export type SortColumn = keyof Country | '';
export type SortDirection = 'asc' | 'desc' | '';

const rotate: { [key: string]: SortDirection } = {
    asc: 'desc',
    desc: '',
    '': 'asc',
};

export const compare = (
    v1: string | number | boolean | Date,
    v2: string | number | boolean | Date
) => (v1 < v2 ? -1 : v1 > v2 ? 1 : 0);

export interface SortEvent {
    column: SortColumn;
    direction: SortDirection;
}

@Directive({
    selector: 'th[sortable]',
    host: {
        '[class.asc]': 'direction === "asc"',
        '[class.desc]': 'direction === "desc"',
        '(click)': 'rotate()',
    },
})
export class SortableHeaderDirective {
    @Input() sortable: SortColumn = '';
    @Input() direction: SortDirection = '';
    @Output() sort = new EventEmitter<SortEvent>();

    rotate() {
        this.direction = rotate[this.direction];
        this.sort.emit({ column: this.sortable, direction: this.direction });
    }
}


2023-07-10

Add a gradient background line to the circle

I have a block on the page where there is a background line, on the line itself there is a circle that scrolls along with the main scroll

The question is, how can you make it so that, along with the circle, another line of the same color as the circle scrolls along the line, and it all would look something like this:

enter image description here

I tried adding styles to before, but it didn't work out what I expected

left: 50%;
transform: translate(-50%, -50%);
width: 3px;
height: 40vh;
background: #4f8eff;
box-shadow: inset 0 20vh 10vh -10vh #f6e75e, inset 0 -20vh 10vh -10vh #f6e75e;
z-index: 2;

Everything should be like in the picture that I threw off, the circle should be white inside, and the blue color should completely overlap the yellow when we scrolled to the very top, and the same from the bottom. And in the center of the block, let's say the blue color should be both above the circle and below, while maintaining the gradient

const circle = document.querySelector(".circle");
const cases = document.querySelectorAll(".case");

circle.style.transition = ""

const handleScroll = () => {
  const {
    height: blockHeight
  } = document.querySelector(".block2").getBoundingClientRect()

  const maxTop = cases[cases.length - 1].offsetTop + cases[cases.length - 1].offsetHeight - 200
  const minTop = cases[0].offsetTop

  let {
    height: startTop
  } = cases[0].getBoundingClientRect()

  const scrollDist = Math.min(maxTop, Math.max(startTop / 2 + window.scrollY, minTop))

  circle.style.top = `${scrollDist}px`
  circle.style.backgroundSize = `17px ${blockHeight}px`
  circle.style.backgroundPosition = `0 ${-scrollDist}px`
}

const handleWindowSizeAndScroll = () => {
  window.removeEventListener("scroll", handleScroll)
  window.removeEventListener("resize", handleScroll)
  window.addEventListener("scroll", handleScroll)
  window.addEventListener("resize", handleScroll)
}

handleScroll()
handleWindowSizeAndScroll()
window.addEventListener("resize", handleWindowSizeAndScroll)
.block1 {
  height: 200px;
  background-color: gray;
}

.block3 {
  height: 600px;
  background-color: gray;
}

.block2 {
  height: 100%;
  position: relative;
}

.block2,
.block2 .circle {
  background: linear-gradient(214deg, rgba(79, 142, 255, 0) 0%, #f5e550 10%, #f5e550 90%, rgba(79, 142, 255, 0) 100%) center/3px calc(100% - 100px) no-repeat;
}

.block2 .circle {
  background: #4f8eff;
  width: 17px;
  height: 17px;
  left: 50%;
  transform: translate(-50%, -50%);
}

.block2 .circle,
.block2 .circle::before {
  position: absolute;
  border-radius: 50%;
}

.block2 .circle::before {
  content: "";
  inset: 3px;
  background-color: white;
}

.block2 .circle::before {
  left: 50%;
  transform: translate(-50%, -50%);
  width: 3px;
  height: 40vh;
  background: #4f8eff;
  box-shadow: inset 0 20vh 10vh -10vh #f6e75e, inset 0 -20vh 10vh -10vh #f6e75e;
  z-index: 2;
}

.text {
  text-align: center;
  padding: 200px 50px;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css" integrity="sha512-t4GWSVZO1eC8BM339Xd7Uphw5s17a86tIZIj8qRxhnKub6WoyhnrxeCIMeAqBPgdZGlCcG2PrZjMc+Wr78+5Xg==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>
<div class="block1"></div>
<div class="block2">
  <div class="circle"></div>
  <div class="case">
    <div class="row">
      <div class="col-5 text">Text 1</div>
      <div class="col-2"></div>
      <div class="col-5 text">Text 1</div>
    </div>
  </div>
  <div class="case">
    <div class="row">
      <div class="col-5 text">Text 2</div>
      <div class="col-2"></div>
      <div class="col-5 text">Text 2</div>
    </div>
  </div>
  <div class="case">
    <div class="row">
      <div class="col-5 text">Text 3</div>
      <div class="col-2"></div>
      <div class="col-5 text">Text 3</div>
    </div>
  </div>
</div>
<div class="block3"></div>


2023-07-09

How do I set a different font style than what is offered in the FontStyle enum?

I am creating PDF documents using SelectPdf. One of these documents needs to use a client-provided font.

The font family in question is Azo Sans, and it contains several different flavors of font such as bold, italic, regular, etc. It also contains styles like "thin". I need to use this thin style, coupled with italics, in my document.

How can I use a style that is not offered in the FontStyle enum?

I declare my font as such

var font = new Font(font: "Azo Sans", fontSize: 12, fontStyle: FontStyle.Italic | FontStyle.WhatStyleIsUsedHere?);

This works for standard styles like bold, underline, etc. How can I combine Italics with the Thin style offered by the Azo Sans font?



2023-07-08

SQL Server How to count consecutive fields across a row with a start point?

I have a table that for headers has account number, 2022 gift, 2021 gift, 2020 gift, 2019 gift, etc. through to 2004 gift (example below only shows a few columns for visual).

I am looking for code that will count how many consecutive years the donor gave a gift starting with the 2022 gift column and going back from there. So for instance if they gave a gift every year between 2022 and 2016 it should set the count equal to 7. If they didn't give a gift in 2022 (regardless of giving in other years), it would return 0. If they gave a gift in 2022, 2021, 2020 and then skipped 2019 but had given in 2018, it would return 3. Sometimes a field without a gift will be null but other times it will be '0' (both of which would be considered a gap; in case that information is helpful).

Any help would be greatly appreciated. Thanks in advance!

Table Example

Acct # 2022 Gift 2021 Gift 2020 Gift 2019 Gift 2018 Gift 2017 Gift 2016 Gift Count
546885 200 12 74 956 23 45 8559 7
253145 40 5 26 56 20 3
524865 854 523 75 52 0 0

I thought I could do a bulky case when for every possibility (ex. case when 2022 gift <1 then '0' when (all years) > 0 then '20' when 2022 gift >0 and 2021 gift >0 and 2020 gift >0, etc. but I know there has to be a better way to do it than that. My SQL skills are pretty low so my hope is that there is a better way to do it than the huge case when with every possibility.



Trying to filter an array of strings to return a single field which is a subset of the array with strings that contain a variable

The DB has items, and these items have a string parameter which is a comma separated string array. Im trying to pass in a search variable, and use that to return the item node, and the string array but with only the strings that match the search variable

match (n:Node) return n.string

returns the strings sorted by the item node as ["abc,def,abcde"]

match (n:Node)  where any(string in n.string where string contains "abc") return n

This gets me the nodes where one of the strings contains what I'm looking for, but I can't seem to find a way to get the ones which matched and return them as a field

So if a node has a string of ["abc","def","abcde"] then when I search for strings containing "bc" then it should get the node and return just the strings of ["abc","abcde"]



2023-07-07

How to limit elevation over distance using the A search algorithm?

My application finds or constructs routes that are shortest for trekkers in a hilly/mountain terrain using the A* search algorithm. Input files are .dem (Digital Elevation Model) and a roadmap file that contains existing routes. Code is in Python, libraries used are pygdal, NumPy and PyQGIS.

The routes provided by the algorithm are very steep. I want my route to follow the gradient guidelines, like say for every 30m only 1m of elevation.

If I could put my objective in a more simpler way, then it is that using A* I can find the shortest route, but the problem with that it finds path from one peak of the mountain to the valley in a straight line, which is not practical. I want the output should descent from one contour line to another at less that a particular angle so that the descent is not so steep. In this case the recommended gradient descent is 1.91 degrees.



Run-time error 424 "object required" on line with ThisComponent

I got a macro code from the Internet for Microsoft Word 2021 software, and when I implement it in Microsoft Word, I get an error! Does anyone know where the problem comes from?

ERROR:

Here's the error message:

Error424_img 1

And it cccurs on the following line:

Error424_img 2

CODE:

Sub ChangeTashkeelColors()
 CrRepDesc = ThisComponent.createReplaceDescriptor
 CrRepDesc.searchRegularExpression = True
 CrRepDesc.searchString = "?" ' Unicode Character 'ARABIC FATHA' (U+064E) or Shift+q on the Arabic keyboard
 FnAllRepDesc = ThisComponent.findAll(CrRepDesc)
 For i = 0 To FnAllRepDesc.Count - 1
     FoundTxt = FnAllRepDesc.getByIndex(i)
     FoundTxt.CharColor = 1400606  ' Dark Green Color
 Next i
 CrRepDesc = ThisComponent.createReplaceDescriptor
 CrRepDesc.searchRegularExpression = True
 CrRepDesc.searchString = "?" ' Unicode Character 'ARABIC FATHATAN' (U+064B) or Shift+w on the Arabic keyboard
 FnAllRepDesc = ThisComponent.findAll(CrRepDesc)
 For i = 0 To FnAllRepDesc.Count - 1
     FoundTxt = FnAllRepDesc.getByIndex(i)
     FoundTxt.CharColor = 9498256 ' Light Green Color
 Next i
 CrRepDesc = ThisComponent.createReplaceDescriptor
 CrRepDesc.searchRegularExpression = True
 CrRepDesc.searchString = "?" ' Unicode Character 'ARABIC DAMMA' (U+064F) or Shift+e on the Arabic keyboard
 FnAllRepDesc = ThisComponent.findAll(CrRepDesc)
 For i = 0 To FnAllRepDesc.Count - 1
     FoundTxt = FnAllRepDesc.getByIndex(i)
     FoundTxt.CharColor = 9109504 ' Dark Red Color
 Next i
 CrRepDesc = ThisComponent.createReplaceDescriptor
 CrRepDesc.searchRegularExpression = True
 CrRepDesc.searchString = "?" 'Unicode Character 'ARABIC DAMMATAN' (U+064C) or Shift+r on the Arabic keyboard
 FnAllRepDesc = ThisComponent.findAll(CrRepDesc)
 For i = 0 To FnAllRepDesc.Count - 1
     FoundTxt = FnAllRepDesc.getByIndex(i)
     FoundTxt.CharColor = 16764107 ' Light Red Color
 Next i
 CrRepDesc = ThisComponent.createReplaceDescriptor
 CrRepDesc.searchRegularExpression = True
 CrRepDesc.searchString = "?" ' Unicode Character 'ARABIC KASRA' (U+0650) or Shift+a on the Arabic keyboard
 FnAllRepDesc = ThisComponent.findAll(CrRepDesc)
 For i = 0 To FnAllRepDesc.Count - 1
     FoundTxt = FnAllRepDesc.getByIndex(i)
     FoundTxt.CharColor = 139 ' Dark Blue Color
 Next i
 CrRepDesc = ThisComponent.createReplaceDescriptor
 CrRepDesc.searchRegularExpression = True
 CrRepDesc.searchString = "?" ' Unicode Character 'ARABIC KASRATAN' (U+064D) or Shift+s on the Arabic keyboard
 FnAllRepDesc = ThisComponent.findAll(CrRepDesc)
 For i = 0 To FnAllRepDesc.Count - 1
     FoundTxt = FnAllRepDesc.getByIndex(i)
     FoundTxt.CharColor = 11393254 ' Light Blue Color
 Next i
 CrRepDesc = ThisComponent.createReplaceDescriptor
 CrRepDesc.searchRegularExpression = True
 CrRepDesc.searchString = "?" ' Unicode Character 'ARABIC SUKUUN' (U+0652) or Shift+x on the Arabic keyboard
 FnAllRepDesc = ThisComponent.findAll(CrRepDesc)
 For i = 0 To FnAllRepDesc.Count - 1
     FoundTxt = FnAllRepDesc.getByIndex(i)
     FoundTxt.CharColor = 16753920 ' Orange Color
 Next i
 CrRepDesc = ThisComponent.createReplaceDescriptor
 CrRepDesc.searchRegularExpression = True
 CrRepDesc.searchString = "?" ' Unicode Character 'ARABIC SHADDA' (U+0651) or Shift+^ on the Arabic keyboard
 FnAllRepDesc = ThisComponent.findAll(CrRepDesc)
 For i = 0 To FnAllRepDesc.Count - 1
     FoundTxt = FnAllRepDesc.getByIndex(i)
     FoundTxt.CharColor = 6950317 ' Purple Color
 Next i
 End Sub

This code is for changing the color of several diacritics in one word. An error is encountered while running.



2023-07-06

Is there a way to conditionally change the background and text color for a cell in Excel/Google Sheets without using many unique conditional rules?

I'm currently creating a spreadsheet for a card collection, and I want the rows to have their background changed based on what element the card is, I also want the text color to change based on its rarity. I've so far changed the background of the row with a conditional formatting rule (=$I2="Element") for each element, but when I add another condition to change the text color based on rarity for the same cells, only one of the two can be applied at once.

Idealy I'd like to have the Element types and Rarities in a table which have an associated background/text color associated with them, and look at that table when I apply the formatting, but I don't know if that's possible, or how to do it if it is. Currently making a rule for every combination would need me to make 40 conditional formatting rules, and wouldn't easily let me change colors/add new elements. I'd rather avoid that if possible. I'm currently using Google Sheets, but I do have access to Excel if this would only be possible there. Thanks!



setMinimal equivalent in QRegularExpression

I am porting some Qt5 code to Qt6, which requires switching QRegExp to QRegularExpression. The Qt5 code uses the setMinimal(bool minimal) method of QRegExp. Is there an equivalent PatternOption in Qt6?

I see a QRegularExpression::InvertedGreedinessOption PatternOption, but I don't really understand if this is equivalent.



2023-07-05

Sort List of List in Python based on days of the week

I have a list of daily temperature, shown below:

weekly_temperature = [['Saturday', 100], ['Wednesday', 95], ['Friday', 80],
['Monday', 95], ['Sunday', 90], ['Tuesday', 100], ['Thursday', 85]]

How do I sort this list based on days of the week, starting from Monday to Sunday?

I would like the sorted output to look like below:

weekly_temperature = [['Monday', 95], ['Tuesday', 100], ['Wednesday', 95], 
['Thursday', 85], ['Friday', 80], ['Saturday', 100], ['Sunday', 90]]


2023-07-04

How to use a trained yolov8 object box detection model directly in tensorflow js in pure javascript? [closed]

I'm currently trying to use a trained yolov8 object box detection model (for 13 ish classes) from ultralytics, directly in tensorflow js in pure javascript.

I don't want to use roboflow js, onnx etc for running it ; or any framework like node-js implementation etc to serve it.. I want to have a fully working yolov8n model detecting custom objects in images/videos/webcam direclty on browser using only tensorflow js.

In the purpose of having something quite usefull (more than 10fps in webcam), i know that i have to use a quantized model for it. So my second question : What's also the code needed to use a custom yolov8n quantized model ?

I looked pretty much at hundreds of links, topics etc on the subject but i haven't found any for this particular use case. I'm also open to someone that has the full solution for an ssd-mobilenet custom training/deploying solution in pure tensorflow js for object detection with boxes.

You would be very nice and serving a lot of people i think if you share the full solution with codes on how to do it here !

Ps : I know that it's possible but any examples I'have found yet are either using node-js, or are for object classification etc... I haven't found any for my specific purpose : pure smooth tjfs yolov8 object detection with boxes.

[EDIT] If you're willing to help : Just give us the code to use a custom trained yolov8n on image/webcam using tf.loadGraphModel for a normal/16-quantized/8-quantized to work as a working example for this use-case that is nowhere on the internet.

[EDIT 2] I basically came up with this code as of right now... It seems to correclty pass the image to the model but i don't understand the output. What's the catch here ? :

html

js tf.ready().then(() => {

    const modelPath = "https://localhost/test_php/yolov8_model_json";

    tf.tidy(() => {

      tf.loadGraphModel(modelPath, { fromTFHub: true }).then((model) => {
        const mysteryImage = document.getElementById("mystery");


        const tfimg = tf.browser.fromPixels(mysteryImage).toInt();
          const tfimg_res = tf.image.resizeBilinear(tfimg, [640, 640]);
          const expandedimg = tfimg_res.transpose([0, 1, 2]).expandDims();
          
          // const predictions = await model.executeAsync(expandedimg);
          const predictions = model.predict(expandedimg);

          console.log(predictions);

          // get image width, height from output
          const imageWidth = predictions.shape[2]
          const imageHeight = predictions.shape[1]

          console.log('imageWidth:');
          console.log(imageWidth);

          console.log('imageHeight:');
          console.log(imageHeight);

          // create a regular array from the model's output prediction (tensor)
          const map = Array.from(predictions.dataSync())

          console.log('map:');
          console.log(map);

          // create an image with the segmentation color data
          let imageData = new ImageData(imageWidth, imageHeight);
          imageData.data.set(map);

          let canvas = document.getElementById('canvas')
          let ctx = canvas.getContext('2d')
          ctx.putImageData(imageData, 640, 640)
          console.log('processOutput completed:', imageData)

output : console log