问:
only pull rows for today's date from dataframe
I'm pulling data from an API and placing it into a Pandas dataframe. I want to then create a new df that includes only the rows that have today's date in. I know how to select between two static dates, but can't seem to filter by a 'today' timestamp.</p>
```<code>from matplotlib import pyplot as plt

#Access API
r = requests.get('REMOVED')
x = r.json()
keys = x.keys()
old_df = pd.DataFrame(x['results'])

#set dataframe
df = old_df[['valid_from','valid_to','value_inc_vat']].copy()

df['valid_from'] = pd.to_datetime(df['valid_from'])
df['valid_to'] = pd.to_datetime(df['valid_to'])

#only today's rows
today = pd.Timestamp.today().date()
mask = (df['from'] == today)
df_today = df.loc[mask]```
</code>```

答:
Use Series.dt.date for compare by dates:

```<code>mask = (df['from'].dt.date == today)
df_today = df[mask]
</code>```

Body:
I'm pulling data from an API and placing it into a Pandas dataframe. I want to then create a new df that includes only the rows that have today's date in. I know how to select between two static dates, but can't seem to filter by a 'today' timestamp.

from matplotlib import pyplot as plt

#Access API
r = requests.get('REMOVED')
x = r.json()
keys = x.keys()
old_df = pd.DataFrame(x['results'])

#set dataframe
df = old_df[['valid_from','valid_to','value_inc_vat']].copy()

df['valid_from'] = pd.to_datetime(df['valid_from'])
df['valid_to'] = pd.to_datetime(df['valid_to'])

#only today's rows
today = pd.Timestamp.today().date()
mask = (df['from'] == today)
df_today = df.loc[mask]```

Body:
Use Series.dt.date for compare by dates:

mask = (df['from'].dt.date == today)
df_today = df[mask]


来源: stackexchange

问:
Why is there a memory leak?
I need to create a large image (w <= 20k, h <= 100k)
I divide it into fragments (w = 20k, h = 5k) and store them in the database in a loop.
But I still get an out of memory error. in the heap 1.5 gigabytes.
Why is there a memory leak? According to my plan, only the current fragment, which weighs about 300 megabytes, should be stored in the heap.

```<code>@Transactional
public long createNewChart (int width, int height) {
    Chartographer chartographer = new Chartographer(width, height);
    chartRepo.save(chartographer);

    int number = 0;
    while (height >= 5000) {
        BufferedImage fragment = new BufferedImage(width, 5000, BufferedImage.TYPE_INT_RGB);
        fragmentRepo.save(new Fragment(imageOperator.imageAsBytes(fragment), number, chartographer));
        height -= 5000;
        number++;
    }
    if (height > 0) {
        BufferedImage fragment = new BufferedImage(width, height % 5000, BufferedImage.TYPE_INT_RGB);
        fragmentRepo.save(new Fragment(imageOperator.imageAsBytes(fragment), number, chartographer));
    }
    return chartographer.getCharId();
}

public byte[] imageAsBytes (BufferedImage image) {
    try(ByteArrayOutputStream stream = new ByteArrayOutputStream()) {
        ImageIO.write(image, "bmp", stream);
        return stream.toByteArray();
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}
</code>```

enter image description here

答:
IMHO you are underestimating your heap space requirement.

For 20_000 by 5_000 pixels the BufferedImage needs at least 400 MB (100_000_000 pixels at 4 bytes per pixel)

ByteArrayOutputStream starts with a buffer size of 32 bytes and increases the buffer size every time when there is not enough room for writing data, at least doubling the size of the buffer every time

in my test the final buffer size in the ByteArrayOutputStream was 536_870_912

because that was size was probably reached by doubling the previous size, it temporarily needed 1.5 times that memory

the final byte array another 300_000_054 bytes to store the final byte array.

The critical point in memory consumption is the line return stream.toByteArray();:

the BufferedImage cannot be garbage collected (400MB)

the ByteArrayOutputStream contains a buffer of about 540MB

the memory for the final byte array needs to be allocated (another 300MB)

giving a total needed memory at that specific point of 1240MB for the image processing alone (not taking into account all the memory that the rest of your application consumes)

You can somewhat reduce the needed memory by presizing the ByteArrayOutputStream (by about 240MB):

```<code>public byte[] imageAsBytes (BufferedImage image) {
    int imageSize = image.getWidth()*image.getHeight()*3 + 54; // 54 bytes for the BMP header
    try (ByteArrayOutputStream stream = new ByteArrayOutputStream(imageSize)) {
        ImageIO.write(image, "bmp", stream);
        return stream.toByteArray();
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}
</code>```

Another problem:

The method createNewChart() is marked as @Transactional. I don't know about your database, the technology that you use for database access and transaction management (JPA?) or how the pictures are effectively stored in the database (BLOB? base64 encoded?).

Most probably the whole database stack (and in this term I include the persistence framework like JPA too) keeps all the pictures in memory until the whole transaction is commited.

To verify this assumption you could remove the @Transactional attribute from createNewChart() so that the chart and the fragments are stored into the database in different transactions.

So it seems that something in your application holds references to memory when you expect them to be freed. Diagnosing this just from the source code alone is (IMHO) impossible - it could be something that you have written, it could be something in a library that you use.

To detect what keeps those references you should as a first step create a heap dump when the OutOfMemoryError is raised. You can do this by adding -XX:+HeapDumpOnOutOfMemoryError to the JVM options like this:

```<code>java -XX:+HeapDumpOnOutOfMemoryError -Xmx3G ..remaining start options..
</code>```

This will produce a java_pid<somenumber>.hprof file when the OutOfMemoryError occurs.

The next step is then analyzing this file to find out what is referencing the memory. What works for me is the Eclipse Memory Analyzer (it is maintained by the Eclipse Foundation but you can use it for all heap dumps). Loading the previously generated heap dump into this tool gives a good overview into what is still referencing the images.

The next step would then be to find out why those references are still there.

ContentLicense: CC BY-SA 4.0

Title: Why is there a memory leak?

Body:
I need to create a large image (w <= 20k, h <= 100k)
I divide it into fragments (w = 20k, h = 5k) and store them in the database in a loop.
But I still get an out of memory error. in the heap 1.5 gigabytes.
Why is there a memory leak? According to my plan, only the current fragment, which weighs about 300 megabytes, should be stored in the heap.

@Transactional
public long createNewChart (int width, int height) {
    Chartographer chartographer = new Chartographer(width, height);
    chartRepo.save(chartographer);

    int number = 0;
    while (height >= 5000) {
        BufferedImage fragment = new BufferedImage(width, 5000, BufferedImage.TYPE_INT_RGB);
        fragmentRepo.save(new Fragment(imageOperator.imageAsBytes(fragment), number, chartographer));
        height -= 5000;
        number++;
    }
    if (height > 0) {
        BufferedImage fragment = new BufferedImage(width, height % 5000, BufferedImage.TYPE_INT_RGB);
        fragmentRepo.save(new Fragment(imageOperator.imageAsBytes(fragment), number, chartographer));
    }
    return chartographer.getCharId();
}

public byte[] imageAsBytes (BufferedImage image) {
    try(ByteArrayOutputStream stream = new ByteArrayOutputStream()) {
        ImageIO.write(image, "bmp", stream);
        return stream.toByteArray();
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}

enter image description here

Body:
IMHO you are underestimating your heap space requirement.

For 20_000 by 5_000 pixels the BufferedImage needs at least 400 MB (100_000_000 pixels at 4 bytes per pixel)

ByteArrayOutputStream starts with a buffer size of 32 bytes and increases the buffer size every time when there is not enough room for writing data, at least doubling the size of the buffer every time

in my test the final buffer size in the ByteArrayOutputStream was 536_870_912

because that was size was probably reached by doubling the previous size, it temporarily needed 1.5 times that memory

the final byte array another 300_000_054 bytes to store the final byte array.

The critical point in memory consumption is the line return stream.toByteArray();:

the BufferedImage cannot be garbage collected (400MB)

the ByteArrayOutputStream contains a buffer of about 540MB

the memory for the final byte array needs to be allocated (another 300MB)

giving a total needed memory at that specific point of 1240MB for the image processing alone (not taking into account all the memory that the rest of your application consumes)

You can somewhat reduce the needed memory by presizing the ByteArrayOutputStream (by about 240MB):

public byte[] imageAsBytes (BufferedImage image) {
    int imageSize = image.getWidth()*image.getHeight()*3 + 54; // 54 bytes for the BMP header
    try (ByteArrayOutputStream stream = new ByteArrayOutputStream(imageSize)) {
        ImageIO.write(image, "bmp", stream);
        return stream.toByteArray();
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}

Another problem:

The method createNewChart() is marked as @Transactional. I don't know about your database, the technology that you use for database access and transaction management (JPA?) or how the pictures are effectively stored in the database (BLOB? base64 encoded?).

Most probably the whole database stack (and in this term I include the persistence framework like JPA too) keeps all the pictures in memory until the whole transaction is commited.

To verify this assumption you could remove the @Transactional attribute from createNewChart() so that the chart and the fragments are stored into the database in different transactions.

So it seems that something in your application holds references to memory when you expect them to be freed. Diagnosing this just from the source code alone is (IMHO) impossible - it could be something that you have written, it could be something in a library that you use.

To detect what keeps those references you should as a first step create a heap dump when the OutOfMemoryError is raised. You can do this by adding -XX:+HeapDumpOnOutOfMemoryError to the JVM options like this:

java -XX:+HeapDumpOnOutOfMemoryError -Xmx3G ..remaining start options..

This will produce a java_pid<somenumber>.hprof file when the OutOfMemoryError occurs.

The next step is then analyzing this file to find out what is referencing the memory. What works for me is the Eclipse Memory Analyzer (it is maintained by the Eclipse Foundation but you can use it for all heap dumps). Loading the previously generated heap dump into this tool gives a good overview into what is still referencing the images.

The next step would then be to find out why those references are still there.


问:
Cannot update UI using the UI thread Dispatcher?
I designed a WPF application based on MVVM pattern and I need to get large amount of data from a webservice, and i do it with a BackgroundWorker inside the ViewModel. To modify the observable collection i have to use a dispatcher and the problem is here, even if i pass by reference UI Dispatcher it dosen't work, it is like I use the inner dispatcher and my application get freezed until all data are retrived.

I try to get the UI Dispatcher in several ways, Dispatcher.CurrentDispatcher, Application.Dispatcher, App.Current.Dispatcher... doing some researches I read that it should be works, does someone have any suggestions?

Thank you
Marco

Update

Here some code: This is how I pass the Dispatcher to the ModelView

```<code>void AppWindow_Loaded(object sender, RoutedEventArgs e)
{
     this.DataContext = new ModelViewApplication(System.Windows.Threading.Dispatcher.CurrentDispatcher);
}
</code>```

Then I try to get data in this way

```<code>public ModelViewApplication(Dispatcher _dispatcher)
{
    BackgroundWorker bw = new BackgroundWorker();
    bw.DoWork += new DoWorkEventHandler(getData);
    bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(completedData);

    bw.RunWorkerAsync();
}

public void getData(object sender, DoWorkEventArgs e)
{
    _dispatcher.Invoke(DispatcherPriority.Normal,
        new Action(
            delegate()
                 {
                 //Connect to webservice and retrieve data
                 ....
                 }));
}
</code>```

It seems like the multithread dosen't work

答:
Here is a sample which may help you implementing the task and UI Updates. You can easily convert the following sample to you scenario.
You can have a look at my blog which has detailed Explanation regarding this error and solution

http://bathinenivenkatesh.blogspot.com/2011/07/wpf-build-more-responsive-ui.html

```<code>ObservableCollection images = new ObservableCollection();
TaskFactory tFactory = new TaskFactory();
tFactory.StartNew(() =>
{
    for (int i = 0; i < 50; i++)
    {
        //GET IMAGE Path FROM SERVER
        System.Windows.Application.Current.Dispatcher.BeginInvoke((Action)delegate()
        {
            // UPDATE PROGRESS BAR IN UI
        });

        images.Add(("");
    }

}).ContinueWith(t =>
{
    if (t.IsFaulted)
    {
        // EXCEPTION IF THREAD IS FAULT
        throw t.Exception;
    }
    System.Windows.Application.Current.Dispatcher.BeginInvoke((Action)delegate()
    {
        //PROCESS IMAGES AND DISPLAY
    });
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I designed a WPF application based on MVVM pattern and I need to get large amount of data from a webservice, and i do it with a BackgroundWorker inside the ViewModel. To modify the observable collection i have to use a dispatcher and the problem is here, even if i pass by reference UI Dispatcher it dosen't work, it is like I use the inner dispatcher and my application get freezed until all data are retrived.

I try to get the UI Dispatcher in several ways, Dispatcher.CurrentDispatcher, Application.Dispatcher, App.Current.Dispatcher... doing some researches I read that it should be works, does someone have any suggestions?

Thank you
Marco

Update

Here some code: This is how I pass the Dispatcher to the ModelView

void AppWindow_Loaded(object sender, RoutedEventArgs e)
{
     this.DataContext = new ModelViewApplication(System.Windows.Threading.Dispatcher.CurrentDispatcher);
}

Then I try to get data in this way

public ModelViewApplication(Dispatcher _dispatcher)
{
    BackgroundWorker bw = new BackgroundWorker();
    bw.DoWork += new DoWorkEventHandler(getData);
    bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(completedData);

    bw.RunWorkerAsync();
}

public void getData(object sender, DoWorkEventArgs e)
{
    _dispatcher.Invoke(DispatcherPriority.Normal,
        new Action(
            delegate()
                 {
                 //Connect to webservice and retrieve data
                 ....
                 }));
}

It seems like the multithread dosen't work

Body:
Here is a sample which may help you implementing the task and UI Updates. You can easily convert the following sample to you scenario.
You can have a look at my blog which has detailed Explanation regarding this error and solution

http://bathinenivenkatesh.blogspot.com/2011/07/wpf-build-more-responsive-ui.html

ObservableCollection images = new ObservableCollection();
TaskFactory tFactory = new TaskFactory();
tFactory.StartNew(() =>
{
    for (int i = 0; i < 50; i++)
    {
        //GET IMAGE Path FROM SERVER
        System.Windows.Application.Current.Dispatcher.BeginInvoke((Action)delegate()
        {
            // UPDATE PROGRESS BAR IN UI
        });

        images.Add(("");
    }

}).ContinueWith(t =>
{
    if (t.IsFaulted)
    {
        // EXCEPTION IF THREAD IS FAULT
        throw t.Exception;
    }
    System.Windows.Application.Current.Dispatcher.BeginInvoke((Action)delegate()
    {
        //PROCESS IMAGES AND DISPLAY
    });
});


问:
Convert specific fields before mapping in controller
I need to convert two specific fields before mapping to Dto class.
Data i get from form:

```<code>userName: test
password: 123
active: N
enabled: N
external: N
id: -1
</code>```

Dto class:

```<code>@Getter @Setter
public class UserDto {
    protected Integer id;
    protected String userName;
    protected String password;
    protected boolean active = false;
    protected boolean enabled = true;
    protected String external;
}
</code>```

Fields active and enabled are a boolean type, but from form i get "Y" or "N" string values. Cause of it, i got an error Failed to convert property value of type 'java.lang.String' to required type 'boolean' for property 'active'; nested exception is java.lang.IllegalArgumentException: Invalid boolean value [N]

I've read about the Сonverter<T,V> and PropertyEditors, but I'm not sure if they work for me and how can i apply it only for 2 specific fields.

Controller:

```<code>    @RequestMapping(value = "/user/save",method = RequestMethod.POST)
    public ResponseEntity<String> saveUser(@ModelAttribute UserDto userDto, BindingResult bindingResultM, HttpServletRequest req) {

        List<FieldError> errors = bindingResultM.getFieldErrors();
        for (FieldError error : errors) {
            log.error("bindingResultM: " + error.getObjectName() + " - " + error.getDefaultMessage());
        }
        try {
            userService.saveUserDto(userDto);
            return new ResponseEntity<>("OK", HttpStatus.OK);
        } catch (Exception e){
            throw new ResponseException(e.getMessage(), HttpStatus.METHOD_FAILURE);
        }
    }
</code>```

答:
On your DTO you can annotate your boolean fields with :

```<code>    @JsonDeserialize(
        using = BooleanDeserializer.class
    )
    protected boolean enabled;
</code>```

And create the deserializer :

```<code>public class BooleanDeserializer extends JsonDeserializer<Boolean> {

    public Boolean deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        String booleanValue = StringUtils.trimToEmpty(jsonParser.getText().trim());
        return BooleanUtils.toBoolean(booleanValue, "Y", "N");
    }
}
</code>```

Body:
I need to convert two specific fields before mapping to Dto class.
Data i get from form:

userName: test
password: 123
active: N
enabled: N
external: N
id: -1

Dto class:

@Getter @Setter
public class UserDto {
    protected Integer id;
    protected String userName;
    protected String password;
    protected boolean active = false;
    protected boolean enabled = true;
    protected String external;
}

Fields active and enabled are a boolean type, but from form i get "Y" or "N" string values. Cause of it, i got an error Failed to convert property value of type 'java.lang.String' to required type 'boolean' for property 'active'; nested exception is java.lang.IllegalArgumentException: Invalid boolean value [N]

I've read about the Сonverter<T,V> and PropertyEditors, but I'm not sure if they work for me and how can i apply it only for 2 specific fields.

Controller:

    @RequestMapping(value = "/user/save",method = RequestMethod.POST)
    public ResponseEntity<String> saveUser(@ModelAttribute UserDto userDto, BindingResult bindingResultM, HttpServletRequest req) {

        List<FieldError> errors = bindingResultM.getFieldErrors();
        for (FieldError error : errors) {
            log.error("bindingResultM: " + error.getObjectName() + " - " + error.getDefaultMessage());
        }
        try {
            userService.saveUserDto(userDto);
            return new ResponseEntity<>("OK", HttpStatus.OK);
        } catch (Exception e){
            throw new ResponseException(e.getMessage(), HttpStatus.METHOD_FAILURE);
        }
    }

Body:
On your DTO you can annotate your boolean fields with :

    @JsonDeserialize(
        using = BooleanDeserializer.class
    )
    protected boolean enabled;

And create the deserializer :

public class BooleanDeserializer extends JsonDeserializer<Boolean> {

    public Boolean deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        String booleanValue = StringUtils.trimToEmpty(jsonParser.getText().trim());
        return BooleanUtils.toBoolean(booleanValue, "Y", "N");
    }
}


问:
using YAML to get input from the user and converting it to dictionary in python
I have to get inputs from the user in YAML form but I can't use any external files, then I have to convert the inputs to dictionaries in which the header would be the key and other elements would be the value stored in a list.

for example, if the input is:

```<code>- name: ali
  age: 12
  city: bushehr
  albums:
    - bidad
    - blaze
</code>```

the answer should be:

```<code>{'Ali': (12, 'Bushehr', ['bidad', 'blaze'])}
</code>```

or for example, if the input is:

```<code>- name: bidad
  singer: shajarian
  genre: classic
  tracks: 10
- name: blaze
  singer: ghorbani
  genre: pop
  tracks: 9
</code>```

the answer should be :

```<code>{'bidad': ('shajarian', 'classic', 10), 'blaze': ('ghorbani', 'pop', 9)}
</code>```

a hand would mean the world to me, thanks in advance.

答:
Use PyYAML after get user input:

```<code># pip install pyyaml
import yaml

data = []

print('Input your data (blank line to quit): ')
while True:
    line = input()
    if line == '':
        break
    data.append(line)
data = yaml.load('\n'.join(data), yaml.SafeLoader)
print(data)
</code>```

Output:

```<code>Input your data (blank line to quit):
- name: ali
  age: 12
  city: bushehr
  albums:
    - bidad
    - blaze

[{'name': 'ali', 'age': 12, 'city': 'bushehr', 'albums': ['bidad', 'blaze']}]
</code>```

Body:
I have to get inputs from the user in YAML form but I can't use any external files, then I have to convert the inputs to dictionaries in which the header would be the key and other elements would be the value stored in a list.

for example, if the input is:

- name: ali
  age: 12
  city: bushehr
  albums:
    - bidad
    - blaze

the answer should be:

{'Ali': (12, 'Bushehr', ['bidad', 'blaze'])}

or for example, if the input is:

- name: bidad
  singer: shajarian
  genre: classic
  tracks: 10
- name: blaze
  singer: ghorbani
  genre: pop
  tracks: 9

the answer should be :

{'bidad': ('shajarian', 'classic', 10), 'blaze': ('ghorbani', 'pop', 9)}

a hand would mean the world to me, thanks in advance.

Body:
Use PyYAML after get user input:

# pip install pyyaml
import yaml

data = []

print('Input your data (blank line to quit): ')
while True:
    line = input()
    if line == '':
        break
    data.append(line)
data = yaml.load('\n'.join(data), yaml.SafeLoader)
print(data)

Output:

Input your data (blank line to quit):
- name: ali
  age: 12
  city: bushehr
  albums:
    - bidad
    - blaze

[{'name': 'ali', 'age': 12, 'city': 'bushehr', 'albums': ['bidad', 'blaze']}]


问:
RobustScaler in PySpark
I would like to use a RobustScaler for preprocessing data. In sklearn it can be found in

```<code>sklearn.preprocessing.RobustScaler
</code>```

. However, I am using pyspark, so I tried to import it with:

```<code> from pyspark.ml.feature import RobustScaler
</code>```

However, I receive the following error:

```<code>ImportError: cannot import name 'RobustScaler' from 'pyspark.ml.feature'
</code>```

As pault pointed out, RobustScaler is implemented only in pyspark 3.  I am trying to implement it as:

```<code>class PySpark_RobustScaler(Pipeline):
    def __init__(self):
        pass

    def fit(self, df):
        return self

    def transform(self, df):
        self._df = df
        for col_name in self._df.columns:
            q1, q2, q3 = self._df.approxQuantile(col_name, [0.25, 0.5, 0.75], 0.00)
            self._df = self._df.withColumn(col_name, 2.0*(sf.col(col_name)-q2)/(q3-q1))
        return self._df

arr = np.array(
            [[ 1., -2.,  2.],
            [ -2.,  1.,  3.],
            [ 4.,  1., -2.]]
          )

rdd1 = sc.parallelize(arr)
rdd2 = rdd1.map(lambda x: [int(i) for i in x])
df_sprk = rdd2.toDF(["A", "B", "C"])
df_pd = pd.DataFrame(arr, columns=list('ABC'))

PySpark_RobustScaler().fit(df_sprk).transform(df_sprk).show()
print(RobustScaler().fit(df_pd).transform(df_pd))
</code>```

However I have found that to obtain the same result of sklearn I have to multiply the result by 2. Furthermore, I am worried that if a column has many values close to zero, the interquartile range q3-q1 could become too small and let the result diverge, creating null values.

Does anyone have any suggestions on how to improve it?

答: This feature has been released in recent pyspark versions.</p>

Title: RobustScaler in PySpark

Body:
I would like to use a RobustScaler for preprocessing data. In sklearn it can be found in

sklearn.preprocessing.RobustScaler

. However, I am using pyspark, so I tried to import it with:

 from pyspark.ml.feature import RobustScaler

However, I receive the following error:

ImportError: cannot import name 'RobustScaler' from 'pyspark.ml.feature'

As pault pointed out, RobustScaler is implemented only in pyspark 3.  I am trying to implement it as:

class PySpark_RobustScaler(Pipeline):
    def __init__(self):
        pass

    def fit(self, df):
        return self

    def transform(self, df):
        self._df = df
        for col_name in self._df.columns:
            q1, q2, q3 = self._df.approxQuantile(col_name, [0.25, 0.5, 0.75], 0.00)
            self._df = self._df.withColumn(col_name, 2.0*(sf.col(col_name)-q2)/(q3-q1))
        return self._df

arr = np.array(
            [[ 1., -2.,  2.],
            [ -2.,  1.,  3.],
            [ 4.,  1., -2.]]
          )

rdd1 = sc.parallelize(arr)
rdd2 = rdd1.map(lambda x: [int(i) for i in x])
df_sprk = rdd2.toDF(["A", "B", "C"])
df_pd = pd.DataFrame(arr, columns=list('ABC'))

PySpark_RobustScaler().fit(df_sprk).transform(df_sprk).show()
print(RobustScaler().fit(df_pd).transform(df_pd))

However I have found that to obtain the same result of sklearn I have to multiply the result by 2. Furthermore, I am worried that if a column has many values close to zero, the interquartile range q3-q1 could become too small and let the result diverge, creating null values.

Does anyone have any suggestions on how to improve it?


问:
run bootstrap action after application software installed on EMR cluster
Is there a way to run bootstrap action after application software (eg: spark) is installed?
My purpose is to replace one of the AWS spark jar with my customized spark jar and this must be done after AWS install it original spark.

The reason I don't do this via normal step is because I want to perform this replacement on all nodes of the cluster, not just on the master node.

答:
Though this question is old, I got it to work and adding answer for people who still need help with this. As in comment above, my configuration with which its tested is:

Release label:emr-5.30.1 Hadoop distribution:Amazon 2.8.5 Applications:spark 2.4.5

The issue really is that Bootstrap on AWS EMR gets executed BEFORE your software like Spark are installed.

Solution: Do it in two steps

Add a bootstrap script to run your second script as a background process. This completes the bootstrap as well as gives you more ability to WAIT for installations to happen. Following example script takes two parameters, S3 bucket path and environment prefix and shows how they are passed along to the next script.

```<code>#!/bin/bash

aws s3 cp $1/$2/some/path/to/second/script/emr_second_script.sh .
chmod +x emr_second_script.sh
nohup ./emr_second_script.sh $1 $2 &>/dev/null &
</code>```

Write your second script, that first one is running in background. In this script check for the installation directory to appear otherwise wait/sleep. Once that condition is met, do your required magic. Following example script takes two parameters, S3 bucket path and environment prefix.

```<code>#!/bin/bash

while [ ! -e /lib/spark/jars/ ]
do
  echo "Spark installation not found, waiting..."
  sleep 15
done
echo "Spark installation found."
# Do your actual scripting work here. e.g. Copy jars from S3.
enter code here
sudo aws s3 cp $1/$2/path/to/my/jar/my-jar-1.0.jar --region us-east-1 /lib/spark/jars
exit(0)
</code>```

You can find the same solution to solve slightly different problem here.

Body:
Though this question is old, I got it to work and adding answer for people who still need help with this. As in comment above, my configuration with which its tested is:

Release label:emr-5.30.1 Hadoop distribution:Amazon 2.8.5 Applications:spark 2.4.5

The issue really is that Bootstrap on AWS EMR gets executed BEFORE your software like Spark are installed.

Solution: Do it in two steps

Add a bootstrap script to run your second script as a background process. This completes the bootstrap as well as gives you more ability to WAIT for installations to happen. Following example script takes two parameters, S3 bucket path and environment prefix and shows how they are passed along to the next script.

#!/bin/bash

aws s3 cp $1/$2/some/path/to/second/script/emr_second_script.sh .
chmod +x emr_second_script.sh
nohup ./emr_second_script.sh $1 $2 &>/dev/null &

Write your second script, that first one is running in background. In this script check for the installation directory to appear otherwise wait/sleep. Once that condition is met, do your required magic. Following example script takes two parameters, S3 bucket path and environment prefix.

#!/bin/bash

while [ ! -e /lib/spark/jars/ ]
do
  echo "Spark installation not found, waiting..."
  sleep 15
done
echo "Spark installation found."
# Do your actual scripting work here. e.g. Copy jars from S3.
enter code here
sudo aws s3 cp $1/$2/path/to/my/jar/my-jar-1.0.jar --region us-east-1 /lib/spark/jars
exit(0)

You can find the same solution to solve slightly different problem here.


问:
Giving a local method a referenced argument
I am passing a ref var to a method, and within the method I have a local method I'd like to ref the var that I passed to the initial method. Example below

```<code>private void SomeMethod(ref var refdVar, var someThing)
{
    //do something
    //then call the method below
    LocalMethod(refdVar);

   void LocalMethod(ref var refdVar)
   {
       refdVar = someThing;
   }
}
</code>```

Is this possible to do, if not, what are the options (I don't want to globally change the var, just because I find it cleaner by changing ref)?

答:
I am not completely sure what you are trying to do but maybe a generic method could be what you are looking for : https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/generic-methods

```<code>private void SomeMethod<T>(ref T refdVar, T someThing)
{
  //do something
  //then call the method below
  LocalMethod(ref refdVar);

  void LocalMethod(ref T refdVar1)
  {
    refdVar1 = someThing;
  }
}
....
....
int x = 3;
SomeMethod(ref x, 4);
double y = 5.0;
SomeMethod(ref y, 7.0);
</code>```

Also note that the parameter refdVar is in scope inside the local parameter, so you should give that parameter a different name to avoid a compiler warning.

Body:
I am passing a ref var to a method, and within the method I have a local method I'd like to ref the var that I passed to the initial method. Example below

private void SomeMethod(ref var refdVar, var someThing)
{
    //do something
    //then call the method below
    LocalMethod(refdVar);

   void LocalMethod(ref var refdVar)
   {
       refdVar = someThing;
   }
}

Is this possible to do, if not, what are the options (I don't want to globally change the var, just because I find it cleaner by changing ref)?

Body:
I am not completely sure what you are trying to do but maybe a generic method could be what you are looking for : https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/generic-methods

private void SomeMethod<T>(ref T refdVar, T someThing)
{
  //do something
  //then call the method below
  LocalMethod(ref refdVar);

  void LocalMethod(ref T refdVar1)
  {
    refdVar1 = someThing;
  }
}
....
....
int x = 3;
SomeMethod(ref x, 4);
double y = 5.0;
SomeMethod(ref y, 7.0);

Also note that the parameter refdVar is in scope inside the local parameter, so you should give that parameter a different name to avoid a compiler warning.


问:
How do I create a release build in Xcode?
Why is it that when I build an application, Xcode creates a debug build? I want to create a release build. How can I do this?</p>

答:
Here is my 'more detailed' list of steps for creating a release build > (Working on a team and a project that has many schemes and environments)

checkout a new branch like releases/x.x.x that contains all changes. (x.x.x is the version) (Its more about your team conventions)

Check to make sure your app bundleIdentifier is correct (might differ for each environment)

Team/account/licence: log into correct account that has provisioning profiles. then under signing and capabilities make sure your Team is correctly selected and has all certificates needed

Upgrade the version in project settings to x.x.x

Make sure the scheme you selected is correct

Make sure the URLs of API calls are pointing to your release environment

Its better to select 'Any iOS device' instead of a simulator or actual device

Commit any changes locally if you have any (this step is very important)

Validate to make sure all is good

Create an archive

Distribute your app for AppStore Connect

I use an apple proxy named 'transporter' that is pretty easy for uploading iPA to Appstore

Happy releasing!


问:
How do getters and setters work in Python?
I am learning getters and setters , what I understand is that they are used so that no one could change the object's attributes directly. In the example

```<code>class Person:
    def __init__(self, name, age):
        self._name = name
        self._age = age

    def get_age(self):
        return self._age

    def set_age(self, new_age):
        if isinstance(new_age, int) & new_age>0 & new_age<120:
            self._age = new_age

    def get_name(self):
        return self._name

    def __str__(self):
        return 'Person[' + self._name + '] is ' + str(self._age)

p1 = Person("Sandeep", 49)
</code>```

I created an object p1 where I set the age 49. As I have made a set_age function so I expect we can change the age of p1 through set_age only, not through the routine way. But it is not happening, I am able to change the age of p1 through , for example, p1._age = 35 as well. Then, what is the advantage to make set_age function, if I am still able to access the attributes directly?

I think, I am missing something, please help.

答: Now I realise that I asked a silly question. The reason is obvious of using setters, creating functions for setting a value is a very convenient way to apply the constraints on it. In the example above, the constraint is that the age of the person should be positive and less than 120. Implementation of such constraints is not possible without setters.

Body:
I am learning getters and setters , what I understand is that they are used so that no one could change the object's attributes directly. In the example

class Person:
    def __init__(self, name, age):
        self._name = name
        self._age = age

    def get_age(self):
        return self._age

    def set_age(self, new_age):
        if isinstance(new_age, int) & new_age>0 & new_age<120:
            self._age = new_age

    def get_name(self):
        return self._name

    def __str__(self):
        return 'Person[' + self._name + '] is ' + str(self._age)

p1 = Person("Sandeep", 49)

I created an object p1 where I set the age 49. As I have made a set_age function so I expect we can change the age of p1 through set_age only, not through the routine way. But it is not happening, I am able to change the age of p1 through , for example, p1._age = 35 as well. Then, what is the advantage to make set_age function, if I am still able to access the attributes directly?

I think, I am missing something, please help.


问:
Populate a list using jQuery from an AJAX as autocomplete
I've got a JSON file with a list of items. Each item has an ID and a name such as

```<code>{ID : 11, Name: 'item 1'}
</code>```

I'm using the jQuery Mobile framework where I need to put a textbox where users can start typing an item name and the list should populate items from the file with the letters inside (some sort of autocomplete).

BTW - the list is VERY long (thousands of items) so I wouldn't like to load it all at once.

Any ideas how this can be accomplished?

Thanks!

答:
I would create a function to return the result set based upon the "terms" in the phrase entry.

An example would be to use the source: of the jQuery UI Autocomplete and then filter your json data (cached on load?) based on the occurence. Something similar to breaking the phrase with a string split and iterating over that like with jQuery(':contains(text)') comes to mind.

If your json is an array jQuery.grep() might be perfectly suited. http://api.jquery.com/jQuery.grep

Here is another example in this question: How can I "filter" JSON for unique key name/value pairs?

Couple of other options in the answers here: json jquery filter javascript array

Body:
I've got a JSON file with a list of items. Each item has an ID and a name such as

{ID : 11, Name: 'item 1'}

I'm using the jQuery Mobile framework where I need to put a textbox where users can start typing an item name and the list should populate items from the file with the letters inside (some sort of autocomplete).

BTW - the list is VERY long (thousands of items) so I wouldn't like to load it all at once.

Any ideas how this can be accomplished?

Thanks!


问:
Swagger 3 Required Global Request Parameter
I am using Spring Boot 2.5.4 with Swagger 3. I have added one Global Request Parameter as type header and required=true in Swagger Config file .
Swagger UI is correctly showing the required request header in all APIs but the problem is that it's allowing requests to be sent when the value is empty for required request header. In Swagger 2 , UI used to disable sending request until the value was filled.

Any suggestions.

```<code>@Bean
    public Docket api() {

        RequestParameterBuilder aParameterBuilder = new RequestParameterBuilder();
        aParameterBuilder.name("x-remote-user").description("Remote User").in(ParameterType.HEADER).required(true)
                .build();

        List<RequestParameter> aParameters = new ArrayList<>();
        aParameters.add(aParameterBuilder.build());
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
                .securityContexts(Arrays.asList(securityContext())).securitySchemes(Arrays.asList(apiKey())).select()
                .apis(RequestHandlerSelectors.basePackage("com.xxx.controller"))
                .paths(PathSelectors.ant("/api/**")).build().globalRequestParameters(aParameters);
    }
</code>```

答:
I found out the solution . Posting it here if someone else is looking for it .

If we disallow empty values , then swagger UI starts blocking us from Executing API if header value is kept empty.

```<code>@Bean
    public Docket api() {

        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
                .securityContexts(Arrays.asList(securityContext())).securitySchemes(Arrays.asList(apiKey())).select()
                .apis(RequestHandlerSelectors.basePackage("com.xxx.controller"))
                .paths(PathSelectors.ant("/api/**")).build()
                .globalRequestParameters(Arrays.asList(new RequestParameterBuilder().name("x-remote-user")
                        .description("Remote User").in(ParameterType.HEADER).required(true)
                        .query(simpleParameterSpecificationBuilder -> simpleParameterSpecificationBuilder
                                .allowEmptyValue(false).model(modelSpecificationBuilder -> modelSpecificationBuilder
                                        .scalarModel(ScalarType.STRING)))
                        .build()));
    }
</code>```

Body:
I am using Spring Boot 2.5.4 with Swagger 3. I have added one Global Request Parameter as type header and required=true in Swagger Config file .
Swagger UI is correctly showing the required request header in all APIs but the problem is that it's allowing requests to be sent when the value is empty for required request header. In Swagger 2 , UI used to disable sending request until the value was filled.

Any suggestions.

@Bean
    public Docket api() {

        RequestParameterBuilder aParameterBuilder = new RequestParameterBuilder();
        aParameterBuilder.name("x-remote-user").description("Remote User").in(ParameterType.HEADER).required(true)
                .build();

        List<RequestParameter> aParameters = new ArrayList<>();
        aParameters.add(aParameterBuilder.build());
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
                .securityContexts(Arrays.asList(securityContext())).securitySchemes(Arrays.asList(apiKey())).select()
                .apis(RequestHandlerSelectors.basePackage("com.xxx.controller"))
                .paths(PathSelectors.ant("/api/**")).build().globalRequestParameters(aParameters);
    }

Body:
I found out the solution . Posting it here if someone else is looking for it .

If we disallow empty values , then swagger UI starts blocking us from Executing API if header value is kept empty.

@Bean
    public Docket api() {

        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
                .securityContexts(Arrays.asList(securityContext())).securitySchemes(Arrays.asList(apiKey())).select()
                .apis(RequestHandlerSelectors.basePackage("com.xxx.controller"))
                .paths(PathSelectors.ant("/api/**")).build()
                .globalRequestParameters(Arrays.asList(new RequestParameterBuilder().name("x-remote-user")
                        .description("Remote User").in(ParameterType.HEADER).required(true)
                        .query(simpleParameterSpecificationBuilder -> simpleParameterSpecificationBuilder
                                .allowEmptyValue(false).model(modelSpecificationBuilder -> modelSpecificationBuilder
                                        .scalarModel(ScalarType.STRING)))
                        .build()));
    }


问:
Delete button not visible in Huawei for deleting app
I want to delete the app in Huawei but there is  no button to delete it.</p>

答:
Generally, once the application is released or if it is under review, that app cannot be deleted. But you can remove an released app and it can be found from your released app list and click the version to be removed from sale.

Please use below document link for details on deleting and removing the application.

Link removing the app :
https://developer.huawei.com/consumer/en/doc/distribution/app/agc-help-removeapp-0000001100316676

Link for deleting app : https://developer.huawei.com/consumer/en/doc/distribution/app/agc-help-deleteapp-0000001146716617


问:
Change number in a character when reading columns
I have an input file that looks like:

```<code>text
6
    1w    1     3.450   1.324   2.915
    1w    2     3.450   1.324   2.915
    4w    2     3.458   1.379   2.837
    4w    1     3.458   1.379   2.837
    7w    2     3.364   1.345   2.951
    7w    2     3.364   1.345   2.951
</code>```

and I want the output file to look like:

```<code>text
6
    1w    N      3.450   1.324   2.915
    1w    H1     3.450   1.324   2.915
    4w    H2     3.458   1.379   2.837
    4w    N      3.458   1.379   2.837
    7w    H1     3.364   1.345   2.951
    7w    HW2    3.364   1.345   2.951
</code>```

For the second column, the numbers 1 2 2 1 2 2, I need to print "N" for 1 and "H1" and "H2" for 2 and than again NH1H2, so I mean to tell the program to change once 2 for H1 and then H2. I used

```<code>if(p==1)p="N"
if(p==2)p="H1"
</code>```

but I have no idea how to put do cycle to tell the second 2 is H2 not H1. Can you suggest what to do?

答:
You probably want to keep a running count of the H elements, something like

```<code>program p
  implicit none

  character(2), allocatable :: element_symbols(:)

  character(100) :: text
  integer :: no_elements
  character(2) :: name
  integer :: element_id
  character(2) :: element_symbol
  real :: x,y,z

  integer :: h_count

  integer :: i,input

  ! The elemental symbols, so 1->"N", 2->"H" etc.
  element_symbols = ['N', 'H']

  h_count = 0

  open(10, file='input.dat')
  open(11, file='output.dat')

  read(10,*) text
  write(11,*) text
  read(10,*) no_elements
  write(11,*) no_elements

  do i=1,no_elements
    read(10,*) name, element_id, x, y, z

    element_symbol = element_symbols(element_id)

    if (element_symbol=="N") then
      ! If the element is `N`, reset h_count.
      h_count = 0
    elseif (element_symbol=="H") then
      ! If the element is `H`, update h_count.
      h_count = h_count + 1
      write(element_symbol,'(A,I0)') trim(element_symbol), h_count
    endif

    write(11,*) name, element_symbol, x, y, z
  enddo
end program
</code>```

Body:
I have an input file that looks like:

text
6
    1w    1     3.450   1.324   2.915
    1w    2     3.450   1.324   2.915
    4w    2     3.458   1.379   2.837
    4w    1     3.458   1.379   2.837
    7w    2     3.364   1.345   2.951
    7w    2     3.364   1.345   2.951

and I want the output file to look like:

text
6
    1w    N      3.450   1.324   2.915
    1w    H1     3.450   1.324   2.915
    4w    H2     3.458   1.379   2.837
    4w    N      3.458   1.379   2.837
    7w    H1     3.364   1.345   2.951
    7w    HW2    3.364   1.345   2.951

For the second column, the numbers 1 2 2 1 2 2, I need to print "N" for 1 and "H1" and "H2" for 2 and than again NH1H2, so I mean to tell the program to change once 2 for H1 and then H2. I used

if(p==1)p="N"
if(p==2)p="H1"

but I have no idea how to put do cycle to tell the second 2 is H2 not H1. Can you suggest what to do?

Body:
You probably want to keep a running count of the H elements, something like

program p
  implicit none

  character(2), allocatable :: element_symbols(:)

  character(100) :: text
  integer :: no_elements
  character(2) :: name
  integer :: element_id
  character(2) :: element_symbol
  real :: x,y,z

  integer :: h_count

  integer :: i,input

  ! The elemental symbols, so 1->"N", 2->"H" etc.
  element_symbols = ['N', 'H']

  h_count = 0

  open(10, file='input.dat')
  open(11, file='output.dat')

  read(10,*) text
  write(11,*) text
  read(10,*) no_elements
  write(11,*) no_elements

  do i=1,no_elements
    read(10,*) name, element_id, x, y, z

    element_symbol = element_symbols(element_id)

    if (element_symbol=="N") then
      ! If the element is `N`, reset h_count.
      h_count = 0
    elseif (element_symbol=="H") then
      ! If the element is `H`, update h_count.
      h_count = h_count + 1
      write(element_symbol,'(A,I0)') trim(element_symbol), h_count
    endif

    write(11,*) name, element_symbol, x, y, z
  enddo
end program


问:
why we need to pass Boolean value to the method
I have confusion on below code i.e why we need to pass Boolean value to the method and what it returns?</p>

```<code>RefreshLookupList(false);
private void RefreshLookupList(bool forExport)

    {
        grdLists.Rows.Clear();
        grdLists.DataSource = Lists.GetListItems(cboListType.SelectedValue);
        grdLists.DataBind();

        lblCount.InnerText = "Lookups: " + grdLists.Rows.Count.ToString();
    }
</code>```

答:
Well if that's the entire code block then you don't need to pass it at all. You can remove it.

Do a search on the code for the method and find out what else calls it. If nothing does then you can safely remove it.

Give it a go, and try to recompile the code. Good luck

Body:
I have confusion on below code i.e why we need to pass Boolean value to the method and what it returns?

RefreshLookupList(false);
private void RefreshLookupList(bool forExport)

    {
        grdLists.Rows.Clear();
        grdLists.DataSource = Lists.GetListItems(cboListType.SelectedValue);
        grdLists.DataBind();

        lblCount.InnerText = "Lookups: " + grdLists.Rows.Count.ToString();
    }


问:
Devexpress Winforms Gridview RowSelection Checkbox in intermediate state

I'm using WinForms Devexpress and bumped into the following task:

Somehow I need for DevExpress GridView to programmatically set data row selection checkbox to intermediate state (as the state of the top checkbox at the header at the picture below:

I'm wondering if it is possible or how to overcome the issue.

答:
You should set the column editor's AllowGrayed property to true.

```<code>this.yourBooleanColumn.ColumnEdit = this.repositoryItemCheckEdit1;
this.repositoryItemCheckEdit1.AllowGrayed = true;
</code>```

Body:
You should set the column editor's AllowGrayed property to true.

this.yourBooleanColumn.ColumnEdit = this.repositoryItemCheckEdit1;
this.repositoryItemCheckEdit1.AllowGrayed = true;


问:
GetX Controller not disposing off automatically
I have a minimlaist sample app running on Android with GetX as State Management lib only. There are two screens LandingPage and MainScreen. On going back from MainScreen to LandingPage screen, the controller is not autodisposing as expected.
I am using Flutter's Navigation only without wrapping with GetMaterialApp.

My expectation is that the value exposed by the controller should be reset to its initial value when the Controller is instantiated.
However, the Widget continues to show the last value from the controller.

I am using the latest version of Flutter and GetX as avail of now : 2.2.3 and 4.3.8 respectively

Your help is appreciated.

Code:

```<code>class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return GetMaterialApp(
  title: 'Flutter Demo',
  theme: ThemeData(

    primarySwatch: Colors.purple,
  ),
  home: LandingScreen(),
  );
 }
}

class LandingScreen extends StatelessWidget {
 @override
 Widget build(BuildContext context) {
  return Container(
   color: Colors.blue[800],
   child: Center(
     child: ElevatedButton(
       onPressed: () => {
         Get.to(MainScreen())
       },
       child: const Text('Navigate to Second Screen'),
     ),
    ),
  );
 }
}

class MainScreen extends StatelessWidget {
 final MyController controller = Get.put(MyController());

 @override
 Widget build(BuildContext context) {
  return Scaffold(
  body: SafeArea(
    child: Container(
      color: Colors.blueAccent,
      child: Center(
        child: Column(
          children: [
            Obx(() => Text('Clicked ${controller.count}')),
            FloatingActionButton(
              onPressed: controller.increment,
              child: Text('+'),
            ),
            ElevatedButton(
              onPressed: ()=>{Navigator.of(context).pop()},
              child: Text('Go Back'),
            )
          ],
          ),
         ),
        ),
       ),
      );
     }
    }

  class MyController extends GetxController {

   var count = 0.obs;
   void increment() => count++;

  }
</code>```

答:
this kinda worked for me when i defined the following method in the controller.dart file:

late Readcontroller controller;

```<code>void dispose(){ Get.delete(); controller = Get.put(ReadController()); }
</code>```

and then in the main file for me which was reading.dart:

```<code>widget build(Build context){ final ReadController controller = Get.put(ReadController()); }
</code>```

the above piece of code just works fine for me

give it a try .......

}

Body:
I have a minimlaist sample app running on Android with GetX as State Management lib only. There are two screens LandingPage and MainScreen. On going back from MainScreen to LandingPage screen, the controller is not autodisposing as expected.
I am using Flutter's Navigation only without wrapping with GetMaterialApp.

My expectation is that the value exposed by the controller should be reset to its initial value when the Controller is instantiated.
However, the Widget continues to show the last value from the controller.

I am using the latest version of Flutter and GetX as avail of now : 2.2.3 and 4.3.8 respectively

Your help is appreciated.

Code:

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return GetMaterialApp(
  title: 'Flutter Demo',
  theme: ThemeData(

    primarySwatch: Colors.purple,
  ),
  home: LandingScreen(),
  );
 }
}

class LandingScreen extends StatelessWidget {
 @override
 Widget build(BuildContext context) {
  return Container(
   color: Colors.blue[800],
   child: Center(
     child: ElevatedButton(
       onPressed: () => {
         Get.to(MainScreen())
       },
       child: const Text('Navigate to Second Screen'),
     ),
    ),
  );
 }
}

class MainScreen extends StatelessWidget {
 final MyController controller = Get.put(MyController());

 @override
 Widget build(BuildContext context) {
  return Scaffold(
  body: SafeArea(
    child: Container(
      color: Colors.blueAccent,
      child: Center(
        child: Column(
          children: [
            Obx(() => Text('Clicked ${controller.count}')),
            FloatingActionButton(
              onPressed: controller.increment,
              child: Text('+'),
            ),
            ElevatedButton(
              onPressed: ()=>{Navigator.of(context).pop()},
              child: Text('Go Back'),
            )
          ],
          ),
         ),
        ),
       ),
      );
     }
    }

  class MyController extends GetxController {

   var count = 0.obs;
   void increment() => count++;

  }

Body:
this kinda worked for me when i defined the following method in the controller.dart file:

late Readcontroller controller;

void dispose(){ Get.delete(); controller = Get.put(ReadController()); }

and then in the main file for me which was reading.dart:

widget build(Build context){ final ReadController controller = Get.put(ReadController()); }

the above piece of code just works fine for me

give it a try .......

}


问:
How to Customize the time format for Python logging?
I am new to Python's logging package and plan to use it for my project. I would like to customize the time format to my taste. Here is a short code I copied from a tutorial:

```<code>import logging

# create logger
logger = logging.getLogger("logging_tryout2")
logger.setLevel(logging.DEBUG)

# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s")

# add formatter to ch
ch.setFormatter(formatter)

# add ch to logger
logger.addHandler(ch)

# "application" code
logger.debug("debug message")
logger.info("info message")
logger.warn("warn message")
logger.error("error message")
logger.critical("critical message")
</code>```

And here is the output:

```<code>2010-07-10 10:46:28,811;DEBUG;debug message
2010-07-10 10:46:28,812;INFO;info message
2010-07-10 10:46:28,812;WARNING;warn message
2010-07-10 10:46:28,812;ERROR;error message
2010-07-10 10:46:28,813;CRITICAL;critical message
</code>```

I would like to shorten the time format to just: '2010-07-10 10:46:28', dropping the mili-second suffix. I looked at the Formatter.formatTime, but I am confused.

答:
In order to customize time format while logging we can create a logger object and and a fileHandler to it.</p>
```<code>        import logging
        from datetime import datetime

        logger = logging.getLogger("OSA")

        logger.setLevel(logging.DEBUG)

        filename = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + ".log"
        fileHandler = logging.FileHandler(filename, mode="a")#'a' for append you can use 'w' for write

        formatter = logging.Formatter(
            "%(asctime)s : %(levelname)s : [%(filename)s:%(lineno)s - %(funcName)s()] : %(message)s",
            "%Y-%m-%d %H:%M:%S")

        fileHandler.setFormatter(formatter)
        logger.addHandler(fileHandler)

</code>```

Body:
I am new to Python's logging package and plan to use it for my project. I would like to customize the time format to my taste. Here is a short code I copied from a tutorial:

import logging

# create logger
logger = logging.getLogger("logging_tryout2")
logger.setLevel(logging.DEBUG)

# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s")

# add formatter to ch
ch.setFormatter(formatter)

# add ch to logger
logger.addHandler(ch)

# "application" code
logger.debug("debug message")
logger.info("info message")
logger.warn("warn message")
logger.error("error message")
logger.critical("critical message")

And here is the output:

2010-07-10 10:46:28,811;DEBUG;debug message
2010-07-10 10:46:28,812;INFO;info message
2010-07-10 10:46:28,812;WARNING;warn message
2010-07-10 10:46:28,812;ERROR;error message
2010-07-10 10:46:28,813;CRITICAL;critical message

I would like to shorten the time format to just: '2010-07-10 10:46:28', dropping the mili-second suffix. I looked at the Formatter.formatTime, but I am confused.

Body:
In order to customize time format while logging we can create a logger object and and a fileHandler to it.

        import logging
        from datetime import datetime

        logger = logging.getLogger("OSA")

        logger.setLevel(logging.DEBUG)

        filename = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + ".log"
        fileHandler = logging.FileHandler(filename, mode="a")#'a' for append you can use 'w' for write

        formatter = logging.Formatter(
            "%(asctime)s : %(levelname)s : [%(filename)s:%(lineno)s - %(funcName)s()] : %(message)s",
            "%Y-%m-%d %H:%M:%S")

        fileHandler.setFormatter(formatter)
        logger.addHandler(fileHandler)


问:
Numbering a nested list in a single ol list
I have an ordered list with some li tags in it. I want the The li tags with  .sub-item class to be nested li tags. Is there a way I can reset numbering for the li tags having class? The list is as below:

```<code><ol>
  <li>One</li>
  <li>Two</li>
  <li>THree</li>
  <li class="sub-item">Sub three 1</li>
  <li class="sub-item">Sub three 2</li>
  <li>Four</li>
</ol>
</code>```

Currently I get which makes sense:

```<code>  1 One
  2 Two
  3 Three
  4 Sub Three 1
  5 Sub three 2
  6 Four
</code>```

However using the class 'sub-item' I want this desired behaviour

```<code>  1 One
  2 Two
  3. Three
     a Sub three 1
     b Sub Three 2
  4 Four
</code>```

I can not change the html part of the code, only can write css. Adding nested ol tags will not work in this case as I can not modify the html.

答:
Since you can't modify the HTML markup, the simplest solution is to use Javascript to correct it:

window.addEventListener('DOMContentLoaded', () => {
  document.querySelectorAll("li.sub-item:not(.sub-item ~ .sub-item)").forEach(el => {
    const parentItem = el.previousElementSibling;
    if (!parentItem) {
      return;
    }

    const items = [];
    for (let li = el; li && li.classList.contains("sub-item"); li = li.nextElementSibling) {
      items.push(li);
    }

    const ol = document.createElement("ol");
    ol.setAttribute("type", "a");
    items.forEach(li => ol.appendChild(li));
    parentItem.appendChild(ol);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ol>
  <li>One</li>
  <li>Two</li>
  <li>THree</li>
  <li class="sub-item">Sub three 1</li>
  <li class="sub-item">Sub three 2</li>
  <li>Four</li>
</ol></code>```

(The .sub-item:not(.sub-item ~ .sub-item) syntax came from this answer.)

Body:
I have an ordered list with some li tags in it. I want the The li tags with  .sub-item class to be nested li tags. Is there a way I can reset numbering for the li tags having class? The list is as below:

One

Two

THree

Sub three 1

Sub three 2

Four

Currently I get which makes sense:

  1 One
  2 Two
  3 Three
  4 Sub Three 1
  5 Sub three 2
  6 Four

However using the class 'sub-item' I want this desired behaviour

  1 One
  2 Two
  3. Three
     a Sub three 1
     b Sub Three 2
  4 Four

I can not change the html part of the code, only can write css. Adding nested ol tags will not work in this case as I can not modify the html.

Body:
Since you can't modify the HTML markup, the simplest solution is to use Javascript to correct it:

window.addEventListener('DOMContentLoaded', () => {
  document.querySelectorAll("li.sub-item:not(.sub-item ~ .sub-item)").forEach(el => {
    const parentItem = el.previousElementSibling;
    if (!parentItem) {
      return;
    }

    const items = [];
    for (let li = el; li && li.classList.contains("sub-item"); li = li.nextElementSibling) {
      items.push(li);
    }

    const ol = document.createElement("ol");
    ol.setAttribute("type", "a");
    items.forEach(li => ol.appendChild(li));
    parentItem.appendChild(ol);
  });
});

<ol>
  <li>One</li>
  <li>Two</li>
  <li>THree</li>
  <li class="sub-item">Sub three 1</li>
  <li class="sub-item">Sub three 2</li>
  <li>Four</li>
</ol>

(The .sub-item:not(.sub-item ~ .sub-item) syntax came from this answer.)


问:
Is there a way in Jmeter JDBC request to convert "result variable" data into Json format?
I am storing Jmeter JDBC REquest data in result variable which come out in following format :
[[alt_id:535644, cd:A, cube:1.000, stat_dt:null, ts:9999-12-31T00:01]]

I tried the following to convert it to JSON but not successful :

```<code>def resl = vars.getObject('jdbc_dcRes');
log.info("Jdbc result : " + resl);
def json = new groovy.json.JsonBuilder(resl).toPreetyString();
OR
def json = new groovy.json.JsonBuilder(resl).toString();
log.info("Jdbc result Converted into Json : " + json);
</code>```

Getting :
2022-02-11 15:31:51,971 ERROR o.a.j.JMeter: Uncaught exception in thread Thread[dc Service 1-1,6,main]
java.lang.StackOverflowError: null
at java.util.concurrent.ConcurrentHashMap.putVal(Unknown Source) ~[?:1.8.0_111]
at java.util.concurrent.ConcurrentHashMap.putIfAbsent(Unknown Source) ~[?:1.8.0_111]
at java.lang.ClassLoader.getClassLoadingLock(Unknown Source) ~[?:1.8.0_111]
at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_111]
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) ~[?:1.8.0_111]
at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_111]
at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_111]
at java.lang.Class.forName0(Native Method) ~[?:1.8.0_111]
at java.lang.Class.forName(Unknown Source) ~[?:1.8.0_111]
at groovy.lang.MetaClassRegistry$MetaClassCreationHandle.createWithCustomLookup(MetaClassRegistry.java:144) ~[groovy-3.0.7.jar:3.0.7]
at groovy.lang.MetaClassRegistry$MetaClassCreationHandle.create(MetaClassRegistry.java:139) ~[groovy-3.0.7.jar:3.0.7]
at org.codehaus.groovy.reflection.ClassInfo.getMetaClassUnderLock(ClassInfo.java:272) ~[groovy-3.0.7.jar:3.0.7]

.............

Any pointer to overcome this would be helpful. Thanks

答:
For me the following code snippet works just fine:

```<code>def resl = vars.getObject('jdbc_dcRes')

def json = new groovy.json.JsonBuilder(resl).toPrettyString()

log.info('Jdbc result Converted into Json :' + json)
</code>```

Demo:

I'm using normal MySQL database 8.0.28 and the following query:

```<code>select * from help_category limit 2
</code>```

So you might want to try to replicate the above and if it will be successful - most probably the problem is with the data from your DB which cannot be converted to JSON using Groovy's JsonBuilder without extra transformation (i.e. you have specific data types which cannot be mapped 1-to-1 to JSON data types)

See Debugging JDBC Sampler Results in JMeter to learn more about anatomy of the beast called "Result variable name" in JMeter's JDBC Request sampler

Body:
I am storing Jmeter JDBC REquest data in result variable which come out in following format :
[[alt_id:535644, cd:A, cube:1.000, stat_dt:null, ts:9999-12-31T00:01]]

I tried the following to convert it to JSON but not successful :

def resl = vars.getObject('jdbc_dcRes');
log.info("Jdbc result : " + resl);
def json = new groovy.json.JsonBuilder(resl).toPreetyString();
OR
def json = new groovy.json.JsonBuilder(resl).toString();
log.info("Jdbc result Converted into Json : " + json);

Getting :
2022-02-11 15:31:51,971 ERROR o.a.j.JMeter: Uncaught exception in thread Thread[dc Service 1-1,6,main]
java.lang.StackOverflowError: null
at java.util.concurrent.ConcurrentHashMap.putVal(Unknown Source) ~[?:1.8.0_111]
at java.util.concurrent.ConcurrentHashMap.putIfAbsent(Unknown Source) ~[?:1.8.0_111]
at java.lang.ClassLoader.getClassLoadingLock(Unknown Source) ~[?:1.8.0_111]
at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_111]
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) ~[?:1.8.0_111]
at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_111]
at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_111]
at java.lang.Class.forName0(Native Method) ~[?:1.8.0_111]
at java.lang.Class.forName(Unknown Source) ~[?:1.8.0_111]
at groovy.lang.MetaClassRegistry$MetaClassCreationHandle.createWithCustomLookup(MetaClassRegistry.java:144) ~[groovy-3.0.7.jar:3.0.7]
at groovy.lang.MetaClassRegistry$MetaClassCreationHandle.create(MetaClassRegistry.java:139) ~[groovy-3.0.7.jar:3.0.7]
at org.codehaus.groovy.reflection.ClassInfo.getMetaClassUnderLock(ClassInfo.java:272) ~[groovy-3.0.7.jar:3.0.7]

.............

Any pointer to overcome this would be helpful. Thanks

Body:
For me the following code snippet works just fine:

def resl = vars.getObject('jdbc_dcRes')

def json = new groovy.json.JsonBuilder(resl).toPrettyString()

log.info('Jdbc result Converted into Json :' + json)

Demo:

I'm using normal MySQL database 8.0.28 and the following query:

select * from help_category limit 2

So you might want to try to replicate the above and if it will be successful - most probably the problem is with the data from your DB which cannot be converted to JSON using Groovy's JsonBuilder without extra transformation (i.e. you have specific data types which cannot be mapped 1-to-1 to JSON data types)

See Debugging JDBC Sampler Results in JMeter to learn more about anatomy of the beast called "Result variable name" in JMeter's JDBC Request sampler


问:
Generate dictionary by template in inventory
At the moment I have the following inventory (simplified):

children:
    child-1111:
        param: some-data-1111
    child-1112:
        param: some-data-1112
    child-1113:
        param: some-data-1113
```
<p>Of course, it's not good when you need a thousand hosts instead of just three and many parameters with substitutions. I would like to write something like this (which doesn't work):</p>
<pre class="lang-yaml prettyprint-override"><code>children:
    "child-{{item}}":
        param: "some-data-{{item}}"
        loop:
            - 1111
            - 1112
            - 1113
</code>```

All the examples I see always produce lists, not dictionaries.

Also, loop seems to work only for tasks, not inventories.

How do I achieve this?

答:
Some forenotes:

Your question is not very precise. My example will only give a general approach which is a bit more scalable than yours but will hit limits very soon.

Your example is not a valid yaml inventory. Moreover it is not clear if you use the name children to declare children groups for the default all or if you want to use this as a group name (which I strongly suggest you don't do).

Having to declare host specific variables depending on the host name inside a static inventory for loads of hosts is generally a sign of either a bad design or that you should switch to a fully dynamic inventory or by managing the hosts in your playbook dynamically through add_host (see @β.εηοιτ.βε's answer)

My example below declares a range of hosts in a group named my_children and takes advantage of the host naming convention to capture their number and reuse it in a variable declared for the group

inv.yml

---
my_children:
  vars:
    param: "some-data-{{ inventory_hostname.split('-')[1] }}"
  hosts:
    child-[1111:1113]:

```
<p>You can see the hosts are parsed correctly:</p>
<pre class="lang-none prettyprint-override"><code>$ ansible-inventory -i inv.yml --list
{
    "_meta": {
        "hostvars": {
            "child-1111": {
                "param": "some-data-{{ inventory_hostname.split('-')[1] }}"
            },
            "child-1112": {
                "param": "some-data-{{ inventory_hostname.split('-')[1] }}"
            },
            "child-1113": {
                "param": "some-data-{{ inventory_hostname.split('-')[1] }}"
            }
        }
    },
    "all": {
        "children": [
            "my_children",
            "ungrouped"
        ]
    },
    "my_children": {
        "hosts": [
            "child-1111",
            "child-1112",
            "child-1113"
        ]
    }
}
</code>```

And the vars are interpreted correctly:

$ ansible my_children -i inv.yml -m debug -a "msg={{ param }}"
child-1111 | SUCCESS => {
    "msg": "some-data-1111"
}
child-1112 | SUCCESS => {
    "msg": "some-data-1112"
}
child-1113 | SUCCESS => {
    "msg": "some-data-1113"
}
```

Body:
At the moment I have the following inventory (simplified):

children:
    child-1111:
        param: some-data-1111
    child-1112:
        param: some-data-1112
    child-1113:
        param: some-data-1113

Of course, it's not good when you need a thousand hosts instead of just three and many parameters with substitutions. I would like to write something like this (which doesn't work):

children:
    "child-{{item}}":
        param: "some-data-{{item}}"
        loop:
            - 1111
            - 1112
            - 1113

All the examples I see always produce lists, not dictionaries.

Also, loop seems to work only for tasks, not inventories.

How do I achieve this?

Body:
Some forenotes:

Your question is not very precise. My example will only give a general approach which is a bit more scalable than yours but will hit limits very soon.

Your example is not a valid yaml inventory. Moreover it is not clear if you use the name children to declare children groups for the default all or if you want to use this as a group name (which I strongly suggest you don't do).

Having to declare host specific variables depending on the host name inside a static inventory for loads of hosts is generally a sign of either a bad design or that you should switch to a fully dynamic inventory or by managing the hosts in your playbook dynamically through add_host (see @β.εηοιτ.βε's answer)

My example below declares a range of hosts in a group named my_children and takes advantage of the host naming convention to capture their number and reuse it in a variable declared for the group

inv.yml

---
my_children:
  vars:
    param: "some-data-{{ inventory_hostname.split('-')[1] }}"
  hosts:
    child-[1111:1113]:

You can see the hosts are parsed correctly:

$ ansible-inventory -i inv.yml --list
{
    "_meta": {
        "hostvars": {
            "child-1111": {
                "param": "some-data-{{ inventory_hostname.split('-')[1] }}"
            },
            "child-1112": {
                "param": "some-data-{{ inventory_hostname.split('-')[1] }}"
            },
            "child-1113": {
                "param": "some-data-{{ inventory_hostname.split('-')[1] }}"
            }
        }
    },
    "all": {
        "children": [
            "my_children",
            "ungrouped"
        ]
    },
    "my_children": {
        "hosts": [
            "child-1111",
            "child-1112",
            "child-1113"
        ]
    }
}

And the vars are interpreted correctly:

$ ansible my_children -i inv.yml -m debug -a "msg={{ param }}"
child-1111 | SUCCESS => {
    "msg": "some-data-1111"
}
child-1112 | SUCCESS => {
    "msg": "some-data-1112"
}
child-1113 | SUCCESS => {
    "msg": "some-data-1113"
}


问:
Using spring data jpa how to execute a native sql query programmatically?
I am aware about how spring data jpa allows using native queries.

```<code>@Query(
  value = "SELECT * FROM USERS u WHERE u.status = 1",
  nativeQuery = true)
Collection<User> findAllActiveUsersNative();
</code>```

Reference - https://www.baeldung.com/spring-data-jpa-query

But my interest here is, instead of using the SQL with @Query annotation, it is possible to execute the sql query programmatically (for example say how we do while using jdbc) and get result in to a dto or resultset.

I just want to explore above approach for cases where the query might be generated dynamically and may not be know at compile time.

I have seen sof posts, which suggests other approaches like QueryByExample and QueryDSL and i know using JPA Specification also this case can be addressed. And these are great and the right way of addressing dynamic query situation.

But in this Q, I am interested in knowing if SQL queries can be executed programmatically (not through @Query annotation). If yes, how? (some demo code will help)

答: Well, you can always write a repository extension, into which you can inject the EntityManager.

Body:
I am aware about how spring data jpa allows using native queries.

@Query(
  value = "SELECT * FROM USERS u WHERE u.status = 1",
  nativeQuery = true)
Collection<User> findAllActiveUsersNative();

Reference - https://www.baeldung.com/spring-data-jpa-query

But my interest here is, instead of using the SQL with @Query annotation, it is possible to execute the sql query programmatically (for example say how we do while using jdbc) and get result in to a dto or resultset.

I just want to explore above approach for cases where the query might be generated dynamically and may not be know at compile time.

I have seen sof posts, which suggests other approaches like QueryByExample and QueryDSL and i know using JPA Specification also this case can be addressed. And these are great and the right way of addressing dynamic query situation.

But in this Q, I am interested in knowing if SQL queries can be executed programmatically (not through @Query annotation). If yes, how? (some demo code will help)


问:
azure pipeline New-AzVM : Cannot process command because of one or more missing mandatory
Im using the script below to deploy a new vm from an existing image using a pipeline:

```<code>New-AzVm
-Credential $(credential)
-ResourceGroupName "RG"
-Name "Dev-VM"
-ImageName "Image"
-Location "West Europe"
-VirtualNetworkName "*****"
-SubnetName "*****"
-SecurityGroupName "**************"
-PublicIpAddressName "myImagePIP"
</code>```

but I got this error

(##[error]Cannot process command because of one or more missing mandatory parameters: Name Credential.)

Even if the parameter is already set. I don't know why it keeps asking for an Credential parameter.

could you please help me? do you have any idea?

答:
Guess you're not the only one looking for this! Also investigating how to be able to do it. My first guess, since you are using Azure, I'd store user and password(or only the latter) on an Azure Keyvault, and create a "session" out of it... Which is nonsense, to my oppinion because you are using a Service connection, that already has permissions over the RG you want to create the VM...
At least hope this helps you getting forward!

... or! Use ARM Templates or Terraform... I'm trying to avoid that at this stage...

Hope to hear your thoughts!

Body:
Im using the script below to deploy a new vm from an existing image using a pipeline:

New-AzVm
-Credential $(credential)
-ResourceGroupName "RG"
-Name "Dev-VM"
-ImageName "Image"
-Location "West Europe"
-VirtualNetworkName "*****"
-SubnetName "*****"
-SecurityGroupName "**************"
-PublicIpAddressName "myImagePIP"

but I got this error

(##[error]Cannot process command because of one or more missing mandatory parameters: Name Credential.)

Even if the parameter is already set. I don't know why it keeps asking for an Credential parameter.

could you please help me? do you have any idea?


问:
Running VSS 2005 Client on a the same server as VSS 6.0
Is it possible to run client-server combination of VSS 2005 (client)/VSS 6.0 (server) on the same box?</p>

答: I believe that should work just fine. I don't believe the client and server share any components and I am able to use VSS 2005 to connect to VSS 6.0 databases.</p>

OwnerDisplayName: Danny G

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Justin Niessner


问:
ApexCharts.exec updateSeries works only once
Have an issue that I'm trying to figure out with Apexcharts.

just to lead with, I cant really post an example as the chart code is somewhat large and relies an web-sockets to get the data so I'm going to try my best to explain the flow with hopes somebody may know what I'm doing wrong here, I apologies in advance.

The flow of the application is

User can view the results of a survey ( this is using apex charts ). This is a modal window that opens and builds an on-the-fly popup that contains the chart div e.g

```<code><div class="poll[dynamic number"></div>
</code>```

User has the results view opened (this renders just fine) and a new response comes in

data comes in and we use

```<code>ApexCharts.exec(chartName, 'updateSeries', [{
   data: updateData
 }], true);
</code>```

To update the data. This works great the first time, however if we close the modal, open it back up again the chart renders just fine but new responses don't update the chart.

Looking at the code there are no duplicate ID's, so when the modal is opened its fully replacing the content of the popup, as noted the chart renders just fine each time but subsequent updateSeries don't work. printing things to the console show the data coming in, it appears it can get the chart object however updates don't seem to work.

Reloading the page will get the updates to work so I'm thinking it may be something with how its being initiated however trying to destroy the charts before etc have change nothing.

I know this is a very hard to debug without seeing and if I could post an example I would. I guess the question really is, should apex charts updateSeries work with multiple dynamically generated charts? If not, then why does it work once and never again?

答:
If you run in the same problem as proximO and me but don't really understand his solution (sorry proxim0 but it took me some time), here is mine.
I had the same problem that the Chart was loading fine after opening or reloading the page, but there was no data shown when leaving the route and then coming back.

As proxim0 stated, normal variable declaration like

```<code>var chart = new VueApexCharts(document.querySelector('#chartID'),this.chartOptions)
console.log('Chart Object', chart)
chart.render()

VueApexCharts.exec('chartID', 'updateOptions', {
        series: [{
          name: 'SeriesName',
          data: myData
        }]
      })
</code>```

does only work after loading or reloading the page.

What solved my problem here was saving the chart variable as a vuex store state and then running a function before the Initialisation (and Series updating as I showed above) to check if the chart Object was initialized allready. If it was, you can just destroy them before initializing again with chartObject.destroy().

```<code> checkForChartElements () {
   if (this.$store.getters.getChartObject !== null) {
     this.$store.getters.getChartObject.destroy()
     this.$store.commit('setChartObject', null)
   }
</code>```

I hope this saves someone some time.

Body:
Have an issue that I'm trying to figure out with Apexcharts.

just to lead with, I cant really post an example as the chart code is somewhat large and relies an web-sockets to get the data so I'm going to try my best to explain the flow with hopes somebody may know what I'm doing wrong here, I apologies in advance.

The flow of the application is

User can view the results of a survey ( this is using apex charts ). This is a modal window that opens and builds an on-the-fly popup that contains the chart div e.g

User has the results view opened (this renders just fine) and a new response comes in

data comes in and we use

ApexCharts.exec(chartName, 'updateSeries', [{
   data: updateData
 }], true);

To update the data. This works great the first time, however if we close the modal, open it back up again the chart renders just fine but new responses don't update the chart.

Looking at the code there are no duplicate ID's, so when the modal is opened its fully replacing the content of the popup, as noted the chart renders just fine each time but subsequent updateSeries don't work. printing things to the console show the data coming in, it appears it can get the chart object however updates don't seem to work.

Reloading the page will get the updates to work so I'm thinking it may be something with how its being initiated however trying to destroy the charts before etc have change nothing.

I know this is a very hard to debug without seeing and if I could post an example I would. I guess the question really is, should apex charts updateSeries work with multiple dynamically generated charts? If not, then why does it work once and never again?

Body:
If you run in the same problem as proximO and me but don't really understand his solution (sorry proxim0 but it took me some time), here is mine.
I had the same problem that the Chart was loading fine after opening or reloading the page, but there was no data shown when leaving the route and then coming back.

As proxim0 stated, normal variable declaration like

var chart = new VueApexCharts(document.querySelector('#chartID'),this.chartOptions)
console.log('Chart Object', chart)
chart.render()

VueApexCharts.exec('chartID', 'updateOptions', {
        series: [{
          name: 'SeriesName',
          data: myData
        }]
      })

does only work after loading or reloading the page.

What solved my problem here was saving the chart variable as a vuex store state and then running a function before the Initialisation (and Series updating as I showed above) to check if the chart Object was initialized allready. If it was, you can just destroy them before initializing again with chartObject.destroy().

 checkForChartElements () {
   if (this.$store.getters.getChartObject !== null) {
     this.$store.getters.getChartObject.destroy()
     this.$store.commit('setChartObject', null)
   }

I hope this saves someone some time.


问:
Google Sheets Query formula, find and select X value from rows

Hello i want to auto-fill the  cell and fill with "The Tweety House" as that one is the highest "$ Result"(111.111), i dont know how to do that maybe someone here can help me to figure it out.

Thank you

答:
In O6 try

```<code>=+sort(B11:B, AJ11:AJ, 0)
</code>```

Also removes the formulas in AE11:AE and enter in AE11

```<code>=INDEX(IF(AJ11:AJ<>"", AJ11:AJ/W11:W,))
</code>```

Then for V6 you can use

```<code>=+sort(B11:B, AE11:AE, 0)
</code>```

Note:

for O5 you can use

```<code>=MAX(AJ11:AJ)
</code>```

and for V5

```<code>=MAX(AE11:AE)
</code>```

See if that helps?

Body:
In O6 try

=+sort(B11:B, AJ11:AJ, 0)

Also removes the formulas in AE11:AE and enter in AE11

=INDEX(IF(AJ11:AJ<>"", AJ11:AJ/W11:W,))

Then for V6 you can use

=+sort(B11:B, AE11:AE, 0)

Note:

for O5 you can use

=MAX(AJ11:AJ)

and for V5

=MAX(AE11:AE)

See if that helps?


问:
Pass array as query parameter in Postman
I am trying to pass an array as query parameter in Postman.

I am calling DELETE method to delete a user from list of databases. It is expecting list of database names as array in the query parameter. When I pass as given below, I am getting error.

{"code":2,"message":"data_services must be an array and not empty"}

Please let me know, how can I pass an array as query parameter in Postman.

答: You need to create 2 keys with the same name and add postfix []


问:
junit 4 testcases and test suites in the same folder
I have some JUnit 4 test cases and test suites that are in the same directory. When I run these from eclipse using a right-click on the top level test directory, the all of the test cases that do not occur in a test suite get run, and all of the test suites get run but the test cases are green but do not look like they have been run in eclipse.

Normally i would prefer that the test suites not get run and just have the test cases run. Is there a way to do that? Should I put then in a different tree structure?

Also is there a way to make a test suite and just specify some tests methods instead of the entire class?

答:
In Run -> Run Configuration you can select your Junit Configuration.
From this menu you can launch the entire TestSuite or even a single method:

Run Configuration Dialog


问:
Foundry Sync Backing Dataset
How can we find the backing dataset for a table which is being queried by using Foundry Postgres SQL service in slate?

Edit: We do have a way to find sync information from Details Tab in a dataset. I want to reverse enginner this. To find a way to get dataset details using foundry sync table name as i don't know the main dataset.

答:
The metadata related to the mapping from a dataset RID to a postgres table is stored in the postgate.dataset table, however only the administrator account has permissions to query the postgate schema. If you've "lost" the source dataset and can't find it by looking at the possible input datasets in the Dataset preview, you can reach out to your Foundry Support contact to get further help.

The general best practice is to manually add the relevant datasets into the Dataset tab in the Slate app - I normally do this even if I'm primarily using the Platform tab to read from the object layer instead of from Postgres.

The reason this isn't automatically inferred is because Slate doesn't actually introspect your query and you can write queries that dynamically choose which table to query at runtime.

Title: Foundry Sync Backing Dataset


问:
Example of getters setters as a bad choice in Java
Could somebody please provide an example where getters and setters are not required?

I still do not get the idea, I guess a very huge class with lots of attributes must have them but in simpler cases?

答:
Getters and setters are required if the class in question is non-trivial or to be extended.

For classes to be used as simple states, where changing the property directly is unlikely to directly incur additional changes to other parts of the class or context in which it is used, there is little point in having getters and setters when just a simple property will suffice.

Good examples from the Java libraries are Rectangle, Dimension, and Insets.

Dimension does have getters and setters for convenience, but the properties (width, height) are still public.


问:
Getting Error related to number format (java.lang.ClassCastException: java.math.BigDecimal cannot be cast to java.lang.String )
I am having a query as below

```<code>select SHIPMENT_COST_SEQNO as SHIPMENT_COST_SEQNO from shipment_cost where shipment_gid = 'A1.53005'
</code>```

which gives me error as 'java.lang.ClassCastException: java.math.BigDecimal cannot be cast to java.lang.String '

Though the SHIPMENT_COST_SEQNO  is a 5 digit number but still gives me above error.

This works fine with SQL Interface but when i try execute from application it gives me above error .

Any pointers would be appreciable.

Thanks

答:
seems you need casting as your used in entity sting</p>
```<code>select cast(SHIPMENT_COST_SEQNO as varchar(50))
 as SHIPMENT_COST_SEQNO from shipment_cost where shipment_gid = 'A1.53005'
</code>```

Body:
I am having a query as below

select SHIPMENT_COST_SEQNO as SHIPMENT_COST_SEQNO from shipment_cost where shipment_gid = 'A1.53005'

which gives me error as 'java.lang.ClassCastException: java.math.BigDecimal cannot be cast to java.lang.String '

Though the SHIPMENT_COST_SEQNO  is a 5 digit number but still gives me above error.

This works fine with SQL Interface but when i try execute from application it gives me above error .

Any pointers would be appreciable.

Thanks

Body:
seems you need casting as your used in entity sting

select cast(SHIPMENT_COST_SEQNO as varchar(50))
 as SHIPMENT_COST_SEQNO from shipment_cost where shipment_gid = 'A1.53005'


问:
Az Powershell function - how to get output in JSON format
I'm migrating / rewriting an azure cli script to Az Powershell.  The current script includes logic like this:

```<code>#look up the storage account name for this resource group.
$storageAccount = az storage account list -g $currentEnv.RESOURCEGROUP-o json | ConvertFrom-Json
Write-Output $storageAccount.name
</code>```

Is there a way to do this using the Get-AzStorageAccount cmdlet?  (version 4.1.1)

The cmdlet itself works ... I can use it to get the storage account info, but it comes back in table format.  I would like JSON so I can ease the burden of parsing the results.

答:
If you simply use the below command then you will get the storage account details in a table format which is the default format in Powershell as show in image:

```<code>Get-AzStorageAccount -ResourceGroupName <ResourceGroupName>
</code>```

But this doesn't mean that you can't use a single storage account name or print   selected Paramters .

To print the Names you can use the below command :

```<code>Get-AzStorageAccount -ResourceGroupName <ResourceGroupName> | Select-Object StorageAccountName
</code>```

And the same way you use Az CLI for using the names or a signle name from the list you can use the below commands:

```<code>$StorageAccount = Get-AzStorageAccount -ResourceGroupName <ResourceGroupName>
Write-Host $StorageAccount.StorageAccountName
Write-Host $StorageAccount.StorageAccountName[1]
</code>```

Body:
I'm migrating / rewriting an azure cli script to Az Powershell.  The current script includes logic like this:

#look up the storage account name for this resource group.
$storageAccount = az storage account list -g $currentEnv.RESOURCEGROUP-o json | ConvertFrom-Json
Write-Output $storageAccount.name

Is there a way to do this using the Get-AzStorageAccount cmdlet?  (version 4.1.1)

The cmdlet itself works ... I can use it to get the storage account info, but it comes back in table format.  I would like JSON so I can ease the burden of parsing the results.

Body:
If you simply use the below command then you will get the storage account details in a table format which is the default format in Powershell as show in image:

Get-AzStorageAccount -ResourceGroupName <ResourceGroupName>

But this doesn't mean that you can't use a single storage account name or print   selected Paramters .

To print the Names you can use the below command :

Get-AzStorageAccount -ResourceGroupName <ResourceGroupName> | Select-Object StorageAccountName

And the same way you use Az CLI for using the names or a signle name from the list you can use the below commands:

$StorageAccount = Get-AzStorageAccount -ResourceGroupName <ResourceGroupName>
Write-Host $StorageAccount.StorageAccountName
Write-Host $StorageAccount.StorageAccountName[1]