问:
VS Code default JS formatter not removing empty spaces
How to make VS Code default JS formatter to remove empty white spaces?

I want the following code:

```<code>function Greetings()
{
  return <h1>Hello World</h1>;

}

</code>```

to look like:

```<code>function Greetings()
{
  return <h1>Hello World</h1>;
}
</code>```

答:
Could you try to install the extension of Prettier - Code formatter, and set it as the default formatter of javascript?</p>
```<code>  "[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
</code>```

Body:
How to make VS Code default JS formatter to remove empty white spaces?

I want the following code:

function Greetings()
{
  return
Hello World
;

}

to look like:

function Greetings()
{
  return
Hello World
;
}

Body:
Could you try to install the extension of Prettier - Code formatter, and set it as the default formatter of javascript?

  "[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },


来源: stackexchange

问:
How can I find out the pid of a running equinox instance, is there a pid file?
How can I find out the pid of a running equinox instance, is there a pid file somewhere or is it configurable where it places a pid file?

UPDATE: to make it clear, I have a bunch of instances running, and they are configured roughly the same, so any user only looking for equinox will not know which instance is which

答:
Just execute the following command from CLI:

```<code>ps aux | grep equinox
</code>```

[EDIT]
Does equinox bind to some port?
If so, for multiple instances you can recognize the one you are interested in basis on port to which it is bound:

```<code>sudo netstat -npa |grep equinox
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Just execute the following command from CLI:

ps aux | grep equinox

[EDIT]
Does equinox bind to some port?
If so, for multiple instances you can recognize the one you are interested in basis on port to which it is bound:

sudo netstat -npa |grep equinox


问:
Reference Queue is Always Empty
I am trying to clean a native resource when it is not accessible anymore. That resource provides a method to clean allocated resources (memory, threads etc.). To achieve this, I used Phantom Reference.

That resource should be created asynchronously when a new configuration provided by library user.

The problem is, ReferenceQueue is always empty. I don't reference the native resource outside of the files. Even in this situation, poll() method returns null. So I can't clean the resource and it causes to memory leak. How can I avoid this situation?

You can find the example code below. I used JDK 8.

```<code>// Engine.java

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Native source
 */
public class Engine {
    private static final Map<Long, byte[]> nativeResource = new HashMap<>();
    private static final AtomicLong counter = new AtomicLong(0);

    private final long id;

    public Engine() {
        // Simple memory leak implementation
        id = counter.incrementAndGet();
        nativeResource.put(id, new byte[1024 * 1024 * 10]);
    }

    public void close() {
        nativeResource.remove(id);
        System.out.println("Engine destroyed.");
    }
}
</code>```
```<code>// EngineHolder.java

/**
 * Native source wrapper.
 */
public class EngineHolder {
    private final Engine engine;
    private final String version;

    EngineHolder(Engine engine, String version) {
        this.engine = engine;
        this.version = version;
    }

    public Engine getEngine() {
        return engine;
    }

    public String getVersion() {
        return version;
    }
}
</code>```
```<code>import java.util.UUID;

// EngineConfiguration.java

/**
 * Native source configuration.
 */
public class EngineConfiguration {
    private final String version;

    public EngineConfiguration() {
        // Assign a new version number for configuration.
        this.version = UUID.randomUUID().toString();
    }

    public String getVersion() {
        return version;
    }
}
</code>```
```<code>// SecuredRunnable.java

public class SecuredRunnable implements Runnable {
    private final Runnable runnable;

    public SecuredRunnable(Runnable runnable) {
        this.runnable = runnable;
    }

    @Override
    public void run() {
        try {
            this.runnable.run();
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}
</code>```
```<code>import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

// EngineService.java

public class EngineService {
    private static EngineService INSTANCE = null;
    private static final Object INSTANCE_LOCK = new Object();

    private final ReferenceQueue<Engine> engineRefQueue = new ReferenceQueue<>();
    private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

    private volatile EngineConfiguration engineConfiguration;

    private volatile EngineHolder engineHolder;

    private EngineService() {
        engineConfiguration = new EngineConfiguration();

        EngineRunnable backgroundDaemon = new EngineRunnable();
        executor.scheduleWithFixedDelay(new SecuredRunnable(backgroundDaemon), 0, 5, TimeUnit.SECONDS);
    }

    public Engine getEngine() {
        return engineHolder != null ? engineHolder.getEngine() : null;
    }

    public void setEngineConfiguration(EngineConfiguration configuration) {
        this.engineConfiguration = configuration;
        // Dispatch job.
        EngineRunnable backgroundDaemon = new EngineRunnable();
        executor.submit(new SecuredRunnable(backgroundDaemon));
    }

    public static EngineService getInstance() {
        synchronized (INSTANCE_LOCK) {
            if (INSTANCE == null) {
                INSTANCE = new EngineService();
            }

            return INSTANCE;
        }
    }

    private static class EngineRunnable implements Runnable {
        @Override
        public void run() {
            EngineHolder engineHolder = INSTANCE.engineHolder;
            EngineConfiguration engineConfiguration = INSTANCE.engineConfiguration;

            // If there is no created engine or the previous engine is outdated, create a new engine.
            if (engineHolder == null || !engineHolder.getVersion().equals(engineConfiguration.getVersion())) {
                Engine engine = new Engine();
                INSTANCE.engineHolder = new EngineHolder(engine, engineConfiguration.getVersion());

                new PhantomReference<>(engine, INSTANCE.engineRefQueue);
                System.out.println("Engine created for version " + engineConfiguration.getVersion());
            }

            Reference<? extends Engine> referenceFromQueue;

            // Clean inaccessible native resources.
            while ((referenceFromQueue = INSTANCE.engineRefQueue.poll()) != null) {
                // This block doesn't work at all.
                System.out.println("Engine will be destroyed.");
                referenceFromQueue.get().close();
                referenceFromQueue.clear();
            }
        }
    }
}
</code>```
```<code>// Application.java

public class Application {
    public static void main(String[] args) throws InterruptedException {
        EngineService engineService = EngineService.getInstance();

        while (true) {
            System.gc();
            engineService.setEngineConfiguration(new EngineConfiguration());
            Thread.sleep(100);
        }
    }
}
</code>```

答:
From the java.lang.ref package documentation:

The relationship between a registered reference object and its queue is one-sided. That is, a queue does not keep track of the references that are registered with it. If a registered reference becomes unreachable itself, then it will never be enqueued. It is the responsibility of the program using reference objects to ensure that the objects remain reachable for as long as the program is interested in their referents.

This is directly violated by your program by doing

new PhantomReference<>(engine, INSTANCE.engineRefQueue);
```

without keeping a reference to the PhantomReference. Therefore, as the queue doesn’t maintain a reference to the PhantomReference either, the PhantomReference itself is unreachable and simply gets garbage collected.

ContentLicense: CC BY-SA 4.0

Title: Reference Queue is Always Empty

Body:
I am trying to clean a native resource when it is not accessible anymore. That resource provides a method to clean allocated resources (memory, threads etc.). To achieve this, I used Phantom Reference.

That resource should be created asynchronously when a new configuration provided by library user.

The problem is, ReferenceQueue is always empty. I don't reference the native resource outside of the files. Even in this situation, poll() method returns null. So I can't clean the resource and it causes to memory leak. How can I avoid this situation?

You can find the example code below. I used JDK 8.

// Engine.java

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Native source
 */
public class Engine {
    private static final Map<Long, byte[]> nativeResource = new HashMap<>();
    private static final AtomicLong counter = new AtomicLong(0);

    private final long id;

    public Engine() {
        // Simple memory leak implementation
        id = counter.incrementAndGet();
        nativeResource.put(id, new byte[1024 * 1024 * 10]);
    }

    public void close() {
        nativeResource.remove(id);
        System.out.println("Engine destroyed.");
    }
}

// EngineHolder.java

/**
 * Native source wrapper.
 */
public class EngineHolder {
    private final Engine engine;
    private final String version;

    EngineHolder(Engine engine, String version) {
        this.engine = engine;
        this.version = version;
    }

    public Engine getEngine() {
        return engine;
    }

    public String getVersion() {
        return version;
    }
}

import java.util.UUID;

// EngineConfiguration.java

/**
 * Native source configuration.
 */
public class EngineConfiguration {
    private final String version;

    public EngineConfiguration() {
        // Assign a new version number for configuration.
        this.version = UUID.randomUUID().toString();
    }

    public String getVersion() {
        return version;
    }
}

// SecuredRunnable.java

public class SecuredRunnable implements Runnable {
    private final Runnable runnable;

    public SecuredRunnable(Runnable runnable) {
        this.runnable = runnable;
    }

    @Override
    public void run() {
        try {
            this.runnable.run();
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}

import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

// EngineService.java

public class EngineService {
    private static EngineService INSTANCE = null;
    private static final Object INSTANCE_LOCK = new Object();

    private final ReferenceQueue<Engine> engineRefQueue = new ReferenceQueue<>();
    private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

    private volatile EngineConfiguration engineConfiguration;

    private volatile EngineHolder engineHolder;

    private EngineService() {
        engineConfiguration = new EngineConfiguration();

        EngineRunnable backgroundDaemon = new EngineRunnable();
        executor.scheduleWithFixedDelay(new SecuredRunnable(backgroundDaemon), 0, 5, TimeUnit.SECONDS);
    }

    public Engine getEngine() {
        return engineHolder != null ? engineHolder.getEngine() : null;
    }

    public void setEngineConfiguration(EngineConfiguration configuration) {
        this.engineConfiguration = configuration;
        // Dispatch job.
        EngineRunnable backgroundDaemon = new EngineRunnable();
        executor.submit(new SecuredRunnable(backgroundDaemon));
    }

    public static EngineService getInstance() {
        synchronized (INSTANCE_LOCK) {
            if (INSTANCE == null) {
                INSTANCE = new EngineService();
            }

            return INSTANCE;
        }
    }

    private static class EngineRunnable implements Runnable {
        @Override
        public void run() {
            EngineHolder engineHolder = INSTANCE.engineHolder;
            EngineConfiguration engineConfiguration = INSTANCE.engineConfiguration;

            // If there is no created engine or the previous engine is outdated, create a new engine.
            if (engineHolder == null || !engineHolder.getVersion().equals(engineConfiguration.getVersion())) {
                Engine engine = new Engine();
                INSTANCE.engineHolder = new EngineHolder(engine, engineConfiguration.getVersion());

                new PhantomReference<>(engine, INSTANCE.engineRefQueue);
                System.out.println("Engine created for version " + engineConfiguration.getVersion());
            }

            Reference<? extends Engine> referenceFromQueue;

            // Clean inaccessible native resources.
            while ((referenceFromQueue = INSTANCE.engineRefQueue.poll()) != null) {
                // This block doesn't work at all.
                System.out.println("Engine will be destroyed.");
                referenceFromQueue.get().close();
                referenceFromQueue.clear();
            }
        }
    }
}

// Application.java

public class Application {
    public static void main(String[] args) throws InterruptedException {
        EngineService engineService = EngineService.getInstance();

        while (true) {
            System.gc();
            engineService.setEngineConfiguration(new EngineConfiguration());
            Thread.sleep(100);
        }
    }
}

Body:
From the java.lang.ref package documentation:

The relationship between a registered reference object and its queue is one-sided. That is, a queue does not keep track of the references that are registered with it. If a registered reference becomes unreachable itself, then it will never be enqueued. It is the responsibility of the program using reference objects to ensure that the objects remain reachable for as long as the program is interested in their referents.

This is directly violated by your program by doing

new PhantomReference<>(engine, INSTANCE.engineRefQueue);

without keeping a reference to the PhantomReference. Therefore, as the queue doesn’t maintain a reference to the PhantomReference either, the PhantomReference itself is unreachable and simply gets garbage collected.


问:
How to remove outline for Material row header with MatSort in Angular 9?
I got an issue after implementing MatSort to my Material table. It's showing outline for the header column name when click on it to sort

Is it possible to disable it? If possible, Please help me on how to do it.

I implemented Material table with sorting as shown in the below link:
https://material.angular.io/components/table/overview#sorting

答:
I had to use the following:</p>
```<code>::ng-deep .mat-sort-header-button {
    outline: none !important;
}
</code>```

Body:
I had to use the following:

::ng-deep .mat-sort-header-button {
    outline: none !important;
}


问:
How can I save the output of a convolution layer with and without a dilation rate as images
I want to save a image file to see about difference using convolution layer with dilation rate and without that.

Of course I can search images about that, but I want to see difference of my dataset.

Is there a special function? or Can I make code with opencv like a keras layers?

I am using
python 3.8 and
tf 2.4.0

答:
You can use matplotlib and a custom Callback to save the feature maps of a CNN layer after every epoch. Here is a working example:

import tensorflow as tf
import pathlib
import matplotlib.pyplot as plt

dataset_url = "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz"
data_dir = tf.keras.utils.get_file('flower_photos', origin=dataset_url, untar=True)
data_dir = pathlib.Path(data_dir)

batch_size = 32

normalized_ds = tf.keras.utils.image_dataset_from_directory(
  data_dir,
  validation_split=0.2,
  subset="training",
  seed=123,
  image_size=(180, 180),
  batch_size=batch_size)

model = tf.keras.Sequential([
  tf.keras.layers.Rescaling(1./255, input_shape=(180, 180, 3)),
  tf.keras.layers.Conv2D(16, 3, padding='same', activation='relu', dilation_rate=(3, 3)),
  tf.keras.layers.MaxPooling2D(),
  tf.keras.layers.Conv2D(32, 3, padding='same', activation='relu'),
  tf.keras.layers.MaxPooling2D(),
  tf.keras.layers.Conv2D(64, 3, padding='same', activation='relu'),
  tf.keras.layers.MaxPooling2D(),
  tf.keras.layers.Flatten(),
  tf.keras.layers.Dense(128, activation='relu'),
  tf.keras.layers.Dense(5)
])

class CustomCallback(tf.keras.callbacks.Callback):
   def __init__(self, data, sample_size):
        self.data = data
        self.sample_size = sample_size
   def on_epoch_end(self, epoch, logs=None):
        images, _ = next(iter(self.data.take(self.sample_size)))
        image = tf.expand_dims(images[0], axis=0)
        output = first_cnn_layer(image)
        plt.imsave('image{}.png'.format(epoch), images[0].numpy()/255)
        ix = 1
        for _ in range(4):
          for _ in range(4):
            ax = plt.subplot(4, 4, ix)
            ax.set_xticks([])
            ax.set_yticks([])
            plt.imshow(output[0, :, :, ix-1], cmap='gray')
            ix += 1
        plt.savefig('filters{}.png'.format(epoch))

first_cnn_layer = model.layers[1]
model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

history = model.fit(normalized_ds, epochs=2, callbacks=[CustomCallback(normalized_ds, 1)])
```

With dilation_rate=(1, 1) at epoch 1:

Original image

Feature maps

With dilation_rate=(3, 3) at epoch 1:

Original image

Feature maps

Body:
You can use matplotlib and a custom Callback to save the feature maps of a CNN layer after every epoch. Here is a working example:

import tensorflow as tf
import pathlib
import matplotlib.pyplot as plt

dataset_url = "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz"
data_dir = tf.keras.utils.get_file('flower_photos', origin=dataset_url, untar=True)
data_dir = pathlib.Path(data_dir)

batch_size = 32

normalized_ds = tf.keras.utils.image_dataset_from_directory(
  data_dir,
  validation_split=0.2,
  subset="training",
  seed=123,
  image_size=(180, 180),
  batch_size=batch_size)

model = tf.keras.Sequential([
  tf.keras.layers.Rescaling(1./255, input_shape=(180, 180, 3)),
  tf.keras.layers.Conv2D(16, 3, padding='same', activation='relu', dilation_rate=(3, 3)),
  tf.keras.layers.MaxPooling2D(),
  tf.keras.layers.Conv2D(32, 3, padding='same', activation='relu'),
  tf.keras.layers.MaxPooling2D(),
  tf.keras.layers.Conv2D(64, 3, padding='same', activation='relu'),
  tf.keras.layers.MaxPooling2D(),
  tf.keras.layers.Flatten(),
  tf.keras.layers.Dense(128, activation='relu'),
  tf.keras.layers.Dense(5)
])

class CustomCallback(tf.keras.callbacks.Callback):
   def __init__(self, data, sample_size):
        self.data = data
        self.sample_size = sample_size
   def on_epoch_end(self, epoch, logs=None):
        images, _ = next(iter(self.data.take(self.sample_size)))
        image = tf.expand_dims(images[0], axis=0)
        output = first_cnn_layer(image)
        plt.imsave('image{}.png'.format(epoch), images[0].numpy()/255)
        ix = 1
        for _ in range(4):
          for _ in range(4):
            ax = plt.subplot(4, 4, ix)
            ax.set_xticks([])
            ax.set_yticks([])
            plt.imshow(output[0, :, :, ix-1], cmap='gray')
            ix += 1
        plt.savefig('filters{}.png'.format(epoch))

first_cnn_layer = model.layers[1]
model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

history = model.fit(normalized_ds, epochs=2, callbacks=[CustomCallback(normalized_ds, 1)])

With dilation_rate=(1, 1) at epoch 1:

Original image

Feature maps

With dilation_rate=(3, 3) at epoch 1:

Original image

Feature maps


问:
While working in angular 13, for "HTMLCanvasElement" and "CanvasRenderingContext2D" I am getting "Object is possibly undefined"
While working in angular 13, for "HTMLCanvasElement" and "CanvasRenderingContext2D" I am getting

Object is possibly undefined

Code snippet:

```<code>canvasEl: HTMLCanvasElement | undefined ;

private plot: CanvasRenderingContext2D | undefined;

....
....

//following all lines giving error of "Object is possibly undefined"
this.canvasEl = this.canvas.nativeElement;
this.plot=this.canvasEl.getContext("2d");
this.canvasEl.width = this.width;
this.canvasEl.height = this.height;
</code>```

How to resolve these errors? How I can declare variables to solve these errors?

答:
If you are sure that your element is available and never undefined just add a ! after your variable:</p>
```<code>canvasEl!: HTMLCanvasElement
private plot!: CanvasRenderingContext2D;
</code>```

Body:
While working in angular 13, for "HTMLCanvasElement" and "CanvasRenderingContext2D" I am getting

Object is possibly undefined

Code snippet:

canvasEl: HTMLCanvasElement | undefined ;

private plot: CanvasRenderingContext2D | undefined;

....
....

//following all lines giving error of "Object is possibly undefined"
this.canvasEl = this.canvas.nativeElement;
this.plot=this.canvasEl.getContext("2d");
this.canvasEl.width = this.width;
this.canvasEl.height = this.height;

How to resolve these errors? How I can declare variables to solve these errors?

Body:
If you are sure that your element is available and never undefined just add a ! after your variable:

canvasEl!: HTMLCanvasElement
private plot!: CanvasRenderingContext2D;


问:
Window form does not close
Hey guys i am new to the Windows application.

I have a form on which Login button click event i have shown to other Forms. Example like i have a login page after user authentication other two Forms shown. But i want after authentication of user Login Form should be close, But others two remain open.

Following is code, my Login Form name is LogIn.cs

```<code>private void btnLogIn_Click(object sender, EventArgs e)
{
    if(ValidateUser())
    {
       //Form1

        DetailForm form = new DetailForm(txtUserName.Text.ToString());
        form.Show();

        //Form2

        Progressbar progress = new Progressbar();
        progress.Show();
    }
}
</code>```

please write some code

答: There is a "Close" method on every form you can use.</p>

Title: Window form does not close

Body:
Hey guys i am new to the Windows application.

I have a form on which Login button click event i have shown to other Forms. Example like i have a login page after user authentication other two Forms shown. But i want after authentication of user Login Form should be close, But others two remain open.

Following is code, my Login Form name is LogIn.cs

private void btnLogIn_Click(object sender, EventArgs e)
{
    if(ValidateUser())
    {
       //Form1

        DetailForm form = new DetailForm(txtUserName.Text.ToString());
        form.Show();

        //Form2

        Progressbar progress = new Progressbar();
        progress.Show();
    }
}

please write some code


问:
react exclude config files from build
In my react app I have 4 separate config files for 4 different environments to run in, test for unit tests, dev use while developing, staging for the staging environment (almost identical to prod) and prod for the actual customer facing production server.

One setting of those config files is the api address (127.0.0.1:7777 for dev, api.staging-app.com for staging, api.app.com for prod.

React will use the config file corresponding to the REACT_APP_NODE_ENV variable. But I have recently noticed that react will always bundle ever config file to be discovered by nosy users.

Since I would like to keep the location of the staging server secret (its still protected, even if it were discovered),  I would like to exclude all the unused config files from the webpack build. Is there a way to do this?

答:
I don't know why this works but I did it like this:

```<code>if(process.env.REACT_APP_NODE_ENV==="prod"){
    var config=require("../config_prod.json")
}
if(process.env.REACT_APP_NODE_ENV==="dev"){
    var config=require("../config_dev.json")
}
if(process.env.REACT_APP_NODE_ENV==="test"){
    var config=require("../config_test.json")
}
else if(process.env.REACT_APP_NODE_ENV==="staging"){
    var config=require("../config_staging.json")
}

export default config;
</code>```

this way any unused config file won't end up in the production bundle. This only works if process.env is in the if clause, if it is for example Math.random()<0.5, it will bundle everything

Title: react exclude config files from build

Body:
I don't know why this works but I did it like this:

if(process.env.REACT_APP_NODE_ENV==="prod"){
    var config=require("../config_prod.json")
}
if(process.env.REACT_APP_NODE_ENV==="dev"){
    var config=require("../config_dev.json")
}
if(process.env.REACT_APP_NODE_ENV==="test"){
    var config=require("../config_test.json")
}
else if(process.env.REACT_APP_NODE_ENV==="staging"){
    var config=require("../config_staging.json")
}

export default config;

this way any unused config file won't end up in the production bundle. This only works if process.env is in the if clause, if it is for example Math.random()<0.5, it will bundle everything


问:
Can't get Table Data from Site After the Page Loads
I'm trying to obtain the 2nd table on the following website. I've tried BS4, Pandas, and now selenium, but I can't obtain the table for the life of me.

The table data doesn't load until after the page comes up.

There is a dictionary on the 'view source' page with the info, but its seems like every element on that page is 'line-content', so its makes it difficult to obtain only the desired table info.

What is the best way to collect the table data?

```<code>from ast import Return
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as ec
import time

path = 'C:\Program Files (x86)\chromedriver.exe'

driver = webdriver.Chrome(path)

driver.get('https://www.linestarapp.com/Ownership/Sport/NFL/Site/DraftKings/PID/295')

time.sleep(5)
driver.maximize_window()

time.sleep(5)

players = driver.find_elements_by_class_name('playerRow').text
print(players)
</code>```

Body:
I'm trying to obtain the 2nd table on the following website. I've tried BS4, Pandas, and now selenium, but I can't obtain the table for the life of me.

The table data doesn't load until after the page comes up.

There is a dictionary on the 'view source' page with the info, but its seems like every element on that page is 'line-content', so its makes it difficult to obtain only the desired table info.

What is the best way to collect the table data?

from ast import Return
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as ec
import time

path = 'C:\Program Files (x86)\chromedriver.exe'

driver = webdriver.Chrome(path)

driver.get('https://www.linestarapp.com/Ownership/Sport/NFL/Site/DraftKings/PID/295')

time.sleep(5)
driver.maximize_window()

time.sleep(5)

players = driver.find_elements_by_class_name('playerRow').text
print(players)

Body:
Just an alternative to Selenium, the table is in the html actually in the <script> tag.

import requests
import pandas as pd
import re
import json

url = 'https://www.linestarapp.com/Ownership/Sport/NFL/Site/DraftKings/PID/295'

response = requests.get(url)

p = 'var actualResultsDict = ({*.})'

replaceDict = {"'":'"',
               'id': '"id"',
               'name':'"name"',
               'owned':'"owned"',
               'pos':'"pos"',
               'team':'"team"',
               'sal':'"sal"'}

jsonStr = re.search(r'var actualResultsDict = {([\w\W]*)function posMatch', response.text, re.M).group(1)

for key, value in replaceDict.items():
    jsonStr = jsonStr.replace(key, value)

jsonStrSplit = jsonStr.split('],')

jsonData = {}
for idx, each in enumerate(jsonStrSplit[:-1]):
    temp = '{' + each.rsplit(',',1)[0] + ']}'
    tempData = json.loads(temp)

    jsonData.update(tempData)

rows = []
for k,v in jsonData.items():
    rows += v

df = pd.DataFrame(rows)

Output:

print(df)
       id                   name  owned pos team   sal
0    5942       Devin Singletary  37.31  RB  BUF  5900
1    7303      Ja&#39;Marr Chase  33.57  WR  CIN  7100
2    7658           Eli Mitchell  28.31  RB   SF  5800
3    3612          Derrick Henry  26.93  RB  TEN  7500
4    2142          Davante Adams  26.25  WR   GB  8500
..    ...                    ...    ...  ..  ...   ...
108  6895  Nick Westbrook-Ikhine   1.72  WR  TEN  3800
109  6006          Scotty Miller   1.70  WR   TB  3300
110  4453     D&#39;Onta Foreman   1.64  RB  TEN  5200
111  2403            Geoff Swaim   1.36  TE  TEN  2800
112  5359      Dontrell Hilliard   1.08  RB  TEN  4300

[113 rows x 6 columns]


问:
How to declare two or multiple words as a single word although it contain space
I am creating a search for blood donors and everything is working fine and after completing the search I am facing some issues in it. My search is working but it's not showing perfect result. Let me elaborate,

```<code>#My Table Structure

    #Table 1- blood_donor
    +----+------+----------+-------------+
    | id | name | blood_id | location_id | // columns
    +----+------+----------+-------------+
    |  1 | rony |     1    |       1     |
    +----+------+----------+-------------+
    |  2 | jony |     2    |       2     |
    +----+------+----------+-------------+
    |  3 | tony |     3    |       3     |
    +----+------+----------+-------------+ // Data example

    #Table 2- blood_group
    +----+------------+
    | id | group_name | // columns
    +----+------------+
    |  1 | a positive |
    +----+------------+
    |  2 | b positive |
    +----+------------+
    |  3 | o negative |
    +----+------------+ // Data example

    #Table 3- location
    +----+---------------+
    | id | location_name | // columns
    +----+---------------+
    |  1 |     khulna    |
    +----+---------------+
    |  2 |     dhaka     |
    +----+---------------+
    |  3 |     sylhet    |
    +----+---------------+ // Data example
</code>```

My keyword

$keyword = "o negative blood donor in khulna";
```
<p>Now I separated the words</p>
<pre class="lang-php prettyprint-override"><code>$keyword_array = explode(" ",$keyword);
</code>```

Here is my query

$query ="SELECT * FROM
    blood_donor AS bd
LEFT JOIN blood_group AS bg ON bg.id = bd.blood_id
LEFT JOIN location    AS lo ON lo.id = bd.location_id
WHERE
bd.name          LIKE '%$keyword%' OR
bg.group_name    LIKE '%$keyword%' OR
lo.location_name LIKE '%$keyword%' OR";

// this above part giving me a result set for 100% match for the full keyword

// Now I generate another result set for separated keyword below

if (count($keyword_array) > 1) {
    foreach ($keyword_array as $array) {
        $query = $query . "
            bd.name          LIKE '%$array%' OR
            bg.group_name    LIKE '%$array%' OR
            lo.location_name LIKE '%$array%' OR";
    }
}

$query = substr($query,0,-3); // Removed the extra OR from the end

// My order by section
$query = $query . " ORDER BY
    CASE
        // If full match found, then bring them top
        WHEN bd.name LIKE '%$keyword%' THEN 1";

        // If partial match found, then bring them afterwards
        if (count($keyword_array) > 1) {
            $keyword_count = count($keyword_array);
            $query = $query . " WHEN";
            for ($i = 0; $i < $keyword_count; $i++) {
                $query = $query . " bd.name LIKE '%$keyword_array[$i]%' AND";
            }
            $query = substr($query,0,-3); // To remove the last AND
            $query = $query . " THEN 2";
        }
        $query = $query . " ELSE 3
    END
LIMIT $items_to_skip, $items_per_page"; // These two variables are OFFSET and LIMIT
```
<p>The keyword I am searching with, in the full match section it has nothing to do because there are no such sentence available in my database as `o negative blood donor in khulna that is okay but when the keywords getting separated then in the separated result section it's generating result what actually I am not looking for!</p>
<p>My separated keywords generating an array which is</p>
<pre class="lang-php prettyprint-override"><code>Array
(
    [0] => o
    [1] => negative
    [2] => blood
    [3] => donor
    [4] => in
    [5] => khulna
)
</code>```

And my SQL generating the query like this

bd.name          LIKE '%o%'        OR
bg.group_name    LIKE '%o%'        OR
lo.location_name LIKE '%o%'        OR
bd.name          LIKE '%negative%' OR
bg.group_name    LIKE '%negative%' OR
lo.location_name LIKE '%negative%' OR
bd.name          LIKE '%blood%'    OR
bg.group_name    LIKE '%blood%'    OR
lo.location_name LIKE '%blood%'    OR
bd.name          LIKE '%donor%'    OR
bg.group_name    LIKE '%donor%'    OR
lo.location_name LIKE '%donor%'    OR
bd.name          LIKE '%in%'       OR
bg.group_name    LIKE '%in%'       OR
lo.location_name LIKE '%in%'       OR
bd.name          LIKE '%khulna%'   OR
bg.group_name    LIKE '%khulna%'   OR
lo.location_name LIKE '%khulna%'
```
<p>This query giving me all the three rows because all the name contain the letter <code>o</code> but I don't want that! I want <code>o negative</code> as a single word so the result must be two rows. row 1 and 3. But how to achieve that? I really can't figure it out. Also I don't know how to make two different word as a single word.</p>
<p>There are eight blood groups and I want to treat every blood group name as a single word!
Example: A Negative is two word, but I want them as one word and how am I going to do it, is it possible?</p>
<p>I need an array like this. And how to do it?</p>
<pre class="lang-php prettyprint-override"><code>$keyword = "o negative blood donor in khulna";
$keyword_array = explode(" ",$keyword);
print_r($keyword_array);
Array
(
    [0] => o negative
    [1] => blood
    [2] => donor
    [3] => in
    [4] => khulna
)
</code>```

Thanks in advance.

答:
<?php

preg_match_all('/(\w\s+)?\w+/', 'o negative blood donor in khulna', $matches);
$keyword_array = $matches[0];
```

and here is an advice: please use prepared statement for SQL

Body:
I am creating a search for blood donors and everything is working fine and after completing the search I am facing some issues in it. My search is working but it's not showing perfect result. Let me elaborate,

#My Table Structure

    #Table 1- blood_donor
    +----+------+----------+-------------+
    | id | name | blood_id | location_id | // columns
    +----+------+----------+-------------+
    |  1 | rony |     1    |       1     |
    +----+------+----------+-------------+
    |  2 | jony |     2    |       2     |
    +----+------+----------+-------------+
    |  3 | tony |     3    |       3     |
    +----+------+----------+-------------+ // Data example

    #Table 2- blood_group
    +----+------------+
    | id | group_name | // columns
    +----+------------+
    |  1 | a positive |
    +----+------------+
    |  2 | b positive |
    +----+------------+
    |  3 | o negative |
    +----+------------+ // Data example

    #Table 3- location
    +----+---------------+
    | id | location_name | // columns
    +----+---------------+
    |  1 |     khulna    |
    +----+---------------+
    |  2 |     dhaka     |
    +----+---------------+
    |  3 |     sylhet    |
    +----+---------------+ // Data example

My keyword

$keyword = "o negative blood donor in khulna";

Now I separated the words

$keyword_array = explode(" ",$keyword);

Here is my query

$query ="SELECT * FROM
    blood_donor AS bd
LEFT JOIN blood_group AS bg ON bg.id = bd.blood_id
LEFT JOIN location    AS lo ON lo.id = bd.location_id
WHERE
bd.name          LIKE '%$keyword%' OR
bg.group_name    LIKE '%$keyword%' OR
lo.location_name LIKE '%$keyword%' OR";

// this above part giving me a result set for 100% match for the full keyword

// Now I generate another result set for separated keyword below

if (count($keyword_array) > 1) {
    foreach ($keyword_array as $array) {
        $query = $query . "
            bd.name          LIKE '%$array%' OR
            bg.group_name    LIKE '%$array%' OR
            lo.location_name LIKE '%$array%' OR";
    }
}

$query = substr($query,0,-3); // Removed the extra OR from the end

// My order by section
$query = $query . " ORDER BY
    CASE
        // If full match found, then bring them top
        WHEN bd.name LIKE '%$keyword%' THEN 1";

        // If partial match found, then bring them afterwards
        if (count($keyword_array) > 1) {
            $keyword_count = count($keyword_array);
            $query = $query . " WHEN";
            for ($i = 0; $i < $keyword_count; $i++) {
                $query = $query . " bd.name LIKE '%$keyword_array[$i]%' AND";
            }
            $query = substr($query,0,-3); // To remove the last AND
            $query = $query . " THEN 2";
        }
        $query = $query . " ELSE 3
    END
LIMIT $items_to_skip, $items_per_page"; // These two variables are OFFSET and LIMIT

The keyword I am searching with, in the full match section it has nothing to do because there are no such sentence available in my database as `o negative blood donor in khulna that is okay but when the keywords getting separated then in the separated result section it's generating result what actually I am not looking for!

My separated keywords generating an array which is

Array
(
    [0] => o
    [1] => negative
    [2] => blood
    [3] => donor
    [4] => in
    [5] => khulna
)

And my SQL generating the query like this

bd.name          LIKE '%o%'        OR
bg.group_name    LIKE '%o%'        OR
lo.location_name LIKE '%o%'        OR
bd.name          LIKE '%negative%' OR
bg.group_name    LIKE '%negative%' OR
lo.location_name LIKE '%negative%' OR
bd.name          LIKE '%blood%'    OR
bg.group_name    LIKE '%blood%'    OR
lo.location_name LIKE '%blood%'    OR
bd.name          LIKE '%donor%'    OR
bg.group_name    LIKE '%donor%'    OR
lo.location_name LIKE '%donor%'    OR
bd.name          LIKE '%in%'       OR
bg.group_name    LIKE '%in%'       OR
lo.location_name LIKE '%in%'       OR
bd.name          LIKE '%khulna%'   OR
bg.group_name    LIKE '%khulna%'   OR
lo.location_name LIKE '%khulna%'

This query giving me all the three rows because all the name contain the letter o but I don't want that! I want o negative as a single word so the result must be two rows. row 1 and 3. But how to achieve that? I really can't figure it out. Also I don't know how to make two different word as a single word.

There are eight blood groups and I want to treat every blood group name as a single word!
Example: A Negative is two word, but I want them as one word and how am I going to do it, is it possible?

I need an array like this. And how to do it?

$keyword = "o negative blood donor in khulna";
$keyword_array = explode(" ",$keyword);
print_r($keyword_array);
Array
(
    [0] => o negative
    [1] => blood
    [2] => donor
    [3] => in
    [4] => khulna
)

Thanks in advance.

Body:
<?php

preg_match_all('/(\w\s+)?\w+/', 'o negative blood donor in khulna', $matches);
$keyword_array = $matches[0];

and here is an advice: please use prepared statement for SQL


问:
How to scroll to an element?
I have a chat widget that pulls up an array of messages every time I scroll up. The problem I am facing now is the slider stays fixed at the top when messages load. I want it to focus on the last index element from the previous array. I figured out that I can make dynamic refs by passing index, but I would also need to know what kind of scroll function to use to achieve that </p>

```<code> handleScrollToElement(event) {
    const tesNode = ReactDOM.findDOMNode(this.refs.test)
    if (some_logic){
      //scroll to testNode
    }
  }

  render() {

    return (
      <div>
        <div ref="test"></div>
      </div>)
  }
</code>```

答:
Maybe someone meets situation like me

https://reactjs.org/docs/hooks-faq.html#how-can-i-measure-a-dom-node

How can I measure a DOM node?
One rudimentary way to measure the position or size of a DOM node is to use a callback ref. React will call that callback whenever the ref gets attached to a different node. Here is a small demo:

```<code>function MeasureExample() {
  const [height, setHeight] = useState(0);

  const measuredRef = useCallback(node => {
    if (node !== null) {
      setHeight(node.getBoundingClientRect().height);// you can scroll in this line
    }
  }, []);

  return (
    <>
      <h1 ref={measuredRef}>Hello, world</h1>
      <h2>The above header is {Math.round(height)}px tall</h2>
    </>
  );
}
</code>```

We didn’t choose useRef in this example because an object ref doesn’t notify us about changes to the current ref value. Using a callback ref ensures that even if a child component displays the measured node later (e.g. in response to a click), we still get notified about it in the parent component and can update the measurements.

Note that we pass [] as a dependency array to useCallback. This ensures that our ref callback doesn’t change between the re-renders, and so React won’t call it unnecessarily.

In this example, the callback ref will be called only when the component mounts and unmounts, since the rendered  component stays present throughout any rerenders. If you want to be notified any time a component resizes, you may want to use ResizeObserver or a third-party Hook built on it.

Title: How to scroll to an element?

Body:
I have a chat widget that pulls up an array of messages every time I scroll up. The problem I am facing now is the slider stays fixed at the top when messages load. I want it to focus on the last index element from the previous array. I figured out that I can make dynamic refs by passing index, but I would also need to know what kind of scroll function to use to achieve that

 handleScrollToElement(event) {
    const tesNode = ReactDOM.findDOMNode(this.refs.test)
    if (some_logic){
      //scroll to testNode
    }
  }

  render() {

    return (

)
  }

Body:
Maybe someone meets situation like me

https://reactjs.org/docs/hooks-faq.html#how-can-i-measure-a-dom-node

How can I measure a DOM node?
One rudimentary way to measure the position or size of a DOM node is to use a callback ref. React will call that callback whenever the ref gets attached to a different node. Here is a small demo:

function MeasureExample() {
  const [height, setHeight] = useState(0);

  const measuredRef = useCallback(node => {
    if (node !== null) {
      setHeight(node.getBoundingClientRect().height);// you can scroll in this line
    }
  }, []);

  return (
    <>
      <h1 ref={measuredRef}>Hello, world</h1>
      <h2>The above header is {Math.round(height)}px tall</h2>
    </>
  );
}

We didn’t choose useRef in this example because an object ref doesn’t notify us about changes to the current ref value. Using a callback ref ensures that even if a child component displays the measured node later (e.g. in response to a click), we still get notified about it in the parent component and can update the measurements.

Note that we pass [] as a dependency array to useCallback. This ensures that our ref callback doesn’t change between the re-renders, and so React won’t call it unnecessarily.

In this example, the callback ref will be called only when the component mounts and unmounts, since the rendered  component stays present throughout any rerenders. If you want to be notified any time a component resizes, you may want to use ResizeObserver or a third-party Hook built on it.


问:
I am unable to create this logic. Need to add index and subIndex fields dynamically
I am unable to create this logic, trying for hours. I just need to add index and subIndex properties with increments and on behave of different eventTicketId.

For a single ticket, for example eventTicketId:461. I have to have 2 fields like first ticket and its first value and then first ticket and its second value. Same goes for other tickets like for eventTicketId:463 it will go like first ticket and its first value, first ticket and its second value, second ticket and its first value and at last second ticket and its second value.

Orignal Array:

```<code> let ticketArray = [
 {
    "eventTicketId": "461",
    "title": "Name 1",
    "value": "salman",
    "type": 'name'
 },
{
    "eventTicketId": "461",
    "title": "CNIC 1",
    "value": "31221321",
    "type": 'cnic'

},
{
    "eventTicketId": "462",
    "title": "Name 1",
    "value": "asdfasdf",
    "type": 'name'

},
{
    "eventTicketId": "462",
    "title": "CNIC 1",
    "value": "31221321",
    "type": 'cnic'

},
{
    "eventTicketId": "463",
    "title": "Name 1",
    "value": "Adsadsa",
    "type": 'name'

},
{
    "eventTicketId": "463",
    "title": "CNIC 1",
    "value": "321312312",
    "type": 'cnic'
},
{
    "eventTicketId": "463",
    "title": "Name 2",
    "value": "Adsadsa",
    "type": 'name'

},
{
    "eventTicketId": "463",
    "title": "CNIC 2",
    "value": "133213",
    "type": 'cnic'
}];
</code>```

Required Array:

```<code> let ticketArray = [
 {
    "eventTicketId": "461",
    "title": "Name 1",
    "value": "salman",
    "type": 'name',
    "index": "1",
    "subIndex": "1"
}, {
    "eventTicketId": "461",
    "title": "CNIC 1",
    "value": "31221321",
    "type": 'cnic',
    "index": "1",
    "subIndex": "2"
},
{
    "eventTicketId": "462",
    "title": "Name 1",
    "value": "asdfasdf",
    "type": 'name',
    "index": "1",
    "subIndex": "1"

},
{
    "eventTicketId": "462",
    "title": "CNIC 1",
    "value": "31221321",
    "type": 'cnic',
    "index": "1",
    "subIndex": "2"

},
{
    "eventTicketId": "463",
    "title": "Name 2",
    "value": "Adsadsa",
    "type": 'name',
    "index": "1",
    "subIndex": "1"

},
{
    "eventTicketId": "463",
    "title": "CNIC 2",
    "value": "133213",
    "type": 'cnic',
    "index": "1",
    "subIndex": "2"
},

{
    "eventTicketId": "463",
    "title": "Name 1",
    "value": "Adsadsa",
    "type": 'name',
    "index": "2",
    "subIndex": "1"
},
{
    "eventTicketId": "463",
    "title": "CNIC 1",
    "value": "321312312",
    "type": 'cnic',
    "index": "2",
    "subIndex": "2"
},];
</code>```

答:
I made a snippet with what I think would be a possible answer to your problem.

 let ticketArray = [
 {
    "eventTicketId": "461",
    "title": "Name 1",
    "value": "salman",
    "type": 'name'
 },
{
    "eventTicketId": "461",
    "title": "CNIC 1",
    "value": "31221321",
    "type": 'cnic'

},
{
    "eventTicketId": "462",
    "title": "Name 1",
    "value": "asdfasdf",
    "type": 'name'

},
{
    "eventTicketId": "462",
    "title": "CNIC 1",
    "value": "31221321",
    "type": 'cnic'

},
{
    "eventTicketId": "463",
    "title": "Name 1",
    "value": "Adsadsa",
    "type": 'name'

},
{
    "eventTicketId": "463",
    "title": "CNIC 1",
    "value": "321312312",
    "type": 'cnic'
},
{
    "eventTicketId": "463",
    "title": "Name 2",
    "value": "Adsadsa",
    "type": 'name'

},
{
    "eventTicketId": "463",
    "title": "CNIC 2",
    "value": "133213",
    "type": 'cnic'
}];

const tickets = {};
const result = ticketArray.map(ticket => {
  let subIndex = 1
  if (tickets[ticket.eventTicketId]) {
    tickets[ticket.eventTicketId] += 1
  } else {
    tickets[ticket.eventTicketId] = 1
  }
  let index = Math.ceil(tickets[ticket.eventTicketId] / 2);
  subIndex = tickets[ticket.eventTicketId] % 2 == 0 ? 2 : 1
  return {...ticket, index, subIndex}
})

console.log(result)```

Body:
I am unable to create this logic, trying for hours. I just need to add index and subIndex properties with increments and on behave of different eventTicketId.

For a single ticket, for example eventTicketId:461. I have to have 2 fields like first ticket and its first value and then first ticket and its second value. Same goes for other tickets like for eventTicketId:463 it will go like first ticket and its first value, first ticket and its second value, second ticket and its first value and at last second ticket and its second value.

Orignal Array:

 let ticketArray = [
 {
    "eventTicketId": "461",
    "title": "Name 1",
    "value": "salman",
    "type": 'name'
 },
{
    "eventTicketId": "461",
    "title": "CNIC 1",
    "value": "31221321",
    "type": 'cnic'

},
{
    "eventTicketId": "462",
    "title": "Name 1",
    "value": "asdfasdf",
    "type": 'name'

},
{
    "eventTicketId": "462",
    "title": "CNIC 1",
    "value": "31221321",
    "type": 'cnic'

},
{
    "eventTicketId": "463",
    "title": "Name 1",
    "value": "Adsadsa",
    "type": 'name'

},
{
    "eventTicketId": "463",
    "title": "CNIC 1",
    "value": "321312312",
    "type": 'cnic'
},
{
    "eventTicketId": "463",
    "title": "Name 2",
    "value": "Adsadsa",
    "type": 'name'

},
{
    "eventTicketId": "463",
    "title": "CNIC 2",
    "value": "133213",
    "type": 'cnic'
}];

Required Array:

 let ticketArray = [
 {
    "eventTicketId": "461",
    "title": "Name 1",
    "value": "salman",
    "type": 'name',
    "index": "1",
    "subIndex": "1"
}, {
    "eventTicketId": "461",
    "title": "CNIC 1",
    "value": "31221321",
    "type": 'cnic',
    "index": "1",
    "subIndex": "2"
},
{
    "eventTicketId": "462",
    "title": "Name 1",
    "value": "asdfasdf",
    "type": 'name',
    "index": "1",
    "subIndex": "1"

},
{
    "eventTicketId": "462",
    "title": "CNIC 1",
    "value": "31221321",
    "type": 'cnic',
    "index": "1",
    "subIndex": "2"

},
{
    "eventTicketId": "463",
    "title": "Name 2",
    "value": "Adsadsa",
    "type": 'name',
    "index": "1",
    "subIndex": "1"

},
{
    "eventTicketId": "463",
    "title": "CNIC 2",
    "value": "133213",
    "type": 'cnic',
    "index": "1",
    "subIndex": "2"
},

{
    "eventTicketId": "463",
    "title": "Name 1",
    "value": "Adsadsa",
    "type": 'name',
    "index": "2",
    "subIndex": "1"
},
{
    "eventTicketId": "463",
    "title": "CNIC 1",
    "value": "321312312",
    "type": 'cnic',
    "index": "2",
    "subIndex": "2"
},];


答:
Create a "special" variable, remove that variable/string from $keyword, explode your $keyword and add the "special" variable back to the resulting array:

```<code><?php
$special = 'o negative';
$keyword = "o negative blood donor in khulna";
$keyword = trim(str_replace($special, '', $keyword));
$keyword_array = explode(" ",$keyword);
$keyword_array[] = $special;
print_r($keyword_array);
</code>```

will output:

```<code>Array
(
    [0] => blood
    [1] => donor
    [2] => in
    [3] => khulna
    [4] => o negative
)
</code>```

Edit:
To use multiple keywords to be replaced you can use this:

```<code><?php
$specials = array('a positive','b negative','o negative','ab positive');
$keyword = "o negative blood donor in khulna";
foreach($specials as $special) {
    if(strstr($keyword, $special)) {
        $keyword = trim(str_replace($special, '', $keyword));
        $found[] = $special;
    }
}
$keyword_array = explode(" ",$keyword);
$keyword_array = array_merge($keyword_array, $found);
print_r($keyword_array);
</code>```

If a "special" keyword was found it will be replaced in the original string and saved to a $found array. Your $keyword_array will be merged with the $found array in the end.

This will also work if you have multiple of those "special" keywords in your original string: Using $keyword = "o negative b negative blood donor in khulna a positive"; would output:

```<code>Array
(
    [0] => blood
    [1] => donor
    [2] => in
    [3] => khulna
    [4] => a positive
    [5] => b negative
    [6] => o negative
)
</code>```

Title: How to declare two or multiple words as a single word although it contain space

Body:
Create a "special" variable, remove that variable/string from $keyword, explode your $keyword and add the "special" variable back to the resulting array:

<?php
$special = 'o negative';
$keyword = "o negative blood donor in khulna";
$keyword = trim(str_replace($special, '', $keyword));
$keyword_array = explode(" ",$keyword);
$keyword_array[] = $special;
print_r($keyword_array);

will output:

Array
(
    [0] => blood
    [1] => donor
    [2] => in
    [3] => khulna
    [4] => o negative
)

Edit:
To use multiple keywords to be replaced you can use this:

<?php
$specials = array('a positive','b negative','o negative','ab positive');
$keyword = "o negative blood donor in khulna";
foreach($specials as $special) {
    if(strstr($keyword, $special)) {
        $keyword = trim(str_replace($special, '', $keyword));
        $found[] = $special;
    }
}
$keyword_array = explode(" ",$keyword);
$keyword_array = array_merge($keyword_array, $found);
print_r($keyword_array);

If a "special" keyword was found it will be replaced in the original string and saved to a $found array. Your $keyword_array will be merged with the $found array in the end.

This will also work if you have multiple of those "special" keywords in your original string: Using $keyword = "o negative b negative blood donor in khulna a positive"; would output:

Array
(
    [0] => blood
    [1] => donor
    [2] => in
    [3] => khulna
    [4] => a positive
    [5] => b negative
    [6] => o negative
)


问:
Selenium-chromedriver: Cannot construct KeyEvent from non-typeable key
I updated my Chrome and Chromedriver to the latest version yesterday, and since then I get the following error messages when running my Cucumber features:

```<code>....
unknown error: Cannot construct KeyEvent from non-typeable key
        (Session info: chrome=98.0.4758.80) (Selenium::WebDriver::Error::UnknownError)
      #0 0x55e9ce6a4093 <unknown>
      #1 0x55e9ce16a648 <unknown>
      #2 0x55e9ce1a9866 <unknown>
      #3 0x55e9ce1cbd29 <unknown>
      .....
</code>```

I try to fill a text field with Capybara's fill_in method. While debugging I noticed that Capybara has problems especially with the symbols @ and \. Every other character can be written into the text field without any problems.

The code that triggers the error looks like this

```<code>def sign_in(user)
  visit new_sign_in_path
  fill_in 'Email', with: user.email
  fill_in 'Password', with: user.password
  click_button 'Sign in'
end
</code>```

user.email contains a string like "example1@mail.com".

I work with Rails 6.1.3.1, Cucumber 5.3.0, Chromedriver 98.0.4758.48, capybara 3.35.3

The error only occurs on features that are tagged with @javascript

Do you have any ideas what causes this error or how to fix it?

答:
This issue affected me as well. This answer is for Python. This is how I currently set up my selenium tests in django. My chromium browser is snap version 98.0.4758.80.

```<code>@classmethod
def setUpClass(cls):
    super().setUpClass()

    options = webdriver.ChromeOptions()
    options.add_argument('--no-sandbox')  # Must be the very first option
    options.add_argument('--headless')
    options.add_argument('--disable-gpu')
    options.add_argument('--disable-software-rasterizer')

    options.add_argument('--disable-dev-shm-usage')
    options.add_argument("--remote-debugging-port=9222")
    options.add_argument("--no-default-browser-check")
    options.add_argument("--no-first-run")
    options.add_argument("--disable-default-apps")

    s = Service(
        ChromeDriverManager(
            # version='98.0.4758.80',
            # version='98.0.4758.48',
            version='97.0.4692.71',
            log_level=logging.WARNING,
            chrome_type=ChromeType.CHROMIUM).install())

    cls.selenium = webdriver.Chrome(
        service=s,
        options=options)
    cls.selenium.implicitly_wait(1)
</code>```

Body:
I updated my Chrome and Chromedriver to the latest version yesterday, and since then I get the following error messages when running my Cucumber features:

....
unknown error: Cannot construct KeyEvent from non-typeable key
        (Session info: chrome=98.0.4758.80) (Selenium::WebDriver::Error::UnknownError)
      #0 0x55e9ce6a4093 <unknown>
      #1 0x55e9ce16a648 <unknown>
      #2 0x55e9ce1a9866 <unknown>
      #3 0x55e9ce1cbd29 <unknown>
      .....

I try to fill a text field with Capybara's fill_in method. While debugging I noticed that Capybara has problems especially with the symbols @ and \. Every other character can be written into the text field without any problems.

The code that triggers the error looks like this

def sign_in(user)
  visit new_sign_in_path
  fill_in 'Email', with: user.email
  fill_in 'Password', with: user.password
  click_button 'Sign in'
end

user.email contains a string like "example1@mail.com".

I work with Rails 6.1.3.1, Cucumber 5.3.0, Chromedriver 98.0.4758.48, capybara 3.35.3

The error only occurs on features that are tagged with @javascript

Do you have any ideas what causes this error or how to fix it?

Body:
This issue affected me as well. This answer is for Python. This is how I currently set up my selenium tests in django. My chromium browser is snap version 98.0.4758.80.

@classmethod
def setUpClass(cls):
    super().setUpClass()

    options = webdriver.ChromeOptions()
    options.add_argument('--no-sandbox')  # Must be the very first option
    options.add_argument('--headless')
    options.add_argument('--disable-gpu')
    options.add_argument('--disable-software-rasterizer')

    options.add_argument('--disable-dev-shm-usage')
    options.add_argument("--remote-debugging-port=9222")
    options.add_argument("--no-default-browser-check")
    options.add_argument("--no-first-run")
    options.add_argument("--disable-default-apps")

    s = Service(
        ChromeDriverManager(
            # version='98.0.4758.80',
            # version='98.0.4758.48',
            version='97.0.4692.71',
            log_level=logging.WARNING,
            chrome_type=ChromeType.CHROMIUM).install())

    cls.selenium = webdriver.Chrome(
        service=s,
        options=options)
    cls.selenium.implicitly_wait(1)


问:
How to do the multiplication with array objects
How to do the multiplication with array objects and get the all 3 outputs

const size = [
  { hight: 20, width: 23, length: 54 },
  { hight: 40, width: 43, length: 44 },
  { hight: 20, width: 23, length: 54 },
];
const total = (size) => {
  const totalvalue = size.hight * size.width * size.length;
};
console.log(total)```

答:
You'll have to loop through the array. Something like:

const size = [
    { hight: 20, width: 23, length: 54 },
    { hight: 40, width: 43, length: 44 },
    { hight: 20, width: 23, length: 54 },
];
const total = row => row.total = row.hight + row.width + row.length;
size.forEach(total);

console.log(size);```


问:
Non nullable instance field must be initalised
im new to Dart-flutter.

i have watching a tutorial video from udemy course writing in dart pad

so i also wrote in dartpad. but it showing error in it.

this is the code wrote in udemy..

```<code>import 'dart:convert';

 void main(){
  var rawJson = '{"url": "https://helo.com","id": 2}';
  var parsedJson = json.decode(rawJson);
  var imageModel = new ImageModel.fromJson(parsedJson);

  print(imageModel.url);
 }

class ImageModel{
  int id;
  String url;

  ImageModel.fromJson(parsedJson) {
    id = parsedJson['id'];
    url = parsedJson['url'];
  }

   ImageModel(this.id, this.url);
}
</code>```

in that video it runs, but for me it shows error as

```<code>Error compiling to JavaScript:
Info: Compiling with sound null safety
Warning: Interpreting this as package URI, 'package:dartpad_sample/main.dart'.
lib/main.dart:15:3:
Error: This constructor should initialize field 'id' because its type 'int' doesn't allow null.
  ImageModel.fromJson(parsedJson) {
  ^
lib/main.dart:12:7:
Info: 'id' is defined here.
  int id;
      ^^
lib/main.dart:15:3:
Error: This constructor should initialize field 'url' because its type 'String' doesn't allow null.
  ImageModel.fromJson(parsedJson) {
  ^
lib/main.dart:13:10:
Info: 'url' is defined here.
  String url;
         ^^^
Error: Compilation failed.
</code>```

i have no idea what the problem is..
can you guys help me to troubleshoot the error

答:
You are probably watching tutorial that was recorded before null-safety introduction in Dart (null-safety is a Dart feature that helps prevent NullRefference exceptions in runtime).

You can either go with nullable values (like @Sowat Kheang suggested in another answer) for id and url in ImageModel class (change String to String? and int to int?). Then you will be fine, but it defeats the purpose of null-safety.

Or you can change your code so it will handle null values in proper way. Code will look something like this:

```<code>import 'dart:convert';

 void main(){
  var rawJson = '{"url": "https://helo.com","id": 2}';
  var parsedJson = json.decode(rawJson);
  var imageModel = ImageModel.fromJson(parsedJson);

  print(imageModel.url);
 }

class ImageModel{
  // Make your fields 'final' if you don't plan to change them later
  // this will make your life easier and is a good practice.
  final int id;
  final String url;

  // we add curly braces to make arguments named
  // and add 'required' keyword to indicate that constructor can't be called
  // without actually passing arguments into it
  ImageModel({required this.id, required this.url});

 // here we use factory constructor that will call our default constructor
 // it's also a good practice to specify type of a variable if you know it (Map<String, dynamic> in this case)
  factory ImageModel.fromJson(Map<String, dynamic> parsedJson) {

    // since we don't know for sure if 'parsedJson' has key 'id'
    // we would add '??' — null checking operator.
    // So if parsedJson['id'] is null, value -1 will be passed
    // to the constructor. Same with 'parsedJson['url']'.
    return ImageModel(
        id: parsedJson['id'] ?? -1,
        url: parsedJson['url'] ?? '');
  }

}
</code>```

Body:
im new to Dart-flutter.

i have watching a tutorial video from udemy course writing in dart pad

so i also wrote in dartpad. but it showing error in it.

this is the code wrote in udemy..

import 'dart:convert';

 void main(){
  var rawJson = '{"url": "https://helo.com","id": 2}';
  var parsedJson = json.decode(rawJson);
  var imageModel = new ImageModel.fromJson(parsedJson);

  print(imageModel.url);
 }

class ImageModel{
  int id;
  String url;

  ImageModel.fromJson(parsedJson) {
    id = parsedJson['id'];
    url = parsedJson['url'];
  }

   ImageModel(this.id, this.url);
}

in that video it runs, but for me it shows error as

Error compiling to JavaScript:
Info: Compiling with sound null safety
Warning: Interpreting this as package URI, 'package:dartpad_sample/main.dart'.
lib/main.dart:15:3:
Error: This constructor should initialize field 'id' because its type 'int' doesn't allow null.
  ImageModel.fromJson(parsedJson) {
  ^
lib/main.dart:12:7:
Info: 'id' is defined here.
  int id;
      ^^
lib/main.dart:15:3:
Error: This constructor should initialize field 'url' because its type 'String' doesn't allow null.
  ImageModel.fromJson(parsedJson) {
  ^
lib/main.dart:13:10:
Info: 'url' is defined here.
  String url;
         ^^^
Error: Compilation failed.

i have no idea what the problem is..
can you guys help me to troubleshoot the error

Body:
You are probably watching tutorial that was recorded before null-safety introduction in Dart (null-safety is a Dart feature that helps prevent NullRefference exceptions in runtime).

You can either go with nullable values (like @Sowat Kheang suggested in another answer) for id and url in ImageModel class (change String to String? and int to int?). Then you will be fine, but it defeats the purpose of null-safety.

Or you can change your code so it will handle null values in proper way. Code will look something like this:

import 'dart:convert';

 void main(){
  var rawJson = '{"url": "https://helo.com","id": 2}';
  var parsedJson = json.decode(rawJson);
  var imageModel = ImageModel.fromJson(parsedJson);

  print(imageModel.url);
 }

class ImageModel{
  // Make your fields 'final' if you don't plan to change them later
  // this will make your life easier and is a good practice.
  final int id;
  final String url;

  // we add curly braces to make arguments named
  // and add 'required' keyword to indicate that constructor can't be called
  // without actually passing arguments into it
  ImageModel({required this.id, required this.url});

 // here we use factory constructor that will call our default constructor
 // it's also a good practice to specify type of a variable if you know it (Map<String, dynamic> in this case)
  factory ImageModel.fromJson(Map<String, dynamic> parsedJson) {

    // since we don't know for sure if 'parsedJson' has key 'id'
    // we would add '??' — null checking operator.
    // So if parsedJson['id'] is null, value -1 will be passed
    // to the constructor. Same with 'parsedJson['url']'.
    return ImageModel(
        id: parsedJson['id'] ?? -1,
        url: parsedJson['url'] ?? '');
  }

}


问:
Trigger single component of hover effect in multi component of `v-for`
all. I currently meet a CSS problem with Vue. Suppose I want to render multiple component by using v-for, and I want bind hover effect with each component. Once I hover my mouse on one component, there will be hover effect on that component, and the other components will keep unchanged. However, as I typed code below, if I hover my mouse on one component, all component will be affected. So, my question is how could I achieve my purpose?

```<code><component v-for="(item, index) in items" :key="index">
  <div @mouseover="hover = true" @mouseleave="hover = false">
     <div v-if="hover" class="xx"> Hover Effect </div>
     <div v-else> Normal Effect </div>
  </div>
</component>
</code>```

答:
The answer is pretty straightforward for this problem. What you have to do is keep track of the index or the key of the element which you hover and clear it when you leave. You can write two specific methods for this if you want.</p>
```<code><component v-for="(item, index) in items" :key="index">
 <div @mouseover="hoveredIndex = index" @mouseleave="hoveredIndex = -1">
  <div v-if="hoveredIndex===index" class="xx"> Hover Effect </div>
    <div v-else> Normal Effect </div>
   </div>
</component>
</code>```

Body:
all. I currently meet a CSS problem with Vue. Suppose I want to render multiple component by using v-for, and I want bind hover effect with each component. Once I hover my mouse on one component, there will be hover effect on that component, and the other components will keep unchanged. However, as I typed code below, if I hover my mouse on one component, all component will be affected. So, my question is how could I achieve my purpose?

<component v-for="(item, index) in items" :key="index">

 Hover Effect

 Normal Effect

</component>

Body:
The answer is pretty straightforward for this problem. What you have to do is keep track of the index or the key of the element which you hover and clear it when you leave. You can write two specific methods for this if you want.

<component v-for="(item, index) in items" :key="index">
 <div @mouseover="hoveredIndex = index" @mouseleave="hoveredIndex = -1">
  <div v-if="hoveredIndex===index" class="xx"> Hover Effect </div>
    <div v-else> Normal Effect </div>
   </div>
</component>


问:
Render hbs template inside a service in NestJS
I need to generate an HTML content from an HBS template and pass this content to a puppeteer page and export a PDF.

```<code>@UseGuards(JwtAuthGuard)
  @Get('minimal')
  async minimal(
    @Param('id') projectId: string,
    @Res() res: Response
  ) {
    const project = await this.projectService.get(projectId);
    const articles = await this.articleService.getAll(projectId);

    const buffer: Buffer = await this.katalog.minimal(res, project, articles);

    res.set({
      'Content-Type': 'application/pdf',
      'Content-Disposition': 'attachment; filename=katalog.pdf',
      'Content-Length': buffer.length,
      'Cache-Control': 'no-cache, no-store, must-revalidate',
      'Pragma': 'no-cache',
      'Expires': 0
    });

    res.end(buffer);
  }
</code>```

and my service looks like this:

```<code>@Injectable()
export class KatalogService {

  async minimal(res: Response, project: Project, articles: Article[]): Promise<Buffer> {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    const content = await this.render(res, project, articles);

    await page.setContent(content);

    const pdfBuffer = await page.pdf();

    await page.close();
    await browser.close();

    return pdfBuffer;
  }

  async render(res: Response, project: Project, articles: Article[]): Promise<string> {
    return new Promise((resolve, reject) => {
      res.render('katalog', {}, (err, html) => {
        if(err) return reject(err);
        return resolve(html);
      })
    });
  }

}
</code>```

My code works fine, i just wanted to know if there is any method to achieve this without passing the res object as a parameter.

答:
Notice!!!

I don't use puppeter to generate a PDF (could not make it work on WSL2), but you can do it by simply changing the RenderPDFInterceptor.generatePDFAttachment method!!!

If you want to try the code and something doesn't work, feel free to ask me in comments .

A custom RenderPDF decorator that adds an interceptor (version 1):

Usage (app.controller.ts):

Add the RenderPDF to any handler. This handler must return PDFRenderOptions.

import { Controller, Get } from '@nestjs/common';
import { PDFRenderOptions, RenderPDF } from './render-pdf.decorator';

@Controller()
export class AppController {
  @Get('/file')
  @RenderPDF()
  getFile(): PDFRenderOptions {
    return {
      templateFilename: 'template',
      attachmentFilename: 'file.pdf',
      locals: { message: 'Hi' }
    }
  }
}
```
<h4>Implementation (<code>render-pdf.decorator.ts</code>):</h4>
<pre class="lang-js prettyprint-override"><code>import { CallHandler, ExecutionContext, Injectable, NestInterceptor, StreamableFile, UseInterceptors } from '@nestjs/common';
import { Observable, mergeMap } from 'rxjs';
import { create as generatePDF } from 'html-pdf';
import { Application, Request } from 'express';

type NodeCallback<T> = (err: Error, val: T) => void;
type PromisifyCallback<T> = (cb: NodeCallback<T>) => void

const promise = <T>(cb: PromisifyCallback<T>) => {
  return new Promise<T>((res, rej) => cb((err, val) => err ? rej(err) : res(val) ));
}

export interface PDFRenderOptions {
  templateFilename: string;
  attachmentFilename: string;
  locals?: Record<string, any>;
}

@Injectable()
class RenderPDFInterceptor implements NestInterceptor {
  intercept(ctx: ExecutionContext, next: CallHandler): Observable<any> {
    const { app } = ctx.switchToHttp().getRequest() as Request;
    return next.handle().pipe(mergeMap((opts: PDFRenderOptions) => this.generatePDFAttachment(app, opts)));
  }

  private async generatePDFAttachment(app: Application, options: PDFRenderOptions) {
    const html = await promise<string>((cb) => app.render(options.templateFilename, options.locals, cb));
    const pdf = await promise<Buffer>((cb) => generatePDF(html).toBuffer(cb));
    return new StreamableFile(pdf, { disposition: `attachment; filename="${options.attachmentFilename}"` })
  }
}

export const RenderPDF = () => {
  return UseInterceptors(RenderPDFInterceptor);
}
</code>```

A custom RenderPDF decorator that adds an interceptor + A custom AddRenderPDFOptions decorator (version 2)

Usage (app.controller.ts)

Apply the RenderPDF to some handler or a whole controller and pass some default options there. Now you can use AddRenderPDFOptions decorator to change controller-level options and/or return options from handlers to change handler-level options.

import { Controller, Get } from '@nestjs/common';
import { PDFRenderOptions, RenderPDF, AddRenderPDFOptions } from './render-pdf.interceptor';

@Controller()
@RenderPDF({
  templateFilename: 'default-template',
  attachmentFilename: 'default-filename.pdf',
  locals: { message: 'DEFAULT MESSAGE' },
})
export class AppController {
  @Get('/default')
  getDefaultFile() {
    return {};
  }

  @Get('/different')
  @AddRenderPDFOptions({
    templateFilename: 'different-template',
    locals: { message: 'DIFFERENT MESSAGE' }
  })
  getDifferentFile(): PDFRenderOptions {
    return {
      attachmentFilename: Math.random() > 0.5
        ? 'first-different-filename.pdf'
        : 'second-different-filename.pdf',
    }
  }

  @Get('/random')
  @AddRenderPDFOptions({
    templateFilename: 'template-for-random',
  })
  getRandomFile() {
    return {
      locals: { message: Math.random().toString() }
    }
  }
}

@Controller()
export class DifferentAppController {
  @Get('something-but-not-pdf')
  getSomethingButNotPDF() {
    return { something: true };
  }

  @Get('pdf')
  @RenderPDF({ templateFilename: 'pdf', attachmentFilename: 'pdf.pdf' })
  getPDF(): PDFRenderOptions {
    return { locals: { message: "pdf" } }
  }
}
```
<h4>Implementation:</h4>
<pre class="lang-js prettyprint-override"><code>import { applyDecorators, CallHandler, ExecutionContext, Injectable, NestInterceptor, SetMetadata, StreamableFile, UseInterceptors } from '@nestjs/common';
import { Observable, mergeMap } from 'rxjs';
import { create as generatePDF } from 'html-pdf';
import { Application, Request } from 'express';
import { Reflector } from '@nestjs/core';

type NodeCallback<T> = (err: Error, val: T) => void;
type PromisifyCallback<T> = (cb: NodeCallback<T>) => void

const promise = <T>(cb: PromisifyCallback<T>) => {
  return new Promise<T>((res, rej) => cb((err, val) => err ? rej(err) : res(val) ));
}

const PDF_RENDER_OPTIONS_METADATA_KEY = Symbol('PDF render options');

export interface PDFRenderOptions {
  templateFilename?: string;
  attachmentFilename?: string;
  locals?: Record<string, any>;
}

@Injectable()
class RenderPDFInterceptor implements NestInterceptor {
  constructor(private reflector: Reflector) {}

  intercept(ctx: ExecutionContext, next: CallHandler): Observable<any> {
    const { app } = ctx.switchToHttp().getRequest() as Request;

    return next.handle().pipe(
      mergeMap((responseOptions: PDFRenderOptions) => (
        this.generatePDFAttachment(app, this.getFinalRenderOptions(ctx, responseOptions))
      ))
    );
  }

  private async generatePDFAttachment(app: Application, options: PDFRenderOptions) {
    console.log("FINAL OPTIONS", options)
    const html = await promise<string>((cb) => app.render(options.templateFilename, options.locals, cb));
    const pdf = await promise<Buffer>((cb) => generatePDF(html).toBuffer(cb));
    return new StreamableFile(pdf, { disposition: `attachment; filename="${options.attachmentFilename}"` })
  }

  private getFinalRenderOptions(ctx: ExecutionContext, responseOptions: PDFRenderOptions) {
    const controllerOptions = this.reflector.get<PDFRenderOptions>(PDF_RENDER_OPTIONS_METADATA_KEY, ctx.getClass()) || {};
    const handlerOptions = this.reflector.get<PDFRenderOptions>(PDF_RENDER_OPTIONS_METADATA_KEY, ctx.getHandler()) || {};

    return {
      ...controllerOptions,
      ...handlerOptions,
      ...responseOptions,
      locals: {
        ...controllerOptions.locals,
        ...handlerOptions.locals,
        ...responseOptions.locals,
      }
    }
  }
}

export const AddRenderPDFOptions = (options: PDFRenderOptions = {}) => {
  return SetMetadata(PDF_RENDER_OPTIONS_METADATA_KEY, { locals: {}, ...options });
}

export const RenderPDF = (options: PDFRenderOptions = {}) => {
  return applyDecorators(
    AddRenderPDFOptions(options),
    UseInterceptors(RenderPDFInterceptor),
  )
}
</code>```

Body:
I need to generate an HTML content from an HBS template and pass this content to a puppeteer page and export a PDF.

@UseGuards(JwtAuthGuard)
  @Get('minimal')
  async minimal(
    @Param('id') projectId: string,
    @Res() res: Response
  ) {
    const project = await this.projectService.get(projectId);
    const articles = await this.articleService.getAll(projectId);

    const buffer: Buffer = await this.katalog.minimal(res, project, articles);

    res.set({
      'Content-Type': 'application/pdf',
      'Content-Disposition': 'attachment; filename=katalog.pdf',
      'Content-Length': buffer.length,
      'Cache-Control': 'no-cache, no-store, must-revalidate',
      'Pragma': 'no-cache',
      'Expires': 0
    });

    res.end(buffer);
  }

and my service looks like this:

@Injectable()
export class KatalogService {

  async minimal(res: Response, project: Project, articles: Article[]): Promise<Buffer> {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    const content = await this.render(res, project, articles);

    await page.setContent(content);

    const pdfBuffer = await page.pdf();

    await page.close();
    await browser.close();

    return pdfBuffer;
  }

  async render(res: Response, project: Project, articles: Article[]): Promise<string> {
    return new Promise((resolve, reject) => {
      res.render('katalog', {}, (err, html) => {
        if(err) return reject(err);
        return resolve(html);
      })
    });
  }

}

My code works fine, i just wanted to know if there is any method to achieve this without passing the res object as a parameter.

Body:
Notice!!!

I don't use puppeter to generate a PDF (could not make it work on WSL2), but you can do it by simply changing the RenderPDFInterceptor.generatePDFAttachment method!!!

If you want to try the code and something doesn't work, feel free to ask me in comments .

A custom RenderPDF decorator that adds an interceptor (version 1):

Usage (app.controller.ts):

Add the RenderPDF to any handler. This handler must return PDFRenderOptions.

import { Controller, Get } from '@nestjs/common';
import { PDFRenderOptions, RenderPDF } from './render-pdf.decorator';

@Controller()
export class AppController {
  @Get('/file')
  @RenderPDF()
  getFile(): PDFRenderOptions {
    return {
      templateFilename: 'template',
      attachmentFilename: 'file.pdf',
      locals: { message: 'Hi' }
    }
  }
}

Implementation (render-pdf.decorator.ts):

import { CallHandler, ExecutionContext, Injectable, NestInterceptor, StreamableFile, UseInterceptors } from '@nestjs/common';
import { Observable, mergeMap } from 'rxjs';
import { create as generatePDF } from 'html-pdf';
import { Application, Request } from 'express';

type NodeCallback<T> = (err: Error, val: T) => void;
type PromisifyCallback<T> = (cb: NodeCallback<T>) => void

const promise = <T>(cb: PromisifyCallback<T>) => {
  return new Promise<T>((res, rej) => cb((err, val) => err ? rej(err) : res(val) ));
}

export interface PDFRenderOptions {
  templateFilename: string;
  attachmentFilename: string;
  locals?: Record<string, any>;
}

@Injectable()
class RenderPDFInterceptor implements NestInterceptor {
  intercept(ctx: ExecutionContext, next: CallHandler): Observable<any> {
    const { app } = ctx.switchToHttp().getRequest() as Request;
    return next.handle().pipe(mergeMap((opts: PDFRenderOptions) => this.generatePDFAttachment(app, opts)));
  }

  private async generatePDFAttachment(app: Application, options: PDFRenderOptions) {
    const html = await promise<string>((cb) => app.render(options.templateFilename, options.locals, cb));
    const pdf = await promise<Buffer>((cb) => generatePDF(html).toBuffer(cb));
    return new StreamableFile(pdf, { disposition: `attachment; filename="${options.attachmentFilename}"` })
  }
}

export const RenderPDF = () => {
  return UseInterceptors(RenderPDFInterceptor);
}

A custom RenderPDF decorator that adds an interceptor + A custom AddRenderPDFOptions decorator (version 2)

Usage (app.controller.ts)

Apply the RenderPDF to some handler or a whole controller and pass some default options there. Now you can use AddRenderPDFOptions decorator to change controller-level options and/or return options from handlers to change handler-level options.

import { Controller, Get } from '@nestjs/common';
import { PDFRenderOptions, RenderPDF, AddRenderPDFOptions } from './render-pdf.interceptor';

@Controller()
@RenderPDF({
  templateFilename: 'default-template',
  attachmentFilename: 'default-filename.pdf',
  locals: { message: 'DEFAULT MESSAGE' },
})
export class AppController {
  @Get('/default')
  getDefaultFile() {
    return {};
  }

  @Get('/different')
  @AddRenderPDFOptions({
    templateFilename: 'different-template',
    locals: { message: 'DIFFERENT MESSAGE' }
  })
  getDifferentFile(): PDFRenderOptions {
    return {
      attachmentFilename: Math.random() > 0.5
        ? 'first-different-filename.pdf'
        : 'second-different-filename.pdf',
    }
  }

  @Get('/random')
  @AddRenderPDFOptions({
    templateFilename: 'template-for-random',
  })
  getRandomFile() {
    return {
      locals: { message: Math.random().toString() }
    }
  }
}

@Controller()
export class DifferentAppController {
  @Get('something-but-not-pdf')
  getSomethingButNotPDF() {
    return { something: true };
  }

  @Get('pdf')
  @RenderPDF({ templateFilename: 'pdf', attachmentFilename: 'pdf.pdf' })
  getPDF(): PDFRenderOptions {
    return { locals: { message: "pdf" } }
  }
}

Implementation:

import { applyDecorators, CallHandler, ExecutionContext, Injectable, NestInterceptor, SetMetadata, StreamableFile, UseInterceptors } from '@nestjs/common';
import { Observable, mergeMap } from 'rxjs';
import { create as generatePDF } from 'html-pdf';
import { Application, Request } from 'express';
import { Reflector } from '@nestjs/core';

type NodeCallback<T> = (err: Error, val: T) => void;
type PromisifyCallback<T> = (cb: NodeCallback<T>) => void

const promise = <T>(cb: PromisifyCallback<T>) => {
  return new Promise<T>((res, rej) => cb((err, val) => err ? rej(err) : res(val) ));
}

const PDF_RENDER_OPTIONS_METADATA_KEY = Symbol('PDF render options');

export interface PDFRenderOptions {
  templateFilename?: string;
  attachmentFilename?: string;
  locals?: Record<string, any>;
}

@Injectable()
class RenderPDFInterceptor implements NestInterceptor {
  constructor(private reflector: Reflector) {}

  intercept(ctx: ExecutionContext, next: CallHandler): Observable<any> {
    const { app } = ctx.switchToHttp().getRequest() as Request;

    return next.handle().pipe(
      mergeMap((responseOptions: PDFRenderOptions) => (
        this.generatePDFAttachment(app, this.getFinalRenderOptions(ctx, responseOptions))
      ))
    );
  }

  private async generatePDFAttachment(app: Application, options: PDFRenderOptions) {
    console.log("FINAL OPTIONS", options)
    const html = await promise<string>((cb) => app.render(options.templateFilename, options.locals, cb));
    const pdf = await promise<Buffer>((cb) => generatePDF(html).toBuffer(cb));
    return new StreamableFile(pdf, { disposition: `attachment; filename="${options.attachmentFilename}"` })
  }

  private getFinalRenderOptions(ctx: ExecutionContext, responseOptions: PDFRenderOptions) {
    const controllerOptions = this.reflector.get<PDFRenderOptions>(PDF_RENDER_OPTIONS_METADATA_KEY, ctx.getClass()) || {};
    const handlerOptions = this.reflector.get<PDFRenderOptions>(PDF_RENDER_OPTIONS_METADATA_KEY, ctx.getHandler()) || {};

    return {
      ...controllerOptions,
      ...handlerOptions,
      ...responseOptions,
      locals: {
        ...controllerOptions.locals,
        ...handlerOptions.locals,
        ...responseOptions.locals,
      }
    }
  }
}

export const AddRenderPDFOptions = (options: PDFRenderOptions = {}) => {
  return SetMetadata(PDF_RENDER_OPTIONS_METADATA_KEY, { locals: {}, ...options });
}

export const RenderPDF = (options: PDFRenderOptions = {}) => {
  return applyDecorators(
    AddRenderPDFOptions(options),
    UseInterceptors(RenderPDFInterceptor),
  )
}


问:
Parse HTML with jquery
suppose in a variable html is saved like

```<code>var vhtm="<div><div id='test'>zebra</div><div id='foo'>here is my many other html content</div></div>";
</code>```

i want to parse the above html stored in variable with the help of jquery.
i need to extract a particular div by id and including its content. the return result would like

```<code><div id='foo'>here is my many other html content</div>
</code>```

so i need to find div by id like id='foo'

please help me how to parse the above like jquery.

答:
Since you want the output to contain the whole div including content I'd suggest you use some regular expressions :) Like this maybe:

```<code>var vhtm="<div><div id='test'>zebra</div><div id='foo'>here is my many other html content</div></div>";
var regex = /<div id='foo'>.*?<\/div>/;
alert(vhtm.match(regex));
</code>```

Result:

Title: Parse HTML with jquery

Body:
suppose in a variable html is saved like

var vhtm="

zebra

here is my many other html content

";

i want to parse the above html stored in variable with the help of jquery.
i need to extract a particular div by id and including its content. the return result would like

here is my many other html content

so i need to find div by id like id='foo'

please help me how to parse the above like jquery.

Body:
Since you want the output to contain the whole div including content I'd suggest you use some regular expressions :) Like this maybe:

var vhtm="<div><div id='test'>zebra</div><div id='foo'>here is my many other html content</div></div>";
var regex = /<div id='foo'>.*?<\/div>/;
alert(vhtm.match(regex));

Result:


问:
Get data from django database model
I have a django model, PhoneNumberVerification.

It has two columns: phone number, and code.
I want to be able to get the code if I am given a phone number. Essentially, search the table for which row has the phone number as my phone number, and fetch the code for that given row.

I could write SQL for this, but I do not know how to execute that to fetch data in django models, and I was wondering if there was a better non-sql way to do this.

My model:

```<code>class PhoneNumberVerification(models.Model):
    phone_number = models.TextField(max_length = 20, blank = False, unique = True)
    code = models.CharField(max_length = 8, blank = False)
</code>```

What I want:

from .models import PhoneNumberVerification

def get_code(phone_number):
    # do some stuff
    return code
```

答:
def get_code(phone_number):
  verification = PhoneNumberVerification.objects.get(phone_number=phone_number)
  return verification.code
```

Django's documentation has great tutorial for beginners.
Writing your first Django app, part 2

Title: Get data from django database model

Body:
I have a django model, PhoneNumberVerification.

It has two columns: phone number, and code.
I want to be able to get the code if I am given a phone number. Essentially, search the table for which row has the phone number as my phone number, and fetch the code for that given row.

I could write SQL for this, but I do not know how to execute that to fetch data in django models, and I was wondering if there was a better non-sql way to do this.

My model:

class PhoneNumberVerification(models.Model):
    phone_number = models.TextField(max_length = 20, blank = False, unique = True)
    code = models.CharField(max_length = 8, blank = False)

What I want:

from .models import PhoneNumberVerification

def get_code(phone_number):
    # do some stuff
    return code

Body:
def get_code(phone_number):
  verification = PhoneNumberVerification.objects.get(phone_number=phone_number)
  return verification.code

Django's documentation has great tutorial for beginners.
Writing your first Django app, part 2


问:
Error : When i try to install php 7 version on centos 7 but Package comes Php 5 version
When I try to install the PHP 7 version on my centos 7 but the Package comes from  Php 5 version so I decided to change the repo rebel to Remi and disable the rebel after I got the below error

答:
I started a Docker container using centos:7 and I ran the following commands:

```<code>yum -y install https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
yum -y install https://rpms.remirepo.net/enterprise/remi-release-7.rpm
yum -y install yum-utils
yum-config-manager --disable 'remi-php*'
yum-config-manager --enable   remi-php74
yum -y update
yum -y install php
yum -y install php-fpm php-gd php-json php-mbstring php-mysqlnd php-xml php-xmlrpc php-opcache
</code>```

Now let's see the phpversion.

```<code>sh-4.2# php -v
PHP 7.4.27 (cli) (built: Dec 14 2021 17:17:06) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
with Zend OPcache v7.4.27, Copyright (c), by Zend Technologies

sh-4.2# php-fpm -v
PHP 7.4.27 (fpm-fcgi) (built: Dec 14 2021 17:17:06)
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
with Zend OPcache v7.4.27, Copyright (c), by Zend Technologies
</code>```

Body:
I started a Docker container using centos:7 and I ran the following commands:

yum -y install https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
yum -y install https://rpms.remirepo.net/enterprise/remi-release-7.rpm
yum -y install yum-utils
yum-config-manager --disable 'remi-php*'
yum-config-manager --enable   remi-php74
yum -y update
yum -y install php
yum -y install php-fpm php-gd php-json php-mbstring php-mysqlnd php-xml php-xmlrpc php-opcache

Now let's see the phpversion.

sh-4.2# php -v
PHP 7.4.27 (cli) (built: Dec 14 2021 17:17:06) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
with Zend OPcache v7.4.27, Copyright (c), by Zend Technologies

sh-4.2# php-fpm -v
PHP 7.4.27 (fpm-fcgi) (built: Dec 14 2021 17:17:06)
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
with Zend OPcache v7.4.27, Copyright (c), by Zend Technologies


问:
Escape ampersand in PL/SQL Developer
I'm trying a simple INSERT statement against an Oracle database.  One of the values is a VARCHAR2 field and the insert statement contains an ampersand.  How do I do this?  I've tried the following methods:

Escape the & as \& with set escape on

set scan off (this causes an ORA-00922 missing or invalid option error)

set define off (this causes an ORA-00922 missing or invalid option error)

Any other ideas?

答:
Have you tried something like this?

```<code>INSERT INTO tablex VALUES ('Sid ' || '&' || ' Nancy');
</code>```

Improving my first answer, your problem is related with PL/SQL Developer. If you execute your block in a PL/SQL Developer Command window, you could also use the standard SET DEFINE OFF, which works the same as in SQL*Plus.

Title: Escape ampersand in PL/SQL Developer

Body:
Have you tried something like this?

INSERT INTO tablex VALUES ('Sid ' || '&' || ' Nancy');

Improving my first answer, your problem is related with PL/SQL Developer. If you execute your block in a PL/SQL Developer Command window, you could also use the standard SET DEFINE OFF, which works the same as in SQL*Plus.


问:
How do I test if my website prevented Clickjacking?
I was asked to check how to prevent Clickjacking on our website.

I did some research and this is what I understand, please correct me if I'm wrong:
The attacker will use iframe to layer their website over your website, then make their iframe transparent.
When user click on a button on our website, they are actually clicking on hacker website.
To prevent this, disable iframe on our website.

I went to this website to check, but I got this error:

Couldn’t find the X-Frame-Options header
in the response headers.

What it means? I'm not sure.

I also searched online and found that you need to add this code in .htaccess

```<code>    <IfModule mod_headers.c>
  Header always append X-Frame-Options SAMEORIGIN
</IfModule>
</code>```

But how do I know if it works?

答:
Clickjacking is about an attacker using an iframe on their website to include yours, with tricks like making your website's iframe transparent. The point is that if a user is logged on to your website (the victim), your website will load the user's content, and the attacker can visually position elements on their website (over your invisible website's iframe for example) so that an unsuspecting user visiting the attacker website will click things in your application. This works, because without further protection of the authentication token (eg. session cookie), your website will just load the user's authenticated content in the iframe.

You could argue that if it loads in the iframe on the attacker's site, why don't they just read or do whatever they want. That's not possible though, because the same origin policy prevents javascript on the attacker's origin from accessing content from another origin (yours), even if it's on the same page in an iframe. But they can possibly make the user perform actions by inadvertently clicking stuff they didn't want to.

This was used to gather likes on Facebook for example, Facebook was loaded in an invisible iframe on malicious sites, and then something like an advertisement's close button was positioned right over a Facebook like button - you tried to close the annoying ad, and in fact liked something you didn't want to.

One protection against this is that your app (or Facebook in the example above) should not allow itself being displayed in an iframe. And that's exactly what X-Frame-Options does. With the value 'deny' it will just never be displayed in an iframe, with 'sameorigin' your own origin (~domain name) can display parts of itself in iframes, but other origins cannot (so an attacker cannot include your site on a different domain).

X-Frame-Options is an http response header, so to check that it works, you can use the network tab of the developer tools in your browser. In most browsers you hit F12, choose the network tab, load your website, find and click the initial request that downloaded the actual page, and you can inspect the list of response headers. That should include X-Frame-Options with the value 'deny' or 'sameorigin'.

You can also use online tools to perform these simple scans (see the other answer for an example), but I think it's worth to actually understand what and why you're doing.

Body:
I was asked to check how to prevent Clickjacking on our website.

I did some research and this is what I understand, please correct me if I'm wrong:
The attacker will use iframe to layer their website over your website, then make their iframe transparent.
When user click on a button on our website, they are actually clicking on hacker website.
To prevent this, disable iframe on our website.

I went to this website to check, but I got this error:

Couldn’t find the X-Frame-Options header
in the response headers.

What it means? I'm not sure.

I also searched online and found that you need to add this code in .htaccess

    <IfModule mod_headers.c>
  Header always append X-Frame-Options SAMEORIGIN
</IfModule>

But how do I know if it works?


问:
Pass user defined variable in function written in JSR223 Sampler
How Can I pass User defined variable while calling function having parameters. (Function is created in JSR223 Sampler). And I need to call this function with user defined variable as parameter in next HTTP request as Server Name/IP/URL.</p>

答:
Put your Groovy code into utility.groovy file in "bin" folder of your JMeter installation. If you want to use the different file - define groovy.utilities JMeter property in user.properties file pointing to the file containing your Groovy function

There is vars shorthand for JMeterVariables class instance which can be used for accessing any JMeter Variable value so the variable can be read as vars.get('variable-name')

You can call your function using __groovy() JMeter Function like:

```<code> ${__groovy(your-function-here(vars.get('your-variable-here'),)}
</code>```

More information: Advanced Groovy Scripting configuration

Body:
Put your Groovy code into utility.groovy file in "bin" folder of your JMeter installation. If you want to use the different file - define groovy.utilities JMeter property in user.properties file pointing to the file containing your Groovy function

There is vars shorthand for JMeterVariables class instance which can be used for accessing any JMeter Variable value so the variable can be read as vars.get('variable-name')

You can call your function using __groovy() JMeter Function like:

 ${__groovy(your-function-here(vars.get('your-variable-here'),)}

More information: Advanced Groovy Scripting configuration