问:
Few shot image clasification with Reptile Keras
I am trying to use the few shot learning example provided by Keras using the Reptile algorithm (https://keras.io/examples/vision/reptile/) with my own database. But after loading the database I get an error when i want to visualize some examples from the database.

the line which I have a problem is:

```<code>sample_keys = list(train_dataset())
</code>```

it produces the following:
TypeError: 'Dataset' object is not callable

can somebody help me fix this as I am new in the ML space and still learning.

my database 3 classes all separated in folders with names. each class has 20 RGB pictures so a total of 60.

Database folder structure

The Code with my changes:

```<code>
learning_rate = 0.003
meta_step_size = 0.25

inner_batch_size = 15
eval_batch_size = 15

meta_iters = 2000
eval_iters = 5
inner_iters = 4

eval_interval = 1
train_shots = 20
shots = 5
classes = 3

class Dataset:

    def __init__(self, training):
        # Download the tfrecord files containing the omniglot data and convert to a
        # dataset.
        split = "train" if training else "test"
        images_ds = tf.data.Dataset.list_files('packages/*/*', shuffle=False)
        image_count = len (images_ds)
        #label=["Box","Cardboard","Plastic_bag"]
        ds = images_ds.take(image_count)
        # Iterate over the dataset to get each individual image and its class,
        # and put that data into a dictionary.
        self.data = {}

        def get_label(file_path):
            return tf.strings.split(file_path, os.path.sep)[-2]

        def extraction(file_path):
            # This function will shrink the Omniglot images to the desired size,
            # scale pixel values and convert the RGB image to grayscale
            label = get_label(file_path)
            img = tf.io.read_file(file_path)
            image = tf.image.decode_jpeg(img)
            image = tf.image.convert_image_dtype(image, tf.float32)
            #image = tf.image.rgb_to_grayscale(image)
            image = tf.image.resize(image, [800, 800])
            return image, label

        for image, label in images_ds.map(extraction):
            image = image.numpy()
            label = str(label.numpy())
            if label not in self.data:
                self.data[label] = []
            self.data[label].append(image)
        self.labels = list(self.data.keys())

    def get_mini_dataset(
        self, batch_size, repetitions, shots, num_classes, split=False
    ):
        temp_labels = np.zeros(shape=(num_classes * shots))
        temp_images = np.zeros(shape=(num_classes * shots, 800, 800, 1))
        if split:
            test_labels = np.zeros(shape=(num_classes))
            test_images = np.zeros(shape=(num_classes, 800, 800, 1))

        # Get a random subset of labels from the entire label set.
        label_subset = random.choices(self.labels, k=num_classes)
        for class_idx, class_obj in enumerate(label_subset):
            # Use enumerated index value as a temporary label for mini-batch in
            # few shot learning.
            temp_labels[class_idx * shots : (class_idx + 1) * shots] = class_idx
            # If creating a split dataset for testing, select an extra sample from each
            # label to create the test dataset.
            if split:
                test_labels[class_idx] = class_idx
                images_to_split = random.choices(
                    self.data[label_subset[class_idx]], k=shots + 1
                )
                test_images[class_idx] = images_to_split[-1]
                temp_images[
                    class_idx * shots : (class_idx + 1) * shots
                ] = images_to_split[:-1]
            else:
                # For each index in the randomly selected label_subset, sample the
                # necessary number of images.
                temp_images[
                    class_idx * shots : (class_idx + 1) * shots
                ] = random.choices(self.data[label_subset[class_idx]], k=shots)

        dataset = tf.data.Dataset.from_tensor_slices(
            (temp_images.astype(np.float32), temp_labels.astype(np.int32))
        )
        dataset = dataset.shuffle(60).batch(batch_size).repeat(repetitions)
        if split:
            return dataset, test_images, test_labels
        return dataset

import urllib3

urllib3.disable_warnings()  # Disable SSL warnings that may happen during download.
train_dataset = Dataset(training=True)
test_dataset = Dataset(training=False)

_, axarr = plt.subplots(nrows=5, ncols=5, figsize=(20, 20))

sample_keys = list(train_dataset())    #Here i get the error

for a in range(5):
    for b in range(5):
        temp_image = train_dataset[sample_keys[a]][b]
        temp_image = np.stack((temp_image[:, :, 0],) * 3, axis=2)
        temp_image *= 255
        temp_image = np.clip(temp_image, 0, 255).astype("uint8")
        if b == 2:
            axarr[a, b].set_title("Class : " + sample_keys[a])
        axarr[a, b].imshow(temp_image)#, cmap="rgb")
        axarr[a, b].xaxis.set_visible(False)
        axarr[a, b].yaxis.set_visible(False)
plt.show()
</code>```

The error:

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[23], line 5
      1 ###################### Visualize some examples from the dataset ####################################
      3 _, axarr = plt.subplots(nrows=5, ncols=5, figsize=(20, 20))
----> 5 sample_keys = list(train_dataset())
      7 for a in range(5):
      8     for b in range(5):

TypeError: 'Dataset' object is not callable
</code>```

i tried replacing also

label = str(label.numpy())

with

label = label as it already is in an string format but then I get an error as well which i am still trying to figure out why

Body:
I am trying to use the few shot learning example provided by Keras using the Reptile algorithm (https://keras.io/examples/vision/reptile/) with my own database. But after loading the database I get an error when i want to visualize some examples from the database.

the line which I have a problem is:

sample_keys = list(train_dataset())

it produces the following:
TypeError: 'Dataset' object is not callable

can somebody help me fix this as I am new in the ML space and still learning.

my database 3 classes all separated in folders with names. each class has 20 RGB pictures so a total of 60.

Database folder structure

The Code with my changes:

learning_rate = 0.003
meta_step_size = 0.25

inner_batch_size = 15
eval_batch_size = 15

meta_iters = 2000
eval_iters = 5
inner_iters = 4

eval_interval = 1
train_shots = 20
shots = 5
classes = 3

class Dataset:

    def __init__(self, training):
        # Download the tfrecord files containing the omniglot data and convert to a
        # dataset.
        split = "train" if training else "test"
        images_ds = tf.data.Dataset.list_files('packages/*/*', shuffle=False)
        image_count = len (images_ds)
        #label=["Box","Cardboard","Plastic_bag"]
        ds = images_ds.take(image_count)
        # Iterate over the dataset to get each individual image and its class,
        # and put that data into a dictionary.
        self.data = {}

        def get_label(file_path):
            return tf.strings.split(file_path, os.path.sep)[-2]

        def extraction(file_path):
            # This function will shrink the Omniglot images to the desired size,
            # scale pixel values and convert the RGB image to grayscale
            label = get_label(file_path)
            img = tf.io.read_file(file_path)
            image = tf.image.decode_jpeg(img)
            image = tf.image.convert_image_dtype(image, tf.float32)
            #image = tf.image.rgb_to_grayscale(image)
            image = tf.image.resize(image, [800, 800])
            return image, label

        for image, label in images_ds.map(extraction):
            image = image.numpy()
            label = str(label.numpy())
            if label not in self.data:
                self.data[label] = []
            self.data[label].append(image)
        self.labels = list(self.data.keys())

    def get_mini_dataset(
        self, batch_size, repetitions, shots, num_classes, split=False
    ):
        temp_labels = np.zeros(shape=(num_classes * shots))
        temp_images = np.zeros(shape=(num_classes * shots, 800, 800, 1))
        if split:
            test_labels = np.zeros(shape=(num_classes))
            test_images = np.zeros(shape=(num_classes, 800, 800, 1))

        # Get a random subset of labels from the entire label set.
        label_subset = random.choices(self.labels, k=num_classes)
        for class_idx, class_obj in enumerate(label_subset):
            # Use enumerated index value as a temporary label for mini-batch in
            # few shot learning.
            temp_labels[class_idx * shots : (class_idx + 1) * shots] = class_idx
            # If creating a split dataset for testing, select an extra sample from each
            # label to create the test dataset.
            if split:
                test_labels[class_idx] = class_idx
                images_to_split = random.choices(
                    self.data[label_subset[class_idx]], k=shots + 1
                )
                test_images[class_idx] = images_to_split[-1]
                temp_images[
                    class_idx * shots : (class_idx + 1) * shots
                ] = images_to_split[:-1]
            else:
                # For each index in the randomly selected label_subset, sample the
                # necessary number of images.
                temp_images[
                    class_idx * shots : (class_idx + 1) * shots
                ] = random.choices(self.data[label_subset[class_idx]], k=shots)

        dataset = tf.data.Dataset.from_tensor_slices(
            (temp_images.astype(np.float32), temp_labels.astype(np.int32))
        )
        dataset = dataset.shuffle(60).batch(batch_size).repeat(repetitions)
        if split:
            return dataset, test_images, test_labels
        return dataset

import urllib3

urllib3.disable_warnings()  # Disable SSL warnings that may happen during download.
train_dataset = Dataset(training=True)
test_dataset = Dataset(training=False)

_, axarr = plt.subplots(nrows=5, ncols=5, figsize=(20, 20))

sample_keys = list(train_dataset())    #Here i get the error

for a in range(5):
    for b in range(5):
        temp_image = train_dataset[sample_keys[a]][b]
        temp_image = np.stack((temp_image[:, :, 0],) * 3, axis=2)
        temp_image *= 255
        temp_image = np.clip(temp_image, 0, 255).astype("uint8")
        if b == 2:
            axarr[a, b].set_title("Class : " + sample_keys[a])
        axarr[a, b].imshow(temp_image)#, cmap="rgb")
        axarr[a, b].xaxis.set_visible(False)
        axarr[a, b].yaxis.set_visible(False)
plt.show()

The error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[23], line 5
      1 ###################### Visualize some examples from the dataset ####################################
      3 _, axarr = plt.subplots(nrows=5, ncols=5, figsize=(20, 20))
----> 5 sample_keys = list(train_dataset())
      7 for a in range(5):
      8     for b in range(5):

TypeError: 'Dataset' object is not callable

i tried replacing also

label = str(label.numpy())

with

label = label as it already is in an string format but then I get an error as well which i am still trying to figure out why


来源: stackexchange

问:
Javascript: variable Leaflet popup
I'm using Leaflet with Geojsons and would like to display a popup:

```<code>    onEachFeature: function (feature, layer) {
      layer.bindPopup('MyProperty: ' + feature.properties.property);
    }
</code>```

This works like expected. The popup is "MyProperty: 12345" (for example).
Now I would like to pass the popup string as a parameter in a script.
The source of this popup string is a WordPress shortcode (php).

I tried:
php:

```<code>$content = "'MyProperty: ' + feature.properties.property";
</code>```

php/JavaScript:

```<code>var att_popup = '.json_encode($content).';
//var att_popup = '.$content.';
...
layer.bindPopup(`${att_popup}`);
//layer.bindPopup(att_popup);
...
</code>```

But I can't get the popup reading the feature.properties.property. The popup is always "'MyProperty: ' + feature.properties.property".

How do I make it work? Thank you very much.

ContentLicense: CC BY-SA 4.0

Title: Javascript: variable Leaflet popup

Body:
I'm using Leaflet with Geojsons and would like to display a popup:

    onEachFeature: function (feature, layer) {
      layer.bindPopup('MyProperty: ' + feature.properties.property);
    }

This works like expected. The popup is "MyProperty: 12345" (for example).
Now I would like to pass the popup string as a parameter in a script.
The source of this popup string is a WordPress shortcode (php).

I tried:
php:

$content = "'MyProperty: ' + feature.properties.property";

php/JavaScript:

var att_popup = '.json_encode($content).';
//var att_popup = '.$content.';
...
layer.bindPopup(`${att_popup}`);
//layer.bindPopup(att_popup);
...

But I can't get the popup reading the feature.properties.property. The popup is always "'MyProperty: ' + feature.properties.property".

How do I make it work? Thank you very much.


问:
Pandas cumulative count joining in one column
How can I get one colomn which is the results of df.groupy('src_mac').transform('nunique') but in every groups the value is from 0 to max?

For example:

df:

IP
src_mac

192.168.0.1
abc

192.168.0.2
abc

192.168.0.3
abc

192.168.0.3
abc

192.168.0.4
666

I want to get a column as follows:

ip_num_per_mac

1

2

3

3

1

I have used counts = pd.get_dummies(df['src_mac']).cumsum() to get the cumulative count per 'src_mac' as many columns. Is there any methods to join every columns in one column?


问:
How to prevent Attemting to reconnect to the server Blazor UI when background job is executing
When i execute many task blazor ui freezes until all the tasks are completed.
I dont know how to limit for example the number of task or somehing in blazor to keep showing ui eventhough tasks keeps running in background.
I think this problem is more a asyncrhonous rather than blazor.

Heres my scenario:
I have a simple class,

```<code>    public class Demo
    {
        public int Id;
        public bool WorkDone { get; set; }

        public Demo(int id)
        {
            this.WorkDone = false;
            this.Id = id;
        }

        //some async job that takes time

        public async Task Work()
        {
            await Task.Run(async () =>
            {
                Random r = new();

                Thread.Sleep(1000 * r.Next(1, 10));
                this.WorkDone = true;

            });

        }
    }
</code>```

So my main objective is to show a list of this demo objects, but this list has to be updated with respective object values when the values area updated.
So i did a simple table to show object values, and after the job is done i called statehaschanged async to forze to update the ui:

```<code>@page "/"

<button @onclick=DoWork>Do Work</button>
<table>
    <tr>
        <th>id</th>
        <th>state</th>
    </tr>
    @foreach(var item in this.data)
    {
        <tr>
            <td>@item.Id</td>
            <td>@item.WorkDone</td>
        </tr>
    }
</table>

@if (allworkdone)
{
    <div class="alert alert-success fade-in" role="alert">
        Work Done!
    </div>
}

@code {
    int max = 10;
    List<Demo> data= new();
    bool allworkdone = false;

    protected override void OnInitialized()
    {
        foreach (var item in Enumerable.Range(0, max))
        {
            this.data.Add(new Demo(item));
        }
    }

    public void DoWork()
    {
        List<Task> tasks = new ();
        data.AsParallel().ForAll(async x=>
        {
            await x.Work();
            await InvokeAsync(StateHasChanged);
        });
        allworkdone = true;
        StateHasChanged();
    }
</code>```

So far so good , but when i add more task( change max to 10000 for example), the ui locks and shows the following:

I think the cause is that all "threads" are consumed so the ui cant be refreshed till all the job is done.
Because after the job is done, the ui "comes back"

What are the ways to prevent this effect?
Working on blazor server, net6.
Thanks!

Body:
When i execute many task blazor ui freezes until all the tasks are completed.
I dont know how to limit for example the number of task or somehing in blazor to keep showing ui eventhough tasks keeps running in background.
I think this problem is more a asyncrhonous rather than blazor.

Heres my scenario:
I have a simple class,

    public class Demo
    {
        public int Id;
        public bool WorkDone { get; set; }

        public Demo(int id)
        {
            this.WorkDone = false;
            this.Id = id;
        }

        //some async job that takes time

        public async Task Work()
        {
            await Task.Run(async () =>
            {
                Random r = new();

                Thread.Sleep(1000 * r.Next(1, 10));
                this.WorkDone = true;

            });

        }
    }

So my main objective is to show a list of this demo objects, but this list has to be updated with respective object values when the values area updated.
So i did a simple table to show object values, and after the job is done i called statehaschanged async to forze to update the ui:

@page "/"

<button @onclick=DoWork>Do Work</button>

        id
        state

    @foreach(var item in this.data)
    {

            @item.Id
            @item.WorkDone

    }

@if (allworkdone)
{

        Work Done!

}

@code {
    int max = 10;
    List<Demo> data= new();
    bool allworkdone = false;

    protected override void OnInitialized()
    {
        foreach (var item in Enumerable.Range(0, max))
        {
            this.data.Add(new Demo(item));
        }
    }

    public void DoWork()
    {
        List<Task> tasks = new ();
        data.AsParallel().ForAll(async x=>
        {
            await x.Work();
            await InvokeAsync(StateHasChanged);
        });
        allworkdone = true;
        StateHasChanged();
    }

So far so good , but when i add more task( change max to 10000 for example), the ui locks and shows the following:

I think the cause is that all "threads" are consumed so the ui cant be refreshed till all the job is done.
Because after the job is done, the ui "comes back"

What are the ways to prevent this effect?
Working on blazor server, net6.
Thanks!


问:
Compare Registry properties; hash compare or simple equality
I am looking to do a hash compare of a variety of things; files, folders, registry properties and registry keys.
File hash is easy...

```<code>$Hash1 = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($filePath1)))
$Hash2 = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($filePath2)))
if ($Hash1 -eq $Hash2) {}
</code>```

And folder is easy because I can do a get Get-ChildItem, and if the resulting list isn't identical then the compare is false, and if the list is identical then if any individual file hash isn't identical then the compare is false.
However, I am trying to add registry stuff to this, and I am not clear on how to do the ReadAllBytes() on a registry property. Or, am I really over thinking this since a property is not a complex file, and I should just first check for property kind with $sourceKey.GetValueKind($name) and then compare actual values if the kinds match? Does -eq work with every possible data type in the registry? Or are there gotchas I need to worry about?

Body:
I am looking to do a hash compare of a variety of things; files, folders, registry properties and registry keys.
File hash is easy...

$Hash1 = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($filePath1)))
$Hash2 = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($filePath2)))
if ($Hash1 -eq $Hash2) {}

And folder is easy because I can do a get Get-ChildItem, and if the resulting list isn't identical then the compare is false, and if the list is identical then if any individual file hash isn't identical then the compare is false.
However, I am trying to add registry stuff to this, and I am not clear on how to do the ReadAllBytes() on a registry property. Or, am I really over thinking this since a property is not a complex file, and I should just first check for property kind with $sourceKey.GetValueKind($name) and then compare actual values if the kinds match? Does -eq work with every possible data type in the registry? Or are there gotchas I need to worry about?


问:
How to pass pg-promise transaction/task between ExpressJS middlewares?
ExpressJS can have a chain of middlewares for a single route, which at the very least allows to split input validation logic from the actual handling of the inputs.
The usual pattern looks like this:

import { Router } from "express";

const router = Router();

router.use("/entity/:id", async (req, res, next) => {
  try {
    // validation logic
    const isValid = ...
    // short circuit if validation fails
    if (!isValid) {
      throw new Error("error message")
    }

    // get to the next middleware in chain
    next()
  } catch (error) {
    // pass the error to the error-handling middleware chain instead
    next(error)
  }
});

router.get("/entity/:id", async (req, res, next) => {
  try {
    // route handling logic
    ...
  } catch (error) {
    next(error)
  }
});
```
<p>This works fine as long as validation middleware doesn't require database calls. But in the most basic usecase, auth, it does.</p>
<p>So auth code looks like this:</p>
<pre class="lang-js prettyprint-override"><code>import { Router } from "express";
// `db` object created as per instructions
// https://vitaly-t.github.io/pg-promise/index.html
import { db } from "#db"

const router = Router();

router.use("/auth", async (req, res, next) => {
  try {
    // key retrieval logic
    // assume it throws on any mistake
    const authKey = ...;

    // retrieve session by key
    const session = await db.one(
      "...",
      { authKey }
    )

    // throw if it's not found for whatever reason
    if (!session) {
      throw new Error("error message")
    }

    // save the session value for the request duration
    // so the middleware/handlers can access
    res.locals.session = session

    // get to the next middleware in chain
    next()
  } catch (error) {
    // pass the error to the error-handling middleware chain instead
    next(error)
  }
});

router.get("/auth/:id/posts", async (req, res, next) => {
  try {
    const { id } = req.params;
    // it is guarantied to be always there because
    // of the middleware before
    const session = res.locals.session;
    const posts = await db.manyOrNone("...", {session, id})

    return res.status(200).json(posts);
  } catch (error) {
    next(error)
  }
});
</code>```

The issue here is these 2 middlewares will use 2 separate connections, and it will only get worse with more complicated routing.
Is there a way to create a transaction/task object, which is an argument for the callback for db.tx()/db.task(), which could be passed around outside of these methods?

Body:
ExpressJS can have a chain of middlewares for a single route, which at the very least allows to split input validation logic from the actual handling of the inputs.
The usual pattern looks like this:

import { Router } from "express";

const router = Router();

router.use("/entity/:id", async (req, res, next) => {
  try {
    // validation logic
    const isValid = ...
    // short circuit if validation fails
    if (!isValid) {
      throw new Error("error message")
    }

    // get to the next middleware in chain
    next()
  } catch (error) {
    // pass the error to the error-handling middleware chain instead
    next(error)
  }
});

router.get("/entity/:id", async (req, res, next) => {
  try {
    // route handling logic
    ...
  } catch (error) {
    next(error)
  }
});

This works fine as long as validation middleware doesn't require database calls. But in the most basic usecase, auth, it does.

So auth code looks like this:

import { Router } from "express";
// `db` object created as per instructions
// https://vitaly-t.github.io/pg-promise/index.html
import { db } from "#db"

const router = Router();

router.use("/auth", async (req, res, next) => {
  try {
    // key retrieval logic
    // assume it throws on any mistake
    const authKey = ...;

    // retrieve session by key
    const session = await db.one(
      "...",
      { authKey }
    )

    // throw if it's not found for whatever reason
    if (!session) {
      throw new Error("error message")
    }

    // save the session value for the request duration
    // so the middleware/handlers can access
    res.locals.session = session

    // get to the next middleware in chain
    next()
  } catch (error) {
    // pass the error to the error-handling middleware chain instead
    next(error)
  }
});

router.get("/auth/:id/posts", async (req, res, next) => {
  try {
    const { id } = req.params;
    // it is guarantied to be always there because
    // of the middleware before
    const session = res.locals.session;
    const posts = await db.manyOrNone("...", {session, id})

    return res.status(200).json(posts);
  } catch (error) {
    next(error)
  }
});

The issue here is these 2 middlewares will use 2 separate connections, and it will only get worse with more complicated routing.
Is there a way to create a transaction/task object, which is an argument for the callback for db.tx()/db.task(), which could be passed around outside of these methods?


问:
Denial of Service (DoS) - Make sure the regex used here, which is vulnerable to polynomial runtime due to backtracking
I am new to sonar & regex and it has shown the below line of code as error.

```<code>propHosts.split("\\s*(,\\s*)+")
</code>```

I am not sure what "propHosts" value is, as it is an environmental variable.

The above regex is giving "comma" as the split character. Making changes to the above regex can stop giving me the error in sonar but it can fail in server as we don't know what it stores.

Can any one help me with this in what can be a better replacement for the above regex.

Thank you.

Body:
I am new to sonar & regex and it has shown the below line of code as error.

propHosts.split("\\s*(,\\s*)+")

I am not sure what "propHosts" value is, as it is an environmental variable.

The above regex is giving "comma" as the split character. Making changes to the above regex can stop giving me the error in sonar but it can fail in server as we don't know what it stores.

Can any one help me with this in what can be a better replacement for the above regex.

Thank you.


问:
Integrate React into Wordpress Dashboard-Plugin
I am currently building a wordpress plugin for the dashboard.
Everything works so far, but at the moment I handle everything with jQuery.
I would now like to integrate React instead of jQuery for practice.

For this I have first created a React app in my plugin

```<code>npx create-react-app reactapp
</code>```

In my dashboard I created a page with the following code:

```<code><?php

echo "<div id='root'></div>";
</code>```

Now I wanted to load React:

```<code>wp_register_script('react-js', plugin_dir_url(__FILE__). "templates/reactapp/src/index.js" , array(),null, true);
wp_enqueue_script('react-js');
</code>```

But there is now the following error in the console if I open the page in the Dashboard:

Uncaught SyntaxError: Cannot use import statement outside a module (at index.js:1:1)

What is the best way to proceed?

Body:
I am currently building a wordpress plugin for the dashboard.
Everything works so far, but at the moment I handle everything with jQuery.
I would now like to integrate React instead of jQuery for practice.

For this I have first created a React app in my plugin

npx create-react-app reactapp

In my dashboard I created a page with the following code:

<?php

echo "

";

Now I wanted to load React:

wp_register_script('react-js', plugin_dir_url(__FILE__). "templates/reactapp/src/index.js" , array(),null, true);
wp_enqueue_script('react-js');

But there is now the following error in the console if I open the page in the Dashboard:

Uncaught SyntaxError: Cannot use import statement outside a module (at index.js:1:1)

What is the best way to proceed?


问:
android aar file file empty/no .class file after updating build Gradle to 7.3.1
After updating

From
classpath 'com.android.tools.build:gradle:7.2.2' to

```<code>classpath 'com.android.tools.build:gradle:7.3.1'
</code>```

and try to Create aar file for my library project, its creates aar file with less size where I could see no .class files at all, So forth the app which is importing this library gets method not found error.
enter image description here

I am using compileSdkVersion 33 &  targetSdkVersion 33 in both app & library project.
Used gradle-7.4-all.zip

Tried decremented to 32 too, but no effect.

With 7.2.2 all good. I could see .class file available.
enter image description here

How to resolve this issue, I don't have option to degrade gradle option, I must have to update in order to support apps with latest gradle version

Body:
After updating

From
classpath 'com.android.tools.build:gradle:7.2.2' to

classpath 'com.android.tools.build:gradle:7.3.1'

and try to Create aar file for my library project, its creates aar file with less size where I could see no .class files at all, So forth the app which is importing this library gets method not found error.
enter image description here

I am using compileSdkVersion 33 &  targetSdkVersion 33 in both app & library project.
Used gradle-7.4-all.zip

Tried decremented to 32 too, but no effect.

With 7.2.2 all good. I could see .class file available.
enter image description here

How to resolve this issue, I don't have option to degrade gradle option, I must have to update in order to support apps with latest gradle version


问:
Update the number of rows based on multi where conditions across tables
I have two tables: [Invoices], which has a field on Vendor ID "i_v_id," and [Inventory_adjustment], which has columns Debit, Credit, and flag value which is set to 0 by default.
In this situation, I need to update every row in the inventory_adjustment database that fits the WHERE requirements.

I tried several methods to update the rows, but they all resulted in error warnings.

Error Number: 1064 You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near '.inad_invoice_id SET inad_adjusted_flag = 1
WHERE IA.inad_date >= '2022-12' at line 1 UPDATE
inventory_adjustment IA JOIN invoices I ON I.i_id =
IA.inad_invoice_id SET inad_adjusted_flag = 1 WHERE
IA.inad_date >= '2022-12-25' AND IA.inad_date <= '2023-01-03'
AND I.i_v_id = '3'

Model

```<code>function Adjustment()
    {

        $data=array(
            'IA.inad_adjusted_flag' => "1"
        );
        $datefrom = $this->input->post('datefrom');
        $dateto = $this->input->post('dateto');
        $this->db->where('IA.inad_date >=', $datefrom);
        $this->db->where('IA.inad_date <=', $dateto);
        $this->db->where('I.i_v_id', $this->input->post('vendor_id'));
        $this->db->update('inventory_adjustment IA JOIN invoices I ON I.i_id = IA.inad_invoice_id',$data);
        if ($this->db->affected_rows() > 0) {
            return true;
        } else {
            return false;
        }
    }
</code>```

Body:
I have two tables: [Invoices], which has a field on Vendor ID "i_v_id," and [Inventory_adjustment], which has columns Debit, Credit, and flag value which is set to 0 by default.
In this situation, I need to update every row in the inventory_adjustment database that fits the WHERE requirements.

I tried several methods to update the rows, but they all resulted in error warnings.

Error Number: 1064 You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near '.inad_invoice_id SET inad_adjusted_flag = 1
WHERE IA.inad_date >= '2022-12' at line 1 UPDATE
inventory_adjustment IA JOIN invoices I ON I.i_id =
IA.inad_invoice_id SET inad_adjusted_flag = 1 WHERE
IA.inad_date >= '2022-12-25' AND IA.inad_date <= '2023-01-03'
AND I.i_v_id = '3'

Model

function Adjustment()
    {

        $data=array(
            'IA.inad_adjusted_flag' => "1"
        );
        $datefrom = $this->input->post('datefrom');
        $dateto = $this->input->post('dateto');
        $this->db->where('IA.inad_date >=', $datefrom);
        $this->db->where('IA.inad_date <=', $dateto);
        $this->db->where('I.i_v_id', $this->input->post('vendor_id'));
        $this->db->update('inventory_adjustment IA JOIN invoices I ON I.i_id = IA.inad_invoice_id',$data);
        if ($this->db->affected_rows() > 0) {
            return true;
        } else {
            return false;
        }
    }


问:
Weglot plugin is not translating my image
I am using Slider Revolution on my website and I am using the Weglot plugin to translate the website to Arabic and Kurdish, but Weglot is not showing my slider images when I am translating the website to Kurdish and Arabic. I also added the media link to the translation but it is still not showing, it shows a white space.</p>


问:
Gnome Builder: Close all opened documents (tabs)?
I could not find any way to close multiple documents. Does Gnome Builder have no such feature?


问:
moodle application android with deepLinking - Android
How can I go from my app to moodle application with deepLinking like bellow?

My moodle application android is customize(I have my domain, username and ...)now I need to redirect user from an application to moodle application android.

Like this link

I need to a sample. Thanks


问:
Is there a way not to include the hover style when copying/pasting a grapes js content
Steps done to encounter this issue
I have an element with a blue background, then if I hover it, the background color turns black.
When I Copy the text inside of that element, and paste it also on that element, it creates another span with a background color of black which is the background color when hovering.
Is there a way not to include that hover style when pasting?

I've read the documentation but it doesn't give any help about this, or I just missed or didn't understand all the documentation


问:
Vue js change structure dist
I need to change the structure of my files when I put in production :

default :

-dist
--css
--fonts
--img
--js
--favicon.ico
--index.html

and i want like this :
-dist
--index.html
--app
---css
---fonts
---img
---js
---favicon.ico

I try to change directly the html in index.html

```<code><!doctype html>
<html lang="">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link rel="icon" href="app/favicon.ico">
    <title>Roquette</title>
    <script defer="defer" src="app/js/chunk-vendors.6e8aa085.js"></script>
    <script defer="defer" src="app/js/app.4955a200.js"></script>
    <link href="app/css/app.d0b83381.css" rel="stylesheet">
</head>
<body>
    <noscript><strong>We're sorry but serveur-roquette doesn't work properly without JavaScript enabled. Please enable it to continue.</strong></noscript><div id="app"></div>
</body>
</html>
</code>```

But it doesn't work there must be some paths missing somewhere

Title: Vue js change structure dist

Body:
I need to change the structure of my files when I put in production :

default :

-dist
--css
--fonts
--img
--js
--favicon.ico
--index.html

and i want like this :
-dist
--index.html
--app
---css
---fonts
---img
---js
---favicon.ico

I try to change directly the html in index.html

<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link rel="icon" href="app/favicon.ico">
    <title>Roquette</title>

    <link href="app/css/app.d0b83381.css" rel="stylesheet">

    We're sorry but serveur-roquette doesn't work properly without JavaScript enabled. Please enable it to continue.

But it doesn't work there must be some paths missing somewhere


问:
QGIS plugin - getting ModuleNotFoundError when importing specifically python-ternary
I am building a QGIS plugin and I'd like to import a module named python-ternary. I have a specific issue importing this module (others get imported), and importing it in QGIS (works outside of QGIS).

I installed it using pip, tried to import it outside of QGIS, works fine.

Now writing this in my plugin main file:

```<code>from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication, Qt
from qgis.PyQt.QtGui import QIcon, QColor
from qgis.PyQt.QtWidgets import QAction, QApplication

from .resources import *

import psycopg2
import ternary
</code>```

I get this when loading my plugin with the QGIS plugin manager:

QGIS error when loading the plugin

Now the python-ternary module is well installed in lib\site-packages:
ternary file in lib\site-packages

And lib\site-packages is on path as shown in the QGIS error.

I have no problem importing other modules in QGIS e.g. psycopg2 is imported without issue. I force reinstalled python-ternary with pip, to no avail.

Is there a compatibility issue with this particular module I'm not aware of ?

Body:
I am building a QGIS plugin and I'd like to import a module named python-ternary. I have a specific issue importing this module (others get imported), and importing it in QGIS (works outside of QGIS).

I installed it using pip, tried to import it outside of QGIS, works fine.

Now writing this in my plugin main file:

from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication, Qt
from qgis.PyQt.QtGui import QIcon, QColor
from qgis.PyQt.QtWidgets import QAction, QApplication

from .resources import *

import psycopg2
import ternary

I get this when loading my plugin with the QGIS plugin manager:

QGIS error when loading the plugin

Now the python-ternary module is well installed in lib\site-packages:
ternary file in lib\site-packages

And lib\site-packages is on path as shown in the QGIS error.

I have no problem importing other modules in QGIS e.g. psycopg2 is imported without issue. I force reinstalled python-ternary with pip, to no avail.

Is there a compatibility issue with this particular module I'm not aware of ?


问:
How to take postgres backup via pg_basebackup
I have to take the pg_basebackup of my postgres cluster. So how I can take the backup of this cluster.
I use the Bitnami Helm chart for PostgreSQL installation. Following Link for reference
https://phoenixnap.com/kb/postgresql-kubernetes
from that 2nd part. Deploy PostgreSQL by Creating Configuration from Scratch.

After successful installation
I tried to take pg_basebackup from localhost

```<code>from Localhost execution-->
pg_basebackup -h localhost -U postgres -D /root/base_bkp -v

pg_basebackup: error: server closed the connection unexpectedly
        This probably means the server terminated abnormally
        before or while processing the request.

</code>```
```<code>2023-01-03 07:16:42.889 GMT [1005845] FATAL:  no pg_hba.conf entry for replication connection from host "10.XX.XXX.X", user "postgres", SSL off
2023-01-03 07:16:42.889 GMT [1005845] DETAIL:  Client IP address resolved to "10-XX-XXX-X.postgres-postgresql-ha-pgpool.postgres.svc.cluster.local", forward lookup not checked.

</code>```

host "10.XX.XXX.X" --> This is the pgpool node ip

```<code>root@hostname~a# kubectl get pods -n postgres -o wide
NAME                                             READY   STATUS    RESTARTS   AGE     IP              NODE        NOMINATED NODE   READINESS GATES
postgres-postgresql-ha-pgpool-6XXXXXX-fXXXX   1/1     Running   0          1d7h   10.XX.XXX.X            <none>           <none>
postgres-postgresql-ha-postgresql-0              1/1     Running   0          1d7h   10.XX.YYY.Y        <none>           <none>
postgres-postgresql-ha-postgresql-1              1/1     Running   0          1d7h   10.XX.ZZZ.Z      <none>           <none>
postgres-postgresql-ha-postgresql-2              1/1     Running   0          1d7h   10.XX.PPP.P            <none>           <none>
</code>```

Can anyone help me that from where I need to initiate the backup and how?

Body:
I have to take the pg_basebackup of my postgres cluster. So how I can take the backup of this cluster.
I use the Bitnami Helm chart for PostgreSQL installation. Following Link for reference
https://phoenixnap.com/kb/postgresql-kubernetes
from that 2nd part. Deploy PostgreSQL by Creating Configuration from Scratch.

After successful installation
I tried to take pg_basebackup from localhost

from Localhost execution-->
pg_basebackup -h localhost -U postgres -D /root/base_bkp -v

pg_basebackup: error: server closed the connection unexpectedly
        This probably means the server terminated abnormally
        before or while processing the request.

2023-01-03 07:16:42.889 GMT [1005845] FATAL:  no pg_hba.conf entry for replication connection from host "10.XX.XXX.X", user "postgres", SSL off
2023-01-03 07:16:42.889 GMT [1005845] DETAIL:  Client IP address resolved to "10-XX-XXX-X.postgres-postgresql-ha-pgpool.postgres.svc.cluster.local", forward lookup not checked.

host "10.XX.XXX.X" --> This is the pgpool node ip

root@hostname~a# kubectl get pods -n postgres -o wide
NAME                                             READY   STATUS    RESTARTS   AGE     IP              NODE        NOMINATED NODE   READINESS GATES
postgres-postgresql-ha-pgpool-6XXXXXX-fXXXX   1/1     Running   0          1d7h   10.XX.XXX.X            <none>           <none>
postgres-postgresql-ha-postgresql-0              1/1     Running   0          1d7h   10.XX.YYY.Y        <none>           <none>
postgres-postgresql-ha-postgresql-1              1/1     Running   0          1d7h   10.XX.ZZZ.Z      <none>           <none>
postgres-postgresql-ha-postgresql-2              1/1     Running   0          1d7h   10.XX.PPP.P            <none>           <none>

Can anyone help me that from where I need to initiate the backup and how?


问:
Selenium 4.7.0 ChromeOptions notifications
i can't set the notification on Selenium version 4.7 in c#

I tried

```<code>chromeOptions.AddAdditionalOption("profile.default_content_setting_values.notifications", 1);
</code>```

but it did not work, ie, chrome always prompts me to enable notifications manually. I wish they were always accepted by default.

does anyone know what to do?

thank you

Body:
i can't set the notification on Selenium version 4.7 in c#

I tried

chromeOptions.AddAdditionalOption("profile.default_content_setting_values.notifications", 1);

but it did not work, ie, chrome always prompts me to enable notifications manually. I wish they were always accepted by default.

does anyone know what to do?

thank you


问:
iOS Firebase Remote Config --- Error Domain=com.google.remoteconfig.ErrorDomain Code=8003
I am using Firebase's Remote Config here on iOS, whether I call fetchAndActivateWithCompletionHandler or fetchWithExpirationDuration and activateWithCompletion, I have encountered such an error:

Error Domain=com.google.remoteconfig.ErrorDomain Code=8003 "Failed to
get installations token.

For this problem, has a friend already solved it? Thx!

I call fetchAndActivateWithCompletionHandler
or fetchWithExpirationDuration and activateWithCompletion, but no solve it.


问:
Hook a too-short function
I found a function that I would like to hook.
The function looks that way:

```<code>undefined __register setVisible(int param_1, undefined param_2)
             undefined         AL:1           <RETURN>
             int               EAX:4          param_1
             undefined         DL:1           param_2
                             setVisible

    XREF[3705]:  [...]
0047c09c 88 50 18        MOV        byte ptr [param_1 + 0x18],param_2
0047c09f c3              RET
</code>```

My goal is to jump to my own function when this one is called.
A jump to my own function will take 5 bytes while the function I want to replace is 4 bytes large, meaning that I would be overriding the function below (FUN_0047c0a0).
I can obviously find a way to avoid having to hook this function by hooking the code that calls this function, but this one is being called from a lot of different functions and that does not seem to be the proper way to do.

Do you have any idea how I could manage to handle such a case, where a function is shorter than an hook?

Title: Hook a too-short function

Body:
I found a function that I would like to hook.
The function looks that way:

undefined __register setVisible(int param_1, undefined param_2)
             undefined         AL:1           <RETURN>
             int               EAX:4          param_1
             undefined         DL:1           param_2
                             setVisible

    XREF[3705]:  [...]
0047c09c 88 50 18        MOV        byte ptr [param_1 + 0x18],param_2
0047c09f c3              RET

My goal is to jump to my own function when this one is called.
A jump to my own function will take 5 bytes while the function I want to replace is 4 bytes large, meaning that I would be overriding the function below (FUN_0047c0a0).
I can obviously find a way to avoid having to hook this function by hooking the code that calls this function, but this one is being called from a lot of different functions and that does not seem to be the proper way to do.

Do you have any idea how I could manage to handle such a case, where a function is shorter than an hook?


问:
Moment JS- React 18
i want to ask about the moment of a date which is recuperated from MongoDB (creation Date)
The problem is when i work with the moment to the (creation date)which is recuperated from MongoDB, i got the current date (date of today)!!
There are two screenshots that can explain more:
(https://i.stack.imgur.com/U1EPH.png)]
(https://i.stack.imgur.com/RnUod.png)

i worked with moment js and i want other propositions if found
Thank you so much

Title: Moment JS- React 18


问:
Is it possible to migrate Artemis multicast temporary queue to Amazon SNS / SQS solutions?
currently we are using Artemis for our publish-subscribe pattern and at one specific case, we are using temporary queues to subscribe to a topic. They are non-shared and non-durable and they receive messages as long as there is a consumer listening from those. As a simple example, application instances are using local cache for a configuration and if that configuration is changed, an event is published, each instance receives the same message and evict their local caches. Each instance is connecting with temporary queue (names created by broker with UUID) at startup, and they may be restarted because of a deployment or rescheduling on kubernetes (as they are running on spot instances). Is it possible to migrate this usage to AWS services using SNS and SQS?

So far, I could only see virtual queues close to this, but as far as I understand they do not receive same message on different virtual queues (of one standard queue). If I have to use standard queues to subscribe for each instance, then I would need to use unique names for instances but there may be also scaling up and then scale down, so application needs to detect queues that do not have consumers anymore and remove them (so they do not receive messages from topic anymore).

I have made some trials with virtual queues where I have created two consumer threads (receiving messages with AmazonSQSVirtualQueuesClient) and send message to host queue (with AmazonSQSClient). They did not end up on virtual queues, in fact messages are still on the queue at the moment. I have also tried to send the message with AmazonSQSVirtualQueuesClient but then get warning WARNING: Orphaned message sent to ... . I believe it is only fit for request-responder pattern and the exact destination needs to be known by publisher.


问:
Display image from backend on frontend (Flask on backend, JS frontend)
I have web application that getting image (BLOB file in SQL) and needs to show it on web page.

Here is full code of page. 1) form to submit request 2) JS to make request 3) JS code to catch response and show it in

```<code><img id="image_data" src="">
</code>```

here is info from developer mode so i see image there in preview (and nothing in response)
enter image description here

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="{{ url_for('static', filename= 'css/style.css') }}">
    <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">
    <title>Lazy board</title>
  </head>
  <script>
    function addNavBar() {
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          document.getElementById("navbar").innerHTML = this.responseText;
        }
      };
      xhttp.open("GET", "navbar.html", true);
      xhttp.send();
    }
  </script>
  <body>
    <div id="navbar"></div>
    <script>
      addNavBar();
    </script>
    <h1>Get picture</h1>
    <form id="getPicture">
      <label for="content_id">Content ID:</label>
      <br><br>
      <input type="text" id="content_id" name="content_id">
      <br>
      <img id="image_data" src="">
      <br>
      <input type="submit" class="button" value="Submit">
    </form>
    <script>
      var form = document.getElementById('getPicture');
      form.addEventListener('submit', function(event) {
        event.preventDefault();
        var contentId = document.getElementById('content_id').value;
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '/getPicture');
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.addEventListener('load', function() {
          var response = xhr.response;
          document.body.innerHTML += response;
          document.getElementById('image_data').src = response;
        });
        var formData = new URLSearchParams();
        formData.append('content_id', contentId);
        xhr.send(formData);

      });
    </script>
  </body>
</html>

</code>```

Tried many things. backends response looks like that and yes, in DB is png file that i can view also

```<code>        return Response(image_data, mimetype='image/png')
</code>```

Body:
I have web application that getting image (BLOB file in SQL) and needs to show it on web page.

Here is full code of page. 1) form to submit request 2) JS to make request 3) JS code to catch response and show it in

here is info from developer mode so i see image there in preview (and nothing in response)
enter image description here

<!DOCTYPE html>

    <meta charset="UTF-8">
    <link rel="stylesheet" href="{{ url_for('static', filename= 'css/style.css') }}">
    <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">
    <title>Lazy board</title>

Get picture

    <form id="getPicture">
      Content ID:

      <input type="text" id="content_id" name="content_id">

      <input type="submit" class="button" value="Submit">
    </form>

Tried many things. backends response looks like that and yes, in DB is png file that i can view also

        return Response(image_data, mimetype='image/png')


问:
What is operator( ) instead of operator( ) ( )?
I have seen class in a library I am using, there is a use of operator overloading that I haven't seen and I can't understand. I can't call it, and it's not the typical parentheses operator overloading I've seen and used which is usually like void operator()(), with two sets of parentheses:</p>
```<code>template <typename T, int N = 1>
class Bitmap {

  // irrelevant code excised

    T * operator()(int x, int y);
    const T * operator()(int x, int y) const;
#ifdef MSDFGEN_USE_CPP11
    explicit operator T *();
    explicit operator const T *() const;
#else
    operator T *(); // THESE ONES
    operator const T *() const; // // THESE ONES
#endif
    operator BitmapRef<T, N>(); // THESE ONES
    operator BitmapConstRef<T, N>() const; // THESE ONES

};
</code>```

Body:
I have seen class in a library I am using, there is a use of operator overloading that I haven't seen and I can't understand. I can't call it, and it's not the typical parentheses operator overloading I've seen and used which is usually like void operator()(), with two sets of parentheses:

template <typename T, int N = 1>
class Bitmap {

  // irrelevant code excised

    T * operator()(int x, int y);
    const T * operator()(int x, int y) const;
#ifdef MSDFGEN_USE_CPP11
    explicit operator T *();
    explicit operator const T *() const;
#else
    operator T *(); // THESE ONES
    operator const T *() const; // // THESE ONES
#endif
    operator BitmapRef<T, N>(); // THESE ONES
    operator BitmapConstRef<T, N>() const; // THESE ONES

};


问:
Editing The Tutor Dashboard
I added a custum link to the Tutor Dashboard it’s called “Marketing”.

1- I tried many times with the ‘documentation’ to add the icon to this custum link but it dosent work with me.

2- I use the AffiliateWP plugin and i want to add the affiliate page directly in this custum link “Marketing” in the Tutor Dash. right now when the user click in Marketing a new page open. I want to ask if it possible to show the result in the Tuto Dash without going to a new page.

Title: Editing The Tutor Dashboard


问:
To extract specific clusters from a image after applying k means clustering
Here i have radish field image which consists of three classes bareground, mulching film and radish(crop region). Now my goal is to use k means clustering to cluster the regions and then apply a cnn to classify each region to assign a class to them. But in order to apply cnn we need to extract the specific clusters from the image after k means clustering which i havent found a solution to. Here is the code :

import numpy as np import matplotlib.pyplot as plt import cv2

%matplotlib inline

Read in the image

image = cv2.imread('D:\\capstone project\\capstone research papers\\Drone agriculture imagery system for Radish Wilt Disease\\datasetB\\36.jpg')

Change color to RGB (from BGR)

image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
plt.imshow(image)
enter image description here

image.shape
(3000, 4000, 3)

Reshaping the image into a 2D array of pixels and 3 color values (RGB)

pixel_vals = image.reshape((-1,3))

Convert to float type

pixel_vals = np.float32(pixel_vals)
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)

then perform k-means clustering wit h number of clusters defined as 3

k = 3 ``retval, labels, centers = cv2.kmeans(pixel_vals, k, None, criteria, 10, cv2.KMEANS_PP_CENTERS)

convert data into 8-bit values

centers = np.uint8(centers) ``segmented_data = centers[labels.flatten()]

reshape data into the original image dimensions

segmented_image = segmented_data.reshape((image.shape))
plt.imshow(segmented_image)
enter image description here`


问:
How do I capture the running command and its output of a shell command in Go?
I have the following program executing shell commands using exec.Command() in os/exec golang package and capturing the output.

package main

import (
    "bufio"
    "fmt"
    "os/exec"
)

func main() {
    cmd := exec.Command("bash", "-c", "ls -la; go version; date;")

    stdout, _ := cmd.StdoutPipe()

    logChan := make(chan string)

    _ = cmd.Start()
    scanner := bufio.NewScanner(stdout)
    scanner.Split(bufio.ScanLines)
    go sendLog(logChan, scanner)

    for l := range logChan {
        fmt.Println(l)
    }

    cmd.Wait()
}

func sendLog(logChan chan<- string, scanner *bufio.Scanner) {
    defer close(logChan)
    for scanner.Scan() {
        m := scanner.Text()
        logChan <- m
    }
}
```
<p>Output:</p>
```total 8
drwxr-xr-x   3 akshayd  staff   96  3 Jan 15:20 .
drwxr-xr-x  11 akshayd  staff  352  3 Jan 15:20 ..
-rw-r--r--   1 akshayd  staff  542  3 Jan 16:29 main.go
go version go1.18.1 darwin/arm64
Tue  3 Jan 2023 16:29:14 IST
```
<p>Along with the output i also want to capture the command its executing. Like this.</p>
```ls -la
total 8
drwxr-xr-x   3 akshayd  staff   96  3 Jan 15:20 .
drwxr-xr-x  11 akshayd  staff  352  3 Jan 15:20 ..
-rw-r--r--   1 akshayd  staff  542  3 Jan 16:29 main.go

go version
go version go1.18.1 darwin/arm64

date
Tue  3 Jan 2023 16:29:14 IST
```

How can i acheive this?

Body:
I have the following program executing shell commands using exec.Command() in os/exec golang package and capturing the output.

package main

import (
    "bufio"
    "fmt"
    "os/exec"
)

func main() {
    cmd := exec.Command("bash", "-c", "ls -la; go version; date;")

    stdout, _ := cmd.StdoutPipe()

    logChan := make(chan string)

    _ = cmd.Start()
    scanner := bufio.NewScanner(stdout)
    scanner.Split(bufio.ScanLines)
    go sendLog(logChan, scanner)

    for l := range logChan {
        fmt.Println(l)
    }

    cmd.Wait()
}

func sendLog(logChan chan<- string, scanner *bufio.Scanner) {
    defer close(logChan)
    for scanner.Scan() {
        m := scanner.Text()
        logChan <- m
    }
}

Output:

total 8
drwxr-xr-x   3 akshayd  staff   96  3 Jan 15:20 .
drwxr-xr-x  11 akshayd  staff  352  3 Jan 15:20 ..
-rw-r--r--   1 akshayd  staff  542  3 Jan 16:29 main.go
go version go1.18.1 darwin/arm64
Tue  3 Jan 2023 16:29:14 IST

Along with the output i also want to capture the command its executing. Like this.

ls -la
total 8
drwxr-xr-x   3 akshayd  staff   96  3 Jan 15:20 .
drwxr-xr-x  11 akshayd  staff  352  3 Jan 15:20 ..
-rw-r--r--   1 akshayd  staff  542  3 Jan 16:29 main.go

go version
go version go1.18.1 darwin/arm64

date
Tue  3 Jan 2023 16:29:14 IST

How can i acheive this?


问:
EF7 all related entities in ICollection loaded twice
I have two entities, Function and Department with a Many to Many table in between.

public class Department
{
    public Department()
    {
        DepartmentFunctions = new HashSet<DepartmentFunction>();
        PersonFunctions = new HashSet<PersonFunction>();
    }

    public int Id { get; set; }

    public string Name { get; set; }

    public virtual ICollection<DepartmentFunction> DepartmentFunctions { get; set; }

    public DateTime? DeletedAt { get; set; }
}
```
<pre class="lang-cs prettyprint-override"><code>public class Function
{
    public Function()
    {
        DepartmentFunctions = new HashSet<DepartmentFunction>();
        FunctionTaskProfiles = new HashSet<FunctionTaskProfile>();
        PersonFunctions = new HashSet<PersonFunction>();
    }

    public int Id { get; set; }

    public string Name { get; set; }
    public float? ItemOrder { get; set; }

    public virtual Organisation Organisation { get; set; }
    public virtual ICollection<DepartmentFunction> DepartmentFunctions { get; set; }
    public virtual ICollection<FunctionTaskProfile> FunctionTaskProfiles { get; set; }
    public virtual ICollection<PersonFunction> PersonFunctions { get; set; }
    public DateTime? DeletedAt { get; set; }
}
</code>```

public class DepartmentFunction
{

    public int FunctionId { set; get; }
    public int DepartmentId { get; set; }

    public virtual Department Department { get; set; }
    public virtual Function Function { get; set; }
}
```
<p>When the departmentfunction on either entity is loaded, either with eager loading or lazy loading, every unique DepartmentFunction is listed twice. This problem occured after updating from EF core 5 to EF core 7. I have not changed anything with that update.</p>
<p>I have tried explicitly configuring the relation like this:</p>
<pre class="lang-cs prettyprint-override"><code>modelBuilder.Entity<DepartmentFunction>(entity =>
    {
        entity.HasKey(e => new {FunctieId = e.FunctionId, AfdelingId = e.DepartmentId})
            .HasName("PK__Afdeling__591131EC594F97A1");

        entity.HasOne(d => d.Department)
            .WithMany(p => p.DepartmentFunctions)
            .HasForeignKey(d => d.DepartmentId)
            .OnDelete(DeleteBehavior.ClientSetNull);

        entity.HasOne(d => d.Function)
            .WithMany(p => p.DepartmentFunctions)
            .HasForeignKey(d => d.FunctionId)
            .OnDelete(DeleteBehavior.ClientSetNull);

</code>```

I have also seen this solution, however, implementing this one would involve changing hundreds of references.

Body:
I have two entities, Function and Department with a Many to Many table in between.

public class Department
{
    public Department()
    {
        DepartmentFunctions = new HashSet<DepartmentFunction>();
        PersonFunctions = new HashSet<PersonFunction>();
    }

    public int Id { get; set; }

    public string Name { get; set; }

    public virtual ICollection<DepartmentFunction> DepartmentFunctions { get; set; }

    public DateTime? DeletedAt { get; set; }
}

public class Function
{
    public Function()
    {
        DepartmentFunctions = new HashSet<DepartmentFunction>();
        FunctionTaskProfiles = new HashSet<FunctionTaskProfile>();
        PersonFunctions = new HashSet<PersonFunction>();
    }

    public int Id { get; set; }

    public string Name { get; set; }
    public float? ItemOrder { get; set; }

    public virtual Organisation Organisation { get; set; }
    public virtual ICollection<DepartmentFunction> DepartmentFunctions { get; set; }
    public virtual ICollection<FunctionTaskProfile> FunctionTaskProfiles { get; set; }
    public virtual ICollection<PersonFunction> PersonFunctions { get; set; }
    public DateTime? DeletedAt { get; set; }
}

public class DepartmentFunction
{

    public int FunctionId { set; get; }
    public int DepartmentId { get; set; }

    public virtual Department Department { get; set; }
    public virtual Function Function { get; set; }
}

When the departmentfunction on either entity is loaded, either with eager loading or lazy loading, every unique DepartmentFunction is listed twice. This problem occured after updating from EF core 5 to EF core 7. I have not changed anything with that update.

I have tried explicitly configuring the relation like this:

modelBuilder.Entity<DepartmentFunction>(entity =>
    {
        entity.HasKey(e => new {FunctieId = e.FunctionId, AfdelingId = e.DepartmentId})
            .HasName("PK__Afdeling__591131EC594F97A1");

        entity.HasOne(d => d.Department)
            .WithMany(p => p.DepartmentFunctions)
            .HasForeignKey(d => d.DepartmentId)
            .OnDelete(DeleteBehavior.ClientSetNull);

        entity.HasOne(d => d.Function)
            .WithMany(p => p.DepartmentFunctions)
            .HasForeignKey(d => d.FunctionId)
            .OnDelete(DeleteBehavior.ClientSetNull);

I have also seen this solution, however, implementing this one would involve changing hundreds of references.


问:
generating a color ramp for normalized data
I'm using open3D and I want to add a colour ramp to a point cloud. I have no issue adding set colours to a point cloud given the following:

```<code>pcd.points = o3d.utility.Vector3dVector(np.asarray(datasets[['x', 'y', 'z']]))
pcd.colors = o3d.utility.Vector3dVector(np.asarray(colours[['red', 'green', 'blue']] / 65535))
o3d.visualization.draw_geometries([pcd])
</code>```

What I would like to do is, rather than having set rgb values, I want to add an array which is relative to the z-value.

Getting the z-value is easy, I have the following:

```<code>data_z
min_z
max_z
</code>```

I can normalise between 0 and 1

```<code>def normalise(data, min, max):
    return(data-min)/(max-min)

z_norm = normalise(data=z-value, min=min_z, max=max_z)
</code>```

So, I'm all set to add a gradient to the z_norm, but how do I:

map an rgb colour ramp to a 0.0-1.0 range

how do I set up a rgb colour ramp?

What is required is an array, equal to the length (size) of the point dataset with r g b values.

For 2 I would prefer to have a gradient between 2 rgb colors

Body:
I'm using open3D and I want to add a colour ramp to a point cloud. I have no issue adding set colours to a point cloud given the following:

pcd.points = o3d.utility.Vector3dVector(np.asarray(datasets[['x', 'y', 'z']]))
pcd.colors = o3d.utility.Vector3dVector(np.asarray(colours[['red', 'green', 'blue']] / 65535))
o3d.visualization.draw_geometries([pcd])

What I would like to do is, rather than having set rgb values, I want to add an array which is relative to the z-value.

Getting the z-value is easy, I have the following:

data_z
min_z
max_z

I can normalise between 0 and 1

def normalise(data, min, max):
    return(data-min)/(max-min)

z_norm = normalise(data=z-value, min=min_z, max=max_z)

So, I'm all set to add a gradient to the z_norm, but how do I:

map an rgb colour ramp to a 0.0-1.0 range

how do I set up a rgb colour ramp?

What is required is an array, equal to the length (size) of the point dataset with r g b values.

For 2 I would prefer to have a gradient between 2 rgb colors


问:
Android gradle keep rebuilding some certain files in externalNativeBuild
I'm using "Run 'app'" in Android Studio 4.2.1 to trigger building.

Even if I have nothing changed in my src files, the gradle task 'externalNativeBuild' rebuilds some certain files and takes 10+ seconds each time.
I get the output log:

```<code>> Task :xxx:externalNativeBuildDebug
Build xxx_module_arm64-v8a
ninja: Entering directory 'path/to/my/cmake/output/dir
[1/5] Building CXX object xxx/CMakeFiles/xxx.dir/source_file_a.cc.o
[2/5] Building CXX object xxx/CMakeFiles/xxx.dir/source_file_b.cc.o
[3/5] Linking CXX static library xxx\some_relative_archive.a
[4/5] Linking CXX static library xxx\some_other_relative_archive.a
[5/5] Linking CXX shared library ..\..\..\..\build\intermediates\cmake\debug\obj\arm64-v8a\some_relative_shared_object.so
Task externalNativeBuildDebug took 9596 ms, 9.596 s
</code>```

However，when I try running ninja -d explain and ninja -t deps to check the mtime of those files, it seems nothing has changed in the src file.

```<code># ninja -d explain, no work to do
ninja explain: output cmake_object_order_depends_target_xxx_viewmodel of phony edge with no inputs doesn't exist
ninja explain: output cmake_object_order_depends_target_xxx_model of phony edge with no inputs doesn't exist
ninja explain: output cmake_object_order_depends_target_xxx_business of phony edge with no inputs doesn't exist
ninja explain: output cmake_object_order_depends_target_xxx_plugin of phony edge with no inputs doesn't exist
ninja explain: output cmake_object_order_depends_target_xxx_util of phony edge with no inputs doesn't exist
ninja: no work to do.
</code>```
```<code># ninja -t deps, indicating the .o file is VALID
xxx/CMakeFiles/xxx.dir/source_file_a.cc.o: #deps 408, deps mtime 694440973 (VALID)
    ../../../../../../viewmodel/source_file_a.cc
    ../../../../../../viewmodel/source_file_a.h
    D:/UGit/WeCalendar/app_common/src/include/wemeet/include/app_header.h
    D:/UGit/WeCalendar/sdk/third_party/runtime/Android/include/wemeet/framework/platform/framework_header.h
    D:/Sdk/ndk/21.3.6528147/toolchains/llvm/prebuilt/windows-x86_64/sysroot/usr/include/c++/v1/stdlib.h
    D:/Sdk/ndk/21.3.6528147/toolchains/llvm/prebuilt/windows-x86_64/sysroot/usr/include/c++/v1/__config
    ……
</code>```

What else can I do to find out the problem?

Body:
I'm using "Run 'app'" in Android Studio 4.2.1 to trigger building.

Even if I have nothing changed in my src files, the gradle task 'externalNativeBuild' rebuilds some certain files and takes 10+ seconds each time.
I get the output log:

> Task :xxx:externalNativeBuildDebug
Build xxx_module_arm64-v8a
ninja: Entering directory 'path/to/my/cmake/output/dir
[1/5] Building CXX object xxx/CMakeFiles/xxx.dir/source_file_a.cc.o
[2/5] Building CXX object xxx/CMakeFiles/xxx.dir/source_file_b.cc.o
[3/5] Linking CXX static library xxx\some_relative_archive.a
[4/5] Linking CXX static library xxx\some_other_relative_archive.a
[5/5] Linking CXX shared library ..\..\..\..\build\intermediates\cmake\debug\obj\arm64-v8a\some_relative_shared_object.so
Task externalNativeBuildDebug took 9596 ms, 9.596 s

However，when I try running ninja -d explain and ninja -t deps to check the mtime of those files, it seems nothing has changed in the src file.

# ninja -d explain, no work to do
ninja explain: output cmake_object_order_depends_target_xxx_viewmodel of phony edge with no inputs doesn't exist
ninja explain: output cmake_object_order_depends_target_xxx_model of phony edge with no inputs doesn't exist
ninja explain: output cmake_object_order_depends_target_xxx_business of phony edge with no inputs doesn't exist
ninja explain: output cmake_object_order_depends_target_xxx_plugin of phony edge with no inputs doesn't exist
ninja explain: output cmake_object_order_depends_target_xxx_util of phony edge with no inputs doesn't exist
ninja: no work to do.

# ninja -t deps, indicating the .o file is VALID
xxx/CMakeFiles/xxx.dir/source_file_a.cc.o: #deps 408, deps mtime 694440973 (VALID)
    ../../../../../../viewmodel/source_file_a.cc
    ../../../../../../viewmodel/source_file_a.h
    D:/UGit/WeCalendar/app_common/src/include/wemeet/include/app_header.h
    D:/UGit/WeCalendar/sdk/third_party/runtime/Android/include/wemeet/framework/platform/framework_header.h
    D:/Sdk/ndk/21.3.6528147/toolchains/llvm/prebuilt/windows-x86_64/sysroot/usr/include/c++/v1/stdlib.h
    D:/Sdk/ndk/21.3.6528147/toolchains/llvm/prebuilt/windows-x86_64/sysroot/usr/include/c++/v1/__config
    ……

What else can I do to find out the problem?


问:
pred.zoib error, non-conformable arguments
I'm trying to fit a model with just one inflation and whereas the pred.zoib function worked when I included both one and zero inflation, it isn't running now that I've excluded the zero inflation - I get this error:

```<code>Error in x1[i, ] %*% b1 : non-conformable arguments
</code>```

The chaffinchdata is just a data frame with various bits of information, but importantly a detection probability column that has been adjusted to remove the zeros and replace them with 0.00001s, and a distance column that holds numeric values between 0 and 131.

When using pred.zoib before with both zero and one inflation, it worked fine:

```<code>fit.zoib.chaffinch4 <- zoib(Detection_probability ~ Distance | Distance | Distance | Distance , data = chaffinchdata)

chaffinchxnew <- data.frame(Distance = seq(0,150,0.1))
pred.chaff4 <- pred.zoib(fit.zoib.chaffinch4, chaffinchxnew)
dfchaff4 <- data.frame(Distance = seq(0,150,0.1),pred.chaff4$summary)
</code>```

So this all worked perfectly up until now. Then the below runs up until the pred.zoib stage.

```<code># now set the zero inflation to FALSE, to investigate just one inflation
nozeroinf <- birddata$Detection_probability
nozeroinf <- ifelse(nozeroinf == 0, 0.00001, nozeroinf)
birddata$nozeroinfs <- nozeroinf
chaffinchdata <- filter(birddata, Species == 'Chaffinch')
fit.zoib.chaff.oneinf <- zoib(nozeroinfs ~ Distance | Distance | Distance,
                              data = chaffinchdata, zero.inflation = F,
                              one.inflation = T)
</code>```
```<code>chaffxnew.oneinf <- data.frame(Distance = seq(0, 100, 0.1))
pred.chaff.oneinf <- pred.zoib(fit.zoib.chaff.oneinf, chaffxnew.oneinf)

</code>```

I've tried using the distance data straight from the chaffinchdata dataset instead of creating a sequence of my own, ie.

```<code>pred.zoib(fit.zoib.chaff.oneinf, data.frame(chaffinchdata$Distance))
</code>```

but that didn't work, nor did

```<code>pred.zoib(fit.zoib.chaff.oneinf, chaffinchdata)
</code>```

Any help on this would be greatly appreciated!

Body:
I'm trying to fit a model with just one inflation and whereas the pred.zoib function worked when I included both one and zero inflation, it isn't running now that I've excluded the zero inflation - I get this error:

Error in x1[i, ] %*% b1 : non-conformable arguments

The chaffinchdata is just a data frame with various bits of information, but importantly a detection probability column that has been adjusted to remove the zeros and replace them with 0.00001s, and a distance column that holds numeric values between 0 and 131.

When using pred.zoib before with both zero and one inflation, it worked fine:

fit.zoib.chaffinch4 <- zoib(Detection_probability ~ Distance | Distance | Distance | Distance , data = chaffinchdata)

chaffinchxnew <- data.frame(Distance = seq(0,150,0.1))
pred.chaff4 <- pred.zoib(fit.zoib.chaffinch4, chaffinchxnew)
dfchaff4 <- data.frame(Distance = seq(0,150,0.1),pred.chaff4$summary)

So this all worked perfectly up until now. Then the below runs up until the pred.zoib stage.

# now set the zero inflation to FALSE, to investigate just one inflation
nozeroinf <- birddata$Detection_probability
nozeroinf <- ifelse(nozeroinf == 0, 0.00001, nozeroinf)
birddata$nozeroinfs <- nozeroinf
chaffinchdata <- filter(birddata, Species == 'Chaffinch')
fit.zoib.chaff.oneinf <- zoib(nozeroinfs ~ Distance | Distance | Distance,
                              data = chaffinchdata, zero.inflation = F,
                              one.inflation = T)

chaffxnew.oneinf <- data.frame(Distance = seq(0, 100, 0.1))
pred.chaff.oneinf <- pred.zoib(fit.zoib.chaff.oneinf, chaffxnew.oneinf)

I've tried using the distance data straight from the chaffinchdata dataset instead of creating a sequence of my own, ie.

pred.zoib(fit.zoib.chaff.oneinf, data.frame(chaffinchdata$Distance))

but that didn't work, nor did

pred.zoib(fit.zoib.chaff.oneinf, chaffinchdata)

Any help on this would be greatly appreciated!


问:
How to change deckgl prop value(extruded) on button click?
I am plotting a hex layer in my app, and I want to modify extruded prop to true on click of a button. Is there a way to do it without plotting the layer again?
I have tried to replicate the required scenario in this fiddle

Below is the layer invocation code,

```<code>new H3HexagonLayer({
        id: 'h3-hexagon-layer',
        data: 'https://raw.githubusercontent.com/visgl/deck.gl-data/master/website/sf.h3cells.json',
        pickable: true,
        filled: true,
        extruded: false,
        elevationScale: 20,
        getLineColor: [0, 0, 0],
        getLineWidth: 1,
        getHexagon: d => d.hex,
        getFillColor: d => [255, (1 - d.count / 500) * 255, 0],
        getElevation: d => d.count
      }),
</code>```

Body:
I am plotting a hex layer in my app, and I want to modify extruded prop to true on click of a button. Is there a way to do it without plotting the layer again?
I have tried to replicate the required scenario in this fiddle

Below is the layer invocation code,

new H3HexagonLayer({
        id: 'h3-hexagon-layer',
        data: 'https://raw.githubusercontent.com/visgl/deck.gl-data/master/website/sf.h3cells.json',
        pickable: true,
        filled: true,
        extruded: false,
        elevationScale: 20,
        getLineColor: [0, 0, 0],
        getLineWidth: 1,
        getHexagon: d => d.hex,
        getFillColor: d => [255, (1 - d.count / 500) * 255, 0],
        getElevation: d => d.count
      }),


问:
Does cruise control works with Apache kafka 3.3.1
Getting 0 metrics collected from 0 brokers when kafka is upgraded from 2.8.1 to 3.3.1

Can Someone help here


问:
PDF or Excel the file created is always blank with 0 byte in sharepoint foundation 2010
I am using Visual Studio 2010 to develop report in sharepoint foundation 2010.

The report is developed in rdlc format.

I am able to display the result in the report viewer control. But when I export it to PDF or Excel, the file created is always blank with 0 byte.

Anyone face this problem before?

I had tried reinstall the Microsoft Report Viewer 2010 Redistributable Package. but the issue still exists.

ContentLicense: CC BY-SA 3.0


问:
Spring Data JPA @Query - creating new object from select
I create new object in select statement.

```<code>  @Query("""
      select new com.myPackage.AuthorDTO(
            a.id,
            a.name,
            booksIds)
            from Author a
            join a.books.id as booksIds
            """)
List<AuthorDTO> getAuthors();

</code>```

My record looks like this:

```<code>record AuthorDTO(Long id, String name, Set<Long> booksIds)
</code>```

I have an error:
illegal attempt to dereference collection.
How to solve it?

Body:
I create new object in select statement.

  @Query("""
      select new com.myPackage.AuthorDTO(
            a.id,
            a.name,
            booksIds)
            from Author a
            join a.books.id as booksIds
            """)
List<AuthorDTO> getAuthors();

My record looks like this:

record AuthorDTO(Long id, String name, Set<Long> booksIds)

I have an error:
illegal attempt to dereference collection.
How to solve it?


问:
Powershell Mail Message HTML format gets messed
I have built an HTML page with a table that uses rowspan when generating the HTML page and the view on the browser looks good. But when the mailmessage is attached and sent via Powershell. The format of the table body changes... any idea how to tackle this issue ?

enter image description here


问:
Telegram start new chat with HTTP requests, no BOT nor API
I want to start a new chat in Telegram with a Python script but I know with neither Telegram's BOT nor its API it is possibile.

If so, why can I start a new chat on Telegram Application (or Web) with someone?
I suppose Telegram client sends HTTP/s requests to achieve this. Is this feature possible to replicate with a Python script?


问:
Share my article with custom image in twitter with iframe
How can I submit a photo in this Twitter share iframe. This is my iframe:

```<code>src="https://platform.twitter.com/widgets/tweet_button.html?url=MyUrl&text=${encodeURIComponent(MyTitle)}&image%3D${encodeURIComponent(image)}" width="100" height="100" style="border: 0; overflow: hidden;"
</code>```

I tried many things but it doesn't work.

Body:
How can I submit a photo in this Twitter share iframe. This is my iframe:

src="https://platform.twitter.com/widgets/tweet_button.html?url=MyUrl&text=${encodeURIComponent(MyTitle)}&image%3D${encodeURIComponent(image)}" width="100" height="100" style="border: 0; overflow: hidden;"

I tried many things but it doesn't work.


问:
Webpack is not displaying my img but only alt attribute text
as a recruitment task I have to copy layout using HTML/CSS and Vanilla JS. I've got a starter pack as a webpack bundle and according to recruiter documentation i have to just install all dependencies using npm install. After creating some layout in css i had to use img tag and here my problem start. First I had error that I'm missing img-loader, so I installed it. Now i can't see image but only alt attribute text.

this is my webpack.config.js for file-loader and img-loader:

```<code>{
        test: /\.(jp?g|png|gif|svg)$/i,
        use: [
          {
            loader: "file-loader",
            options: {
              name: "img/[name].[ext]",
            },
          },
          {
            loader: "img-loader",
            options: {
              enabled: isProduction,
              gifscale: {
                interlaced: false,
              },
              mozjpeg: {
                progressive: true,
                arithmetic: false,
              },
              optipng: false,
              pngquant: {
                floyd: 0.5,
                speed: 2,
              },
              svgo: {
                plugins: [{ removeTitle: true }, { covertPathData: false }],
              },
            },
          },
        ],
      },
</code>```

here is file structure: file structure

I tried installing all dependencies step by step, changing config and I searched internet across. Unfortunately i couldn't find any solution.

Body:
as a recruitment task I have to copy layout using HTML/CSS and Vanilla JS. I've got a starter pack as a webpack bundle and according to recruiter documentation i have to just install all dependencies using npm install. After creating some layout in css i had to use img tag and here my problem start. First I had error that I'm missing img-loader, so I installed it. Now i can't see image but only alt attribute text.

this is my webpack.config.js for file-loader and img-loader:

{
        test: /\.(jp?g|png|gif|svg)$/i,
        use: [
          {
            loader: "file-loader",
            options: {
              name: "img/[name].[ext]",
            },
          },
          {
            loader: "img-loader",
            options: {
              enabled: isProduction,
              gifscale: {
                interlaced: false,
              },
              mozjpeg: {
                progressive: true,
                arithmetic: false,
              },
              optipng: false,
              pngquant: {
                floyd: 0.5,
                speed: 2,
              },
              svgo: {
                plugins: [{ removeTitle: true }, { covertPathData: false }],
              },
            },
          },
        ],
      },

here is file structure: file structure

I tried installing all dependencies step by step, changing config and I searched internet across. Unfortunately i couldn't find any solution.


问:
gem5 pci device CopyEngine
Hi I am trying to study PCI device in gem5 system. I am trying to use a ready device from gem5 /dev folder. However, I am not sure how to use the PCI device. Is there anyone can give me some hits about the software driver or hardware configuration. THANKS.

The file is in /gem5/src/dev/pci/CopyEngine.py

The version is 22.

thanks.

Liu

example or some hints

Title: gem5 pci device CopyEngine


问:
Logger level change for multi-tenant application as well as Package/Class logger level
here we have a use cases, we are working on a web application that will host multiple companies (tenant).

Currently, we have added company-specific log separation using MDC. It will separate the log files per company.

We want the flexibility to change the logger level at runtime for a company (tenant) specific along with package/class logger level change, as we are getting a bulk number of unwanted logs in those files.

Can anyone help me with this?

We have achieved it partially either for the Company or Package level.

· Company-specific logger level change using Turbo Filter.

· Package/Class level using Admin Centre (using Actuator endpoints)

Our question is if there is any way to change the logger level at run-time for a company-specific along with package/class.

Eg: As Our application is Hosted for two companies ACOMP & BCOMP.

Our requirement is

ACOMP should log at INFO as root logger level, also user can set few packages like com.test.samplepackage to DEBUG level.

Similarly,

BCOMP should log at DEBUG as root logger level, also user can set few packages like com.test.samplepackage to ERROR level.

Can anyone help me with this?


问:
Get matrix element through a vector of indices
I have posted a similar question here: Get matrix element through a vector of indices

However, my example and the data seemed to be too simplified, which did not solve my problem.

The main issue I'm having is that I have rows and columns named through numbers, which seems to complicate things a bit.

```<code>m <- matrix(1:25, ncol = 5, dimnames = list(c(1, 10, 100, 1000, 10000), c(1, 10, 100, 1000, 10000)))
v <- c(10,100)
</code>```

I'm basically trying to get the element m[10,100], in that case the value 12, by parsing the vector as coordinates:

```<code>m[v]
m[10,100]
</code>```

results in

```<code>> Error in m[10,100] : subscript out of bounds
</code>```

while

```<code>m[paste(v[1]), paste(v[2])]
m["10","100"]
</code>```

works.

How can is parse the vector into coordinates, without accessing each element individually (i.e. v[1], v[2])?

Body:
I have posted a similar question here: Get matrix element through a vector of indices

However, my example and the data seemed to be too simplified, which did not solve my problem.

The main issue I'm having is that I have rows and columns named through numbers, which seems to complicate things a bit.

m <- matrix(1:25, ncol = 5, dimnames = list(c(1, 10, 100, 1000, 10000), c(1, 10, 100, 1000, 10000)))
v <- c(10,100)

I'm basically trying to get the element m[10,100], in that case the value 12, by parsing the vector as coordinates:

m[v]
m[10,100]

results in

> Error in m[10,100] : subscript out of bounds

while

m[paste(v[1]), paste(v[2])]
m["10","100"]

works.

How can is parse the vector into coordinates, without accessing each element individually (i.e. v[1], v[2])?


问:
How to display Flash message in Nodejs
I am working with Nodejs (express js) and right now i am trying to display "flash message" but giving me error,How can i do this ? Here is my current code in controller

```<code>employeeController.deleteEmployee=function(req,res)
{
    var response={};
    var employeeId=req.params.employee_id;

    employeeModel.deleteEmployeeById(employeeId, function (result) {
        if (result == null) {
            response.status=0;
            response.data={};
            response.message="Something went wrong";
        } else {
            response.status=1;
            response.message="Employee deleted successfully";
        }
        res.send(JSON.stringify(response));
       })
}
</code>```

Here is my code in view file for display flash message

```<code>
<% if (response) { %>
                    <%= response.message %>
                <% } %>
</code>```

Title: How to display Flash message in Nodejs

Body:
I am working with Nodejs (express js) and right now i am trying to display "flash message" but giving me error,How can i do this ? Here is my current code in controller

employeeController.deleteEmployee=function(req,res)
{
    var response={};
    var employeeId=req.params.employee_id;

    employeeModel.deleteEmployeeById(employeeId, function (result) {
        if (result == null) {
            response.status=0;
            response.data={};
            response.message="Something went wrong";
        } else {
            response.status=1;
            response.message="Employee deleted successfully";
        }
        res.send(JSON.stringify(response));
       })
}

Here is my code in view file for display flash message

<% if (response) { %>
                    <%= response.message %>
                <% } %>


问:
Opening an browser + url in Mobicontrol Messagebox
I'm trying to open an url in browser in Mobicontrol Messagebox when pressing the YES dialog button.
It allows for some very basic javascript / Mobicontrol API scripting.
https://www.soti.net/mc/help/javascriptapi/en/index.html

But so far I had no succes, so was wondering if perhaps anyone knows a very basic javascript function to run an intent/scheme...or something like that.

So far variations of things I used was:

```<code>mobicontrol.message.createYesNoDialog('Would you like to open https://google.com ?')
.withCallback(onConfirm).show();

function onConfirm(result) {
if (result.isYesButton) {
mobicontrol.log.info('The Yes button was clicked');
OpenURL();
}
else if (result.isNoButton) {
mobicontrol.log.info('The No button was clicked');}
else if (result.isDismissed) {
mobicontrol.log.info('The dialog was dismissed');}
}

function OpenURL() {
mobicontrol.app.Activity('https://google.com#Intent;action=android.intent.action.VIEW;end');
}
</code>```

I've also seen a lot of examples of window.open but the API doesn't seem to understand that yet.

Body:
I'm trying to open an url in browser in Mobicontrol Messagebox when pressing the YES dialog button.
It allows for some very basic javascript / Mobicontrol API scripting.
https://www.soti.net/mc/help/javascriptapi/en/index.html

But so far I had no succes, so was wondering if perhaps anyone knows a very basic javascript function to run an intent/scheme...or something like that.

So far variations of things I used was:

mobicontrol.message.createYesNoDialog('Would you like to open https://google.com ?')
.withCallback(onConfirm).show();

function onConfirm(result) {
if (result.isYesButton) {
mobicontrol.log.info('The Yes button was clicked');
OpenURL();
}
else if (result.isNoButton) {
mobicontrol.log.info('The No button was clicked');}
else if (result.isDismissed) {
mobicontrol.log.info('The dialog was dismissed');}
}

function OpenURL() {
mobicontrol.app.Activity('https://google.com#Intent;action=android.intent.action.VIEW;end');
}

I've also seen a lot of examples of window.open but the API doesn't seem to understand that yet.


问:
After using vue3-notification in laravel sail and vite, I got "permission denied" on non-existing directory, what can I do?
I'm trying to add this package
https://github.com/kyvg/vue3-notification

I'm using vue3 with laravel sail and vite, after installing this package, my "sail npm run dev" command prints an error

```<code>error when starting dev server:
Error: EACCES: permission denied, unlink '/var/www/html/node_modules/.vite/deps/@inertiajs_inertia-vue3.js'
    at unlinkSync (node:fs:1780:3)
    at _unlinkSync (node:internal/fs/rimraf:214:14)
    ...
</code>```

I  tried to chmod that directory, but I don't even have directory "www" inside my "var" directory, so there is nothing to change.
What can I do to make it work?

My versions:

```<code>        "vite": "^4.0.0",
        "vue": "^3.2.41"
        "@kyvg/vue3-notification": "^2.7.0"
</code>```

Body:
I'm trying to add this package
https://github.com/kyvg/vue3-notification

I'm using vue3 with laravel sail and vite, after installing this package, my "sail npm run dev" command prints an error

error when starting dev server:
Error: EACCES: permission denied, unlink '/var/www/html/node_modules/.vite/deps/@inertiajs_inertia-vue3.js'
    at unlinkSync (node:fs:1780:3)
    at _unlinkSync (node:internal/fs/rimraf:214:14)
    ...

I  tried to chmod that directory, but I don't even have directory "www" inside my "var" directory, so there is nothing to change.
What can I do to make it work?

My versions:

        "vite": "^4.0.0",
        "vue": "^3.2.41"
        "@kyvg/vue3-notification": "^2.7.0"


问:
How to customize pcoGoDialog popup menu selection color in TcxPageControl?
I am using Delphi 10.4 with DevExpress VCL components 2020.2.8. I want to customize TcxPageControl's popup menu selection color. Example:

Create new Windows VCL Application - Delphi.

Drop a TcxPageControl on Form.

In cxPageControl1.Options set pcoGoDialog to True.

Add tabs until the "go dialog" dropdown button becomes visible.

My code for customizing it:

unit Unit2;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, dxBarBuiltInMenu, cxGraphics,
  cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxSkinsCore, dxSkinBasic,
  cxPC, cxPCPainters, cxPCPaintersFactory;

const
  MyStyleId = 100;

type
  TForm2 = class(TForm)
    cxPageControl1: TcxPageControl;
    cxTabSheet1: TcxTabSheet;
    cxTabSheet2: TcxTabSheet;
    cxTabSheet3: TcxTabSheet;
    cxTabSheet4: TcxTabSheet;
    cxTabSheet5: TcxTabSheet;
    cxTabSheet6: TcxTabSheet;
    cxTabSheet7: TcxTabSheet;
    procedure FormCreate(Sender: TObject);
    procedure cxPageControl1DrawTabEx(AControl: TcxCustomTabControl;
      ATab: TcxTab; Font: TFont);
  end;

  TMyPCPainter = class(TcxPCUltraFlatPainter)
  private
    class function GetStyleID: TcxPCStyleID; static;
  protected
    //function GetTabBodyColor(TabVisibleIndex: Integer): TColor; override;
    function GetTabsRowColor: TColor; override;
    function GetTabCorrection(ATabVisibleIndex: Integer): TRect; override;
    function GetButtonColor(AButtonState: TcxPCNavigatorButtonState): TColor; override;  public
  end;

var
  Form2: TForm2;

implementation

{$R *.dfm}

{ TMyPCPainter }

function TMyPCPainter.GetButtonColor(
  AButtonState: TcxPCNavigatorButtonState): TColor;
begin
  Result:=clGray;
end;

class function TMyPCPainter.GetStyleID: TcxPCStyleID;
begin
  Result := MyStyleId;
end;

function TMyPCPainter.GetTabCorrection(ATabVisibleIndex: Integer): TRect;
begin
// add space btn tabs
  Result := Rect(5, -1, 0,2);
end;

function TMyPCPainter.GetTabsRowColor: TColor;
begin
  Result:=clGray;
end;

procedure TForm2.cxPageControl1DrawTabEx(AControl: TcxCustomTabControl;
  ATab: TcxTab; Font: TFont);
begin
  if ATab.IsMainTab then begin
    ATab.Color := clWhite;
    Font.Color := clBlack;
  end
  else begin
    ATab.Color := clBlack;
    Font.Color := clWhite;
  end;
end;

procedure TForm2.FormCreate(Sender: TObject);
begin
  cxPageControl1.Style := MyStyleId;
  cxPageControl1.OnDrawTabEx:=cxPageControl1DrawTabEx;
end;

initialization
  RegisterPCPainterClass(TMyPCPainter);

finalization
  UnregisterPCPainterClass(TMyPCPainter);

end.
```

Run the application. Click on the "go dialog" drop down button. When you try to select a popup menu item it is highlighted in blue. Like shown in below picture:

How to change the go dialog popup menu selection color?

Body:
I am using Delphi 10.4 with DevExpress VCL components 2020.2.8. I want to customize TcxPageControl's popup menu selection color. Example:

Create new Windows VCL Application - Delphi.

Drop a TcxPageControl on Form.

In cxPageControl1.Options set pcoGoDialog to True.

Add tabs until the "go dialog" dropdown button becomes visible.

My code for customizing it:

unit Unit2;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, dxBarBuiltInMenu, cxGraphics,
  cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxSkinsCore, dxSkinBasic,
  cxPC, cxPCPainters, cxPCPaintersFactory;

const
  MyStyleId = 100;

type
  TForm2 = class(TForm)
    cxPageControl1: TcxPageControl;
    cxTabSheet1: TcxTabSheet;
    cxTabSheet2: TcxTabSheet;
    cxTabSheet3: TcxTabSheet;
    cxTabSheet4: TcxTabSheet;
    cxTabSheet5: TcxTabSheet;
    cxTabSheet6: TcxTabSheet;
    cxTabSheet7: TcxTabSheet;
    procedure FormCreate(Sender: TObject);
    procedure cxPageControl1DrawTabEx(AControl: TcxCustomTabControl;
      ATab: TcxTab; Font: TFont);
  end;

  TMyPCPainter = class(TcxPCUltraFlatPainter)
  private
    class function GetStyleID: TcxPCStyleID; static;
  protected
    //function GetTabBodyColor(TabVisibleIndex: Integer): TColor; override;
    function GetTabsRowColor: TColor; override;
    function GetTabCorrection(ATabVisibleIndex: Integer): TRect; override;
    function GetButtonColor(AButtonState: TcxPCNavigatorButtonState): TColor; override;  public
  end;

var
  Form2: TForm2;

implementation

{$R *.dfm}

{ TMyPCPainter }

function TMyPCPainter.GetButtonColor(
  AButtonState: TcxPCNavigatorButtonState): TColor;
begin
  Result:=clGray;
end;

class function TMyPCPainter.GetStyleID: TcxPCStyleID;
begin
  Result := MyStyleId;
end;

function TMyPCPainter.GetTabCorrection(ATabVisibleIndex: Integer): TRect;
begin
// add space btn tabs
  Result := Rect(5, -1, 0,2);
end;

function TMyPCPainter.GetTabsRowColor: TColor;
begin
  Result:=clGray;
end;

procedure TForm2.cxPageControl1DrawTabEx(AControl: TcxCustomTabControl;
  ATab: TcxTab; Font: TFont);
begin
  if ATab.IsMainTab then begin
    ATab.Color := clWhite;
    Font.Color := clBlack;
  end
  else begin
    ATab.Color := clBlack;
    Font.Color := clWhite;
  end;
end;

procedure TForm2.FormCreate(Sender: TObject);
begin
  cxPageControl1.Style := MyStyleId;
  cxPageControl1.OnDrawTabEx:=cxPageControl1DrawTabEx;
end;

initialization
  RegisterPCPainterClass(TMyPCPainter);

finalization
  UnregisterPCPainterClass(TMyPCPainter);

end.

Run the application. Click on the "go dialog" drop down button. When you try to select a popup menu item it is highlighted in blue. Like shown in below picture:

How to change the go dialog popup menu selection color?


问:
How do I subtract an R,G,B of 25 at all the pixels where this watermark appears in ffmpeg?

I have a video with a watermark on it for the full duration.

I have figured out that I need to subtract R,G,B of 25 from those pixels where the water mark appears

How can I do this with ffmpeg?


问:
ASP.Net Core C# - Identity Two factor authentication, Redirect to home page after QR code authentication instead of Login Page first time
I am using a QR code MFA Authentication to log in to the user using Identity. When User first time login it goes to the MFA QR code screen. I scan that QR code using an App(google/Microsoft Authenticator). After putting the 6-digit value in the text field and it updates the TwoFactorEnabled variable in DB and makes it true and after that it redirects to the login page again.
My requirement is that instead of the Login page it goes to the dashboard</p>


问:
Trino with https
I am new to Trino, I have installed Trino using helm chart https://trinodb.github.io/charts
but I am not able to get it working on https,

Details of my cluster

I have a kubeadm cluster deployed on barebones EC2, also have a Ha Proxy installed thats managing the ingress of other services, I have added ingress for the same.

Is there some config I need to pass to it, I tried to read the documents but had tough time understanding those.

Tried

Added entries in haproxy
generated the certs
created ingress for trino

Expecting

trino to open on a https secure connection

Title: Trino with https


问:
dataTable tableedit error, adding a new column while searching in jQuery
I'm developing a stock manager webapp for a company.

I have this page where the administrator can edit and delete products that they added in a table (dataTable), I managed to make this possible by using this tutorial:
https://www.webslesson.info/2017/05/live-table-data-edit-delete-using-tabledit-plugin-in-php.html

Everything works fine but I had this issue where the 2 edit and delete buttons weren't showed on other pages of my table except from the 1st, I managed to resolve this issue with attached code

Everything right now works fine but i have a huge graphic problem. While i'm searching, every time I tap a letter or a backspace, the last column as you can see from the attachment is cloning itself every time.

Error of multiple columns

I've already tried to debug the search method but I don't think it's related to that... it's a standard method.

Do you think it can possibly be a problem related to the fact that the last column with the 2 button (edit and delete) is automatically added with a js of the library extension I'm using and it's not hardcoded? so every time I redraw the table it is like an external element to redraw?

var table = $('#dataTable').DataTable();

// Document ready
$(function() {
  editTable();
});
// Assuming "table" is the variable name of your datatable
table.on('draw', editTable);

function editTable() {
  $('#dataTable').Tabledit({
    url: 'updateDB.php',
    columns: {
      identifier: [0, "id"],
      editable: [
        [1, 'name'],
        [4, 'quantity'],
        [5, 'threshold'],
      ]
    },
    restoreButton: false,
    onSuccess: function(data, textStatus, jqXHR) {
      if (data.action == "delete") {
        document.getElementById(data.id).remove();
      }
    }
  });

};
```