问:
Extract column values of Dataframe as List in Apache Spark
I want to convert a string column of a data frame to a list. What I can find from the Dataframe API is RDD, so I tried converting it back to RDD first, and then apply toArray function to the RDD. In this case, the length and SQL work just fine. However, the result I got from RDD has square brackets around every element like this [A00001]. I was wondering if there's an appropriate way to convert a column to a list or a way to remove the square brackets.

Any suggestions would be appreciated. Thank you!

答:
This is java answer.</p>

```<code>df.select("id").collectAsList();
</code>```

Body:
This is java answer.

df.select("id").collectAsList();


来源: stackexchange

问:
jQuery - on click with * selector trigger too many times
I want to record down the full css path on every element click by user, I follow this answer to create a function that get css path of the clicked element

```<code>$('body').on('click',"*",function(){
    var rightArrowParents = [];
    $(this).parents().addBack().not('html').each(function(e) {
        var entry = this.tagName.toLowerCase();

        if($(this).attr('id')){
            entry += "#" + $(this).attr('id');
        }

        if (this.className) {
        entry += "." + this.className.replace(/ /g, '.');
        }

        rightArrowParents.push(entry);
    });
    console.log(rightArrowParents.join(" > "));
})
</code>```

but I notice that this function is called so many times when I click on an element which is wrap by multiple element,

for example when I click on h1:

```<code>body > div.sample1.sample2 > div.sample3.sample4 > h1.test1.test2.test3

body > div.sample1.sample2 > div.sample3.sample4

body > div.sample1.sample2

</code>```

when I add return false after console.log, it will only output the full css path of h1, which is the expected result, but if I do this, some element will not work properly such as  will not redirect to another website

below is what I have tried:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <title>Document</title>
</head>
<body>
    <div class="sample1 sample2">
        <div class="sample3 sample4">
            <h1 class="test1 test2 test3">some example text</h1>
        </div>
    </div>
    <div>
        <h1 class="test1 test2 test3">some sample text</h1>
    </div>
    <div class="sample1 sample2">
        <div class="sample3 sample4">
            <a class="test1 test2 test3" href="https://www.google.com/">henlo</a>
        </div>
    </div>
    <script>
        jQuery(function($){
            $('body').on('click',"*",function(){
                var rightArrowParents = [];
                $(this).parents().addBack().not('html').each(function(e) {
                    var entry = this.tagName.toLowerCase();

                    if($(this).attr('id')){
                        entry += "#" + $(this).attr('id');
                    }

                    if (this.className) {
                    entry += "." + this.className.replace(/ /g, '.');
                    }

                    rightArrowParents.push(entry);
                });
                console.log(rightArrowParents.join(" > "));
                //can't do this, since it will make some element malfunction
                //return false
            })
        })
    </script>
</body>
</html>
</code>```

what should I do to make the jQuery work properly?

答:
If I understand your question clearly, all you need to do is add an event parameter to your function function(e), then use e.stopPropagation() at the end to prevent it from going through the event handlers of the parent elements.

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Document</title>

some example text

some sample text

      henlo

```

ContentLicense: CC BY-SA 4.0

Body:
I want to record down the full css path on every element click by user, I follow this answer to create a function that get css path of the clicked element

$('body').on('click',"*",function(){
    var rightArrowParents = [];
    $(this).parents().addBack().not('html').each(function(e) {
        var entry = this.tagName.toLowerCase();

        if($(this).attr('id')){
            entry += "#" + $(this).attr('id');
        }

        if (this.className) {
        entry += "." + this.className.replace(/ /g, '.');
        }

        rightArrowParents.push(entry);
    });
    console.log(rightArrowParents.join(" > "));
})

but I notice that this function is called so many times when I click on an element which is wrap by multiple element,

for example when I click on h1:

body > div.sample1.sample2 > div.sample3.sample4 > h1.test1.test2.test3

body > div.sample1.sample2 > div.sample3.sample4

body > div.sample1.sample2

when I add return false after console.log, it will only output the full css path of h1, which is the expected result, but if I do this, some element will not work properly such as  will not redirect to another website

below is what I have tried:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Document</title>

some example text

some sample text

            henlo

what should I do to make the jQuery work properly?

Body:
If I understand your question clearly, all you need to do is add an event parameter to your function function(e), then use e.stopPropagation() at the end to prevent it from going through the event handlers of the parent elements.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <title>Document</title>
</head>

<body>
  <div class="sample1 sample2">
    <div class="sample3 sample4">
      <h1 class="test1 test2 test3">some example text</h1>
    </div>
  </div>
  <div>
    <h1 class="test1 test2 test3">some sample text</h1>
  </div>
  <div class="sample1 sample2">
    <div class="sample3 sample4">
      <a class="test1 test2 test3" href="https://www.google.com/">henlo</a>
    </div>
  </div>
  <script>
    jQuery(function($) {
      $('body').on('click', "*", function(e) {
        var rightArrowParents = [];
        $(this).parents().addBack().not('html').each(function() {
          var entry = this.tagName.toLowerCase();

          if ($(this).attr('id')) {
            entry += "#" + $(this).attr('id');
          }

          if (this.className) {
            entry += "." + this.className.replace(/ /g, '.');
          }

          rightArrowParents.push(entry);
        });
        console.log(rightArrowParents.join(" > "));

        e.stopPropagation();
      })
    })
  </script>
</body>

</html>


问:
Call a class attribute of a class instance from a function in python
Let's say I want to plot different class objects attribute from a function.

So far I have this:

...

import matplotlib.pyplot as plt

def plot2vars (deviceList, xVars, yVars, xLims, yLims, colormap=plt.cm.Spectral):
    x0 = xVars[0]
    x1 = xVars[1]
    y0 = yVars[0]
    y1 = yVars[1]
    fig, ax = plt.subplots(1,2)

    fig, ax = plt.subplots(1,2)
    for d in deviceList: #these 'd' are the class instances...
        if not d.discard:
                    ax[0].plot(d.x0, d.y0)
                    ax[0].set_xlim(xLims[0])
                    ax[0].set_ylim(yLims[0])

                    ax[1].plot(d.x1, d.y1)
                    ax[1].set_xlim(xLims[1])
                    ax[1].set_ylim(yLims[1])
    plt.show()

```

<p>where deviceList is a list containing class instances with different attributes like, for example, <code>u</code>, <code>z</code> or <code>T</code>.</p>

<p>Now, when I call the function, I declare xVars, yVars, xLims, yLims as arrays of strings, which obviously doesn't work. But I don't know how to call these. And I don't even know how to look for this in the manuals...</p>

<pre class="lang-py prettyprint-override"><code>plot2vars (
      deviceList,
      xVars=['u', 'u'], yVars=['z', 'T'],
      xLims=['', 'left=0.8'], yLims=['','bottom=0, top=0.8']
      )
</code>```

答:
So if I understand correctly, you are trying to access the attribute u of object d which would typically be called by writing d.u, but you want to be able to do that without defining ahead of time that the attribute in question is u.

d.x0 will look for an attribute of d which is called x0, which has nothing to do the x0 you have defined.

The closest thing to what you're trying to do in this case is the getattr function: getattr(d, x0) should give you what you want.

That being said, it's not great practice if you can avoid using it. I would recommend simply passing d.u as argument to plot2vars and edit plot2vars accordingly when possible.

Body:
Let's say I want to plot different class objects attribute from a function.

So far I have this:

...

import matplotlib.pyplot as plt

def plot2vars (deviceList, xVars, yVars, xLims, yLims, colormap=plt.cm.Spectral):
    x0 = xVars[0]
    x1 = xVars[1]
    y0 = yVars[0]
    y1 = yVars[1]
    fig, ax = plt.subplots(1,2)

    fig, ax = plt.subplots(1,2)
    for d in deviceList: #these 'd' are the class instances...
        if not d.discard:
                    ax[0].plot(d.x0, d.y0)
                    ax[0].set_xlim(xLims[0])
                    ax[0].set_ylim(yLims[0])

                    ax[1].plot(d.x1, d.y1)
                    ax[1].set_xlim(xLims[1])
                    ax[1].set_ylim(yLims[1])
    plt.show()

where deviceList is a list containing class instances with different attributes like, for example, u, z or T.

Now, when I call the function, I declare xVars, yVars, xLims, yLims as arrays of strings, which obviously doesn't work. But I don't know how to call these. And I don't even know how to look for this in the manuals...

plot2vars (
      deviceList,
      xVars=['u', 'u'], yVars=['z', 'T'],
      xLims=['', 'left=0.8'], yLims=['','bottom=0, top=0.8']
      )


问:
How to share ownership of mounted directory on docker?
I am still new at using docker and currently I am planning to do a machine learning training on a supercomputer shared by many user. I have successfully created an image and mount all the necessary data but when I try to run the training, I got permission denied when the code tries to access a .txt file. Here is the error

```<code>user@701c214f9fa9:/app/sfsnet$ python main_mix_training.py
Traceback (most recent call last):
  File "main_mix_training.py", line 156, in <module>
    main()
  File "main_mix_training.py", line 132, in main
    with open(args.log_dir+'/details.txt', 'w') as f:
PermissionError: [Errno 13] Permission denied: './results//details.txt'
user@701c214f9fa9:/app/sfsnet$ python main_mix_training.py
Traceback (most recent call last):
  File "main_mix_training.py", line 156, in <module>
    main()
  File "main_mix_training.py", line 132, in main
    with open(args.log_dir+'/details.txt', 'w') as f:
PermissionError: [Errno 13] Permission denied: './results//details.txt'
</code>```

I have checked the mounted directory ownership and it should all be mine (dgx_user6) :

```<code>total 308
-rw-r--r-- 1 dgx_user6 dgx_user6  1271  二  14 05:32  checkmodel.py
-rw-r--r-- 1 dgx_user6 dgx_user6   458  二  13 23:51  cropping.py
-rw-r--r-- 1 dgx_user6 dgx_user6 12890  二  14 14:03  data_loading.py
drwxr-xr-x 5 dgx_user6 dgx_user6  4096  二  14 04:26  dataset
-rw-r--r-- 1 dgx_user6 dgx_user6   641  二  13 23:51  generate_dataset_csv.py
-rw-r--r-- 1 dgx_user6 dgx_user6  2687  二  13 23:51  interpolate.py
-rw-r--r-- 1 dgx_user6 dgx_user6    95  二  14 05:32  interpolate.sh
-rw-r--r-- 1 dgx_user6 dgx_user6     0  二  14 05:32  log_file
-rw-r--r-- 1 dgx_user6 dgx_user6  6555  二  13 23:51  main_gen_pseudo-data.py
-rw-r--r-- 1 dgx_user6 dgx_user6  7548  二  13 23:51  main_gen_synthetic_and_full.py
-rw-r--r-- 1 dgx_user6 dgx_user6  7030  二  14 14:12  main_mix_training.py
-rw-r--r-- 1 dgx_user6 dgx_user6 69169  二  14 05:34 'model backup.py'
-rw-r--r-- 1 dgx_user6 dgx_user6  2914  二  14 05:32  model_loading_synchronization.ipynb
-rw-r--r-- 1 dgx_user6 dgx_user6 69339  二  14 05:34  models.py
drwxr-xr-x 2 dgx_user6 dgx_user6  4096  二  13 23:51  pretrained
drwxr-xr-x 2 dgx_user6 dgx_user6  4096  二  14 05:33  __pycache__
-rw-r--r-- 1 dgx_user6 dgx_user6  3490  二  13 23:51  README.md
drwxr-xr-x 9 dgx_user6 dgx_user6  4096  二  14 05:33  results
-rw-r--r-- 1 dgx_user6 dgx_user6  5090  二  14 05:34  shading.py
-rw-r--r-- 1 dgx_user6 dgx_user6   605  二  14 05:34  super_resolution.py
-rw-r--r-- 1 dgx_user6 dgx_user6 39867  二  14 05:32 'train backup.py'
-rw-r--r-- 1 dgx_user6 dgx_user6 32377  二  13 23:51  train.py
-rw-r--r-- 1 dgx_user6 dgx_user6  1685  二  13 23:51  utils.py
</code>```

I created the container using this command

```<code>nvidia-docker run -e NVIDIA_VISIBLE_DEVICES=3 -t -i --name coba --mount type=bind,src=/home/dgx_user6/SfSNet/,dst=/app/sfsnet sfs_face
</code>```

part of the container about creating a user

```<code># Create a non-root user and switch to it
RUN adduser --disabled-password --gecos '' --shell /bin/bash user \
 && chown -R user:user /app
RUN echo "user ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/90-user
USER user

# All users can use /home/user as their home directory
ENV HOME=/home/user
RUN chmod 777 /home/user
</code>```

I hope someone can help me resolve this problem

答:
The problem is located in the results directory :

```<code>PermissionError: [Errno 13] Permission denied: './results//details.txt'
</code>```

but only the owner of the directory can write in :

drwxr-xr-x 9 dgx_user6 dgx_user6  4096  二  14 05:33  results

The image that you use specifies a user which the id differs from the user id of the directory owner on the host .

You can override that behavior by specifying the user (and optionally the group) when you start the container with the -u / --user flag (see run command reference).

For example that start the container with the user and group id of the host user :

```<code>docker run  --user $(id -u):$(id -g) myImage
</code>```

Note that ii will work only if the user and group id in the image are the same that those of the user on the host. Default is 1000:1000.

If these ids don't match, you should probably find a way to make the user or group id match for files you need to manipulate in both sides.

Body:
I am still new at using docker and currently I am planning to do a machine learning training on a supercomputer shared by many user. I have successfully created an image and mount all the necessary data but when I try to run the training, I got permission denied when the code tries to access a .txt file. Here is the error

user@701c214f9fa9:/app/sfsnet$ python main_mix_training.py
Traceback (most recent call last):
  File "main_mix_training.py", line 156, in <module>
    main()
  File "main_mix_training.py", line 132, in main
    with open(args.log_dir+'/details.txt', 'w') as f:
PermissionError: [Errno 13] Permission denied: './results//details.txt'
user@701c214f9fa9:/app/sfsnet$ python main_mix_training.py
Traceback (most recent call last):
  File "main_mix_training.py", line 156, in <module>
    main()
  File "main_mix_training.py", line 132, in main
    with open(args.log_dir+'/details.txt', 'w') as f:
PermissionError: [Errno 13] Permission denied: './results//details.txt'

I have checked the mounted directory ownership and it should all be mine (dgx_user6) :

total 308
-rw-r--r-- 1 dgx_user6 dgx_user6  1271  二  14 05:32  checkmodel.py
-rw-r--r-- 1 dgx_user6 dgx_user6   458  二  13 23:51  cropping.py
-rw-r--r-- 1 dgx_user6 dgx_user6 12890  二  14 14:03  data_loading.py
drwxr-xr-x 5 dgx_user6 dgx_user6  4096  二  14 04:26  dataset
-rw-r--r-- 1 dgx_user6 dgx_user6   641  二  13 23:51  generate_dataset_csv.py
-rw-r--r-- 1 dgx_user6 dgx_user6  2687  二  13 23:51  interpolate.py
-rw-r--r-- 1 dgx_user6 dgx_user6    95  二  14 05:32  interpolate.sh
-rw-r--r-- 1 dgx_user6 dgx_user6     0  二  14 05:32  log_file
-rw-r--r-- 1 dgx_user6 dgx_user6  6555  二  13 23:51  main_gen_pseudo-data.py
-rw-r--r-- 1 dgx_user6 dgx_user6  7548  二  13 23:51  main_gen_synthetic_and_full.py
-rw-r--r-- 1 dgx_user6 dgx_user6  7030  二  14 14:12  main_mix_training.py
-rw-r--r-- 1 dgx_user6 dgx_user6 69169  二  14 05:34 'model backup.py'
-rw-r--r-- 1 dgx_user6 dgx_user6  2914  二  14 05:32  model_loading_synchronization.ipynb
-rw-r--r-- 1 dgx_user6 dgx_user6 69339  二  14 05:34  models.py
drwxr-xr-x 2 dgx_user6 dgx_user6  4096  二  13 23:51  pretrained
drwxr-xr-x 2 dgx_user6 dgx_user6  4096  二  14 05:33  __pycache__
-rw-r--r-- 1 dgx_user6 dgx_user6  3490  二  13 23:51  README.md
drwxr-xr-x 9 dgx_user6 dgx_user6  4096  二  14 05:33  results
-rw-r--r-- 1 dgx_user6 dgx_user6  5090  二  14 05:34  shading.py
-rw-r--r-- 1 dgx_user6 dgx_user6   605  二  14 05:34  super_resolution.py
-rw-r--r-- 1 dgx_user6 dgx_user6 39867  二  14 05:32 'train backup.py'
-rw-r--r-- 1 dgx_user6 dgx_user6 32377  二  13 23:51  train.py
-rw-r--r-- 1 dgx_user6 dgx_user6  1685  二  13 23:51  utils.py

I created the container using this command

nvidia-docker run -e NVIDIA_VISIBLE_DEVICES=3 -t -i --name coba --mount type=bind,src=/home/dgx_user6/SfSNet/,dst=/app/sfsnet sfs_face

part of the container about creating a user

# Create a non-root user and switch to it
RUN adduser --disabled-password --gecos '' --shell /bin/bash user \
 && chown -R user:user /app
RUN echo "user ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/90-user
USER user

# All users can use /home/user as their home directory
ENV HOME=/home/user
RUN chmod 777 /home/user

I hope someone can help me resolve this problem

Body:
The problem is located in the results directory :

PermissionError: [Errno 13] Permission denied: './results//details.txt'

but only the owner of the directory can write in :

drwxr-xr-x 9 dgx_user6 dgx_user6  4096  二  14 05:33  results

The image that you use specifies a user which the id differs from the user id of the directory owner on the host .

You can override that behavior by specifying the user (and optionally the group) when you start the container with the -u / --user flag (see run command reference).

For example that start the container with the user and group id of the host user :

docker run  --user $(id -u):$(id -g) myImage

Note that ii will work only if the user and group id in the image are the same that those of the user on the host. Default is 1000:1000.

If these ids don't match, you should probably find a way to make the user or group id match for files you need to manipulate in both sides.


问:
ORA-00905: missing keyword - Alter table modify column not working in Oracle 10g
I regularly take caution when creating tables for database. This time I came across a situation to alter a table.

I wanted to change the Data Type of a field/column in Table.

To change the data type of a column in a table: General Syntax

```<code>ALTER TABLE table_name ALTER COLUMN column_name datatype
</code>```

SQL Query :

```<code>alter table employee modify column ename varchar(40);
</code>```

I Rarely use Alter and Modify commands. This time when tried, it throws me an Error as ORA-00905: missing keyword.

I surfed the Internet and referred StackOverflow raised questions, but there is no relative answer found.

I also referred this Oracle Documentation :
Oracle Reference Documentation

But It did not help.

答:
Try This:
ALTER TABLE Shopper MODIFY  MobileNo(varchar2(15))</p>

ContentLicense: CC BY-SA 3.0

Body:
I regularly take caution when creating tables for database. This time I came across a situation to alter a table.

I wanted to change the Data Type of a field/column in Table.

To change the data type of a column in a table: General Syntax

ALTER TABLE table_name ALTER COLUMN column_name datatype

SQL Query :

alter table employee modify column ename varchar(40);

I Rarely use Alter and Modify commands. This time when tried, it throws me an Error as ORA-00905: missing keyword.

I surfed the Internet and referred StackOverflow raised questions, but there is no relative answer found.

I also referred this Oracle Documentation :
Oracle Reference Documentation

But It did not help.


问:
Pivot Table MySQL?
I Have A Query :

```<code>SELECT item_id,
       MAX(CASE WHEN `vendor_id` = 2
                THEN price
                END) AS "Bandung",
       MAX(CASE WHEN `vendor_id` = 3
                THEN price
                END) AS "Vendor Bandung",
       MAX(CASE WHEN `vendor_id` = 4
                THEN price
                END) AS "Jakarta",
       MIN(price)
FROM transactions
GROUP BY item_id
</code>```

Output:

I Want to get detail information about price from where,.. like below

```<code>|ItemID|Bandung|Vendor Bandung|Jakarta |Price Min|*Area*
|10001 |12000  |11000         |9000    |9000     |*Jakarta|*
|10002 |12000  |11000         |12400   |11000    |*Vendor Bandung|*
|10004 |12000  |11000         |12400   |11000    |*Vendor Bandung|*
|10005 |12000  |11000         |12400   |11000    |*Vendor Bandung|*
</code>```

答:
SQL

```<code>SELECT DATASET.`bandung`,
   DATASET.`vendor bandung`,
   DATASET.`jakarta`,
   DATASET.`price min`,
   ( CASE DATASET.`price min`
       WHEN DATASET.`bandung` THEN "bandung"
       WHEN DATASET.`vendor bandung` THEN "vendor bandung"
       WHEN DATASET.`jakarta` THEN "jakarta"
       ELSE "otrher"
     end ) AS "Area"
FROM (SELECT item_id,
           Max(CASE
                 WHEN `vendor_id` = 2 THEN price
               end)   AS "Bandung",
           Max(CASE
                 WHEN `vendor_id` = 3 THEN price
               end)   AS "Vendor Bandung",
           Max(CASE
                 WHEN `vendor_id` = 4 THEN price
               end)   AS "Jakarta",
           Min(price) AS "Price Min"
    FROM   transactions
    GROUP  BY item_id) DATASET
</code>```

Table

```<code>SELECT * FROM transactions;
</code>```

Result

Title: Pivot Table MySQL?

Body:
I Have A Query :

SELECT item_id,
       MAX(CASE WHEN `vendor_id` = 2
                THEN price
                END) AS "Bandung",
       MAX(CASE WHEN `vendor_id` = 3
                THEN price
                END) AS "Vendor Bandung",
       MAX(CASE WHEN `vendor_id` = 4
                THEN price
                END) AS "Jakarta",
       MIN(price)
FROM transactions
GROUP BY item_id

Output:

I Want to get detail information about price from where,.. like below

|ItemID|Bandung|Vendor Bandung|Jakarta |Price Min|*Area*
|10001 |12000  |11000         |9000    |9000     |*Jakarta|*
|10002 |12000  |11000         |12400   |11000    |*Vendor Bandung|*
|10004 |12000  |11000         |12400   |11000    |*Vendor Bandung|*
|10005 |12000  |11000         |12400   |11000    |*Vendor Bandung|*

Body:
SQL

SELECT DATASET.`bandung`,
   DATASET.`vendor bandung`,
   DATASET.`jakarta`,
   DATASET.`price min`,
   ( CASE DATASET.`price min`
       WHEN DATASET.`bandung` THEN "bandung"
       WHEN DATASET.`vendor bandung` THEN "vendor bandung"
       WHEN DATASET.`jakarta` THEN "jakarta"
       ELSE "otrher"
     end ) AS "Area"
FROM (SELECT item_id,
           Max(CASE
                 WHEN `vendor_id` = 2 THEN price
               end)   AS "Bandung",
           Max(CASE
                 WHEN `vendor_id` = 3 THEN price
               end)   AS "Vendor Bandung",
           Max(CASE
                 WHEN `vendor_id` = 4 THEN price
               end)   AS "Jakarta",
           Min(price) AS "Price Min"
    FROM   transactions
    GROUP  BY item_id) DATASET

Table

SELECT * FROM transactions;

Result


问:
Wrapping an object and pretend it's an int
I have a class Object that I'd like to use as if it were an int. In other words I want to pass this object to functions that accepts int, int* or int& so that the functions "see" actually ony the wrapped int value.

The code below illustrates what I want to do. I was able to write the code for int and int* but I'm not able to write the code for int&.

```<code>#include <cassert>

class Object
{
public:
  int bla = 0;
  int val = 0;   // the int being wrapped

  Object(int v) : val(v) {};
  operator int() const { return val; };
  int *operator &() { return &val; };

#if 1
  int & operator() { return val; };   // << does not compile
#endif
};

int func(int val) {
  return val * 2;
}

void Bar(int* pval, int val) {
  *pval = val;
}

void Foo(int & pval, int val) {
  pval = val;
}

int main() {
  int val;
  Bar(&val, 123);
  assert(val == 123);
  Foo(val, 789);
  assert(val == 789);

  Object o(8);
  assert(func(o) == 2 * 8);   // operator int()
  Bar(&o, 1234);              // int *operator &()
  assert(o.val == 1234);

#if 1
  Foo(o, 456);                // << does not compile
  assert(o.val == 456);
#endif
}
</code>```

If  #if 1 is replaced with #if 0, the code works as expected.

Could anybody point me into the right direction so Foo(o, 456); compiles?

答:
The problem is the conversion operator, which you have the wrong syntax for.

It should be

```<code>operator int&() { return val; }
</code>```

Body:
I have a class Object that I'd like to use as if it were an int. In other words I want to pass this object to functions that accepts int, int* or int& so that the functions "see" actually ony the wrapped int value.

The code below illustrates what I want to do. I was able to write the code for int and int* but I'm not able to write the code for int&.

#include <cassert>

class Object
{
public:
  int bla = 0;
  int val = 0;   // the int being wrapped

  Object(int v) : val(v) {};
  operator int() const { return val; };
  int *operator &() { return &val; };

#if 1
  int & operator() { return val; };   // << does not compile
#endif
};

int func(int val) {
  return val * 2;
}

void Bar(int* pval, int val) {
  *pval = val;
}

void Foo(int & pval, int val) {
  pval = val;
}

int main() {
  int val;
  Bar(&val, 123);
  assert(val == 123);
  Foo(val, 789);
  assert(val == 789);

  Object o(8);
  assert(func(o) == 2 * 8);   // operator int()
  Bar(&o, 1234);              // int *operator &()
  assert(o.val == 1234);

#if 1
  Foo(o, 456);                // << does not compile
  assert(o.val == 456);
#endif
}

If  #if 1 is replaced with #if 0, the code works as expected.

Could anybody point me into the right direction so Foo(o, 456); compiles?

Body:
The problem is the conversion operator, which you have the wrong syntax for.

It should be

operator int&() { return val; }


问:
Kafka-streams application error using mapValue() method with Gson
I write a kafka-streams application that getting data from topic "topic_one" (data had received from MySQL). Then I want to get a part (section "after", see below) of this data with KStream interface to make other operations. But I have an error with serialization then I use mapValue(). I am a new in kafka-streams and have no idea how to make and use a proper serde. Can anybody help me?

Source data from topic_one:

```<code>[KSTREAM-SOURCE-0000000000]: null, {"before": null, "after": {"id": 1, "category": 1, "item": "abc"}, "source": {"version": "0.8.3.Final", "name": "example", "server_id": 1, "ts_sec": 1581491071, "gtid": null, "file": "mysql-bin.000013", "pos": 217827349, "row": 0, "snapshot": false, "thread": 95709, "db": "example", "table": "item", "query": null}, "op": "c", "ts_ms": 1581491071727}
</code>```

I want to get:

```<code>{"id": 1, "category": 1, "item": "abc"}
</code>```

My code:

```<code>    Properties properties = getProperties();

    try {
        StreamsBuilder builder = new StreamsBuilder();

        KStream<String, String> resourceStream = builder.stream("topic_one");
        resourceStream.print(Printed.toSysOut());

        KStream<String, String> resultStream = resourceStream.mapValues(value ->
                new Gson().fromJson(value, JsonObject.class).get("after").getAsJsonObject().toString());
        resultStream.print(Printed.toSysOut());

        Topology topology = builder.build();

        KafkaStreams streams = new KafkaStreams(topology, properties);

        streams.cleanUp();
        streams.start();

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

private static Properties getProperties() {

    Properties properties = new Properties(); // TODO настройки вынести в отдельный файл?

    properties.put(StreamsConfig.APPLICATION_ID_CONFIG, "app_id");
    properties.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
    properties.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
    properties.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, GenericAvroSerde.class);
    properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
    properties.put("schema.registry.url", "http://localhost:8081");

    return properties;
}
</code>```

Error:

```<code>Exception in thread "streams_id-db618fbf-c3e4-468b-a5a2-18e6b0b9c6be-StreamThread-1" org.apache.kafka.streams.errors.StreamsException: Exception caught in process. taskId=0_0, processor=KSTREAM-SOURCE-0000000000, topic=matomo.matomo.matomo_scenarios_directory, partition=0, offset=30, stacktrace=org.apache.kafka.streams.errors.StreamsException: ClassCastException invoking Processor. Do the Processor's input types match the deserialized types? Check the Serde setup and change the default Serdes in StreamConfig or provide correct Serdes via method parameters. **Make sure the Processor can accept the deserialized input of type key: unknown because key is null, and value: org.apache.avro.generic.GenericData$Record.
Note that although incorrect Serdes are a common cause of error, the cast exception might have another cause (in user code, for example). For example, if a processor wires in a store, but casts the generics incorrectly, a class cast exception could be raised during processing, but the cause would not be wrong Serdes.**
    at org.apache.kafka.streams.processor.internals.ProcessorNode.process(ProcessorNode.java:122)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:201)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:180)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:133)
    at org.apache.kafka.streams.processor.internals.SourceNode.process(SourceNode.java:87)
    at org.apache.kafka.streams.processor.internals.StreamTask.process(StreamTask.java:429)
    at org.apache.kafka.streams.processor.internals.AssignedStreamsTasks.process(AssignedStreamsTasks.java:474)
    at org.apache.kafka.streams.processor.internals.TaskManager.process(TaskManager.java:536)
    at org.apache.kafka.streams.processor.internals.StreamThread.runOnce(StreamThread.java:792)
    at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:698)
    at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:671)
Caused by: java.lang.ClassCastException: org.apache.avro.generic.GenericData$Record cannot be cast to java.lang.String
    at org.apache.kafka.streams.kstream.internals.AbstractStream.lambda$withKey$1(AbstractStream.java:103)
    at org.apache.kafka.streams.kstream.internals.KStreamMapValues$KStreamMapProcessor.process(KStreamMapValues.java:40)
    at org.apache.kafka.streams.processor.internals.ProcessorNode.process(ProcessorNode.java:118)
    ... 10 more

    at org.apache.kafka.streams.processor.internals.StreamTask.process(StreamTask.java:446)
    at org.apache.kafka.streams.processor.internals.AssignedStreamsTasks.process(AssignedStreamsTasks.java:474)
    at org.apache.kafka.streams.processor.internals.TaskManager.process(TaskManager.java:536)
    at org.apache.kafka.streams.processor.internals.StreamThread.runOnce(StreamThread.java:792)
    at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:698)
    at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:671)
**Caused by: org.apache.kafka.streams.errors.StreamsException: ClassCastException invoking Processor. Do the Processor's input types match the deserialized types? Check the Serde setup and change the default Serdes in StreamConfig or provide correct Serdes via method parameters. Make sure the Processor can accept the deserialized input of type key: unknown because key is null, and value: org.apache.avro.generic.GenericData$Record.**
Note that although incorrect Serdes are a common cause of error, the cast exception might have another cause (in user code, for example). For example, if a processor wires in a store, but casts the generics incorrectly, a class cast exception could be raised during processing, but the cause would not be wrong Serdes.
    at org.apache.kafka.streams.processor.internals.ProcessorNode.process(ProcessorNode.java:122)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:201)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:180)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:133)
    at org.apache.kafka.streams.processor.internals.SourceNode.process(SourceNode.java:87)
    at org.apache.kafka.streams.processor.internals.StreamTask.process(StreamTask.java:429)
    ... 5 more
Caused by: java.lang.ClassCastException: org.apache.avro.generic.GenericData$Record cannot be cast to java.lang.String
    at org.apache.kafka.streams.kstream.internals.AbstractStream.lambda$withKey$1(AbstractStream.java:103)
    at org.apache.kafka.streams.kstream.internals.KStreamMapValues$KStreamMapProcessor.process(KStreamMapValues.java:40)
    at org.apache.kafka.streams.processor.internals.ProcessorNode.process(ProcessorNode.java:118)
    ... 10 more
</code>```

答:
In your getProperties() method, you defined your value serde as GenericAvroSerde.class, but when you create the streams, you are using String as value type. That's why you get the exception at runtime.

KStream<String, String> resourceStream = ...
KStream<String, String> resultStream = ...
```

<p>If you really use Avro as message format, then you have the use the correct types, when defining you <code>KStream</code>. But as it seems, you have just JSON strings as values, so you can probably just set the correct value serde by replacing</p>

<pre class="lang-java prettyprint-override"><code>properties.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, GenericAvroSerde.class);
</code>```

with

properties.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
```

Hope it helps.

Body:
I write a kafka-streams application that getting data from topic "topic_one" (data had received from MySQL). Then I want to get a part (section "after", see below) of this data with KStream interface to make other operations. But I have an error with serialization then I use mapValue(). I am a new in kafka-streams and have no idea how to make and use a proper serde. Can anybody help me?

Source data from topic_one:

[KSTREAM-SOURCE-0000000000]: null, {"before": null, "after": {"id": 1, "category": 1, "item": "abc"}, "source": {"version": "0.8.3.Final", "name": "example", "server_id": 1, "ts_sec": 1581491071, "gtid": null, "file": "mysql-bin.000013", "pos": 217827349, "row": 0, "snapshot": false, "thread": 95709, "db": "example", "table": "item", "query": null}, "op": "c", "ts_ms": 1581491071727}

I want to get:

{"id": 1, "category": 1, "item": "abc"}

My code:

    Properties properties = getProperties();

    try {
        StreamsBuilder builder = new StreamsBuilder();

        KStream<String, String> resourceStream = builder.stream("topic_one");
        resourceStream.print(Printed.toSysOut());

        KStream<String, String> resultStream = resourceStream.mapValues(value ->
                new Gson().fromJson(value, JsonObject.class).get("after").getAsJsonObject().toString());
        resultStream.print(Printed.toSysOut());

        Topology topology = builder.build();

        KafkaStreams streams = new KafkaStreams(topology, properties);

        streams.cleanUp();
        streams.start();

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

private static Properties getProperties() {

    Properties properties = new Properties(); // TODO настройки вынести в отдельный файл?

    properties.put(StreamsConfig.APPLICATION_ID_CONFIG, "app_id");
    properties.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
    properties.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
    properties.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, GenericAvroSerde.class);
    properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
    properties.put("schema.registry.url", "http://localhost:8081");

    return properties;
}

Error:

Exception in thread "streams_id-db618fbf-c3e4-468b-a5a2-18e6b0b9c6be-StreamThread-1" org.apache.kafka.streams.errors.StreamsException: Exception caught in process. taskId=0_0, processor=KSTREAM-SOURCE-0000000000, topic=matomo.matomo.matomo_scenarios_directory, partition=0, offset=30, stacktrace=org.apache.kafka.streams.errors.StreamsException: ClassCastException invoking Processor. Do the Processor's input types match the deserialized types? Check the Serde setup and change the default Serdes in StreamConfig or provide correct Serdes via method parameters. **Make sure the Processor can accept the deserialized input of type key: unknown because key is null, and value: org.apache.avro.generic.GenericData$Record.
Note that although incorrect Serdes are a common cause of error, the cast exception might have another cause (in user code, for example). For example, if a processor wires in a store, but casts the generics incorrectly, a class cast exception could be raised during processing, but the cause would not be wrong Serdes.**
    at org.apache.kafka.streams.processor.internals.ProcessorNode.process(ProcessorNode.java:122)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:201)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:180)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:133)
    at org.apache.kafka.streams.processor.internals.SourceNode.process(SourceNode.java:87)
    at org.apache.kafka.streams.processor.internals.StreamTask.process(StreamTask.java:429)
    at org.apache.kafka.streams.processor.internals.AssignedStreamsTasks.process(AssignedStreamsTasks.java:474)
    at org.apache.kafka.streams.processor.internals.TaskManager.process(TaskManager.java:536)
    at org.apache.kafka.streams.processor.internals.StreamThread.runOnce(StreamThread.java:792)
    at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:698)
    at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:671)
Caused by: java.lang.ClassCastException: org.apache.avro.generic.GenericData$Record cannot be cast to java.lang.String
    at org.apache.kafka.streams.kstream.internals.AbstractStream.lambda$withKey$1(AbstractStream.java:103)
    at org.apache.kafka.streams.kstream.internals.KStreamMapValues$KStreamMapProcessor.process(KStreamMapValues.java:40)
    at org.apache.kafka.streams.processor.internals.ProcessorNode.process(ProcessorNode.java:118)
    ... 10 more

    at org.apache.kafka.streams.processor.internals.StreamTask.process(StreamTask.java:446)
    at org.apache.kafka.streams.processor.internals.AssignedStreamsTasks.process(AssignedStreamsTasks.java:474)
    at org.apache.kafka.streams.processor.internals.TaskManager.process(TaskManager.java:536)
    at org.apache.kafka.streams.processor.internals.StreamThread.runOnce(StreamThread.java:792)
    at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:698)
    at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:671)
**Caused by: org.apache.kafka.streams.errors.StreamsException: ClassCastException invoking Processor. Do the Processor's input types match the deserialized types? Check the Serde setup and change the default Serdes in StreamConfig or provide correct Serdes via method parameters. Make sure the Processor can accept the deserialized input of type key: unknown because key is null, and value: org.apache.avro.generic.GenericData$Record.**
Note that although incorrect Serdes are a common cause of error, the cast exception might have another cause (in user code, for example). For example, if a processor wires in a store, but casts the generics incorrectly, a class cast exception could be raised during processing, but the cause would not be wrong Serdes.
    at org.apache.kafka.streams.processor.internals.ProcessorNode.process(ProcessorNode.java:122)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:201)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:180)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:133)
    at org.apache.kafka.streams.processor.internals.SourceNode.process(SourceNode.java:87)
    at org.apache.kafka.streams.processor.internals.StreamTask.process(StreamTask.java:429)
    ... 5 more
Caused by: java.lang.ClassCastException: org.apache.avro.generic.GenericData$Record cannot be cast to java.lang.String
    at org.apache.kafka.streams.kstream.internals.AbstractStream.lambda$withKey$1(AbstractStream.java:103)
    at org.apache.kafka.streams.kstream.internals.KStreamMapValues$KStreamMapProcessor.process(KStreamMapValues.java:40)
    at org.apache.kafka.streams.processor.internals.ProcessorNode.process(ProcessorNode.java:118)
    ... 10 more

Body:
In your getProperties() method, you defined your value serde as GenericAvroSerde.class, but when you create the streams, you are using String as value type. That's why you get the exception at runtime.

KStream<String, String> resourceStream = ...
KStream<String, String> resultStream = ...

If you really use Avro as message format, then you have the use the correct types, when defining you KStream. But as it seems, you have just JSON strings as values, so you can probably just set the correct value serde by replacing

properties.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, GenericAvroSerde.class);

with

properties.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());

Hope it helps.


问:
Python - Create a new sublist between two elements in an ordered list
Given two elements in an ordered list, I want to make a  new list consisting of everything between (and including) those elements.
The problem comes if the second point comes before the first point in the list.
right is my existing sorted list of objects. rt is the beginning boundary and rb is the end boundary.
new_right = right[right.index(rt): right.index(rb) + 1]

This snippet works except in the case

right = [a, rb, c, rt, d, e]

where I get [rt, d, e] instead of the wrapped [rt, d, e, a, rb]

Is there a way to do this without creating a complicated method? Some other people's problems were solved by list comprehension. Looking into it, I was able to come up with

```<code>begin = right.index(rt)
end = right.index(rb)
if end > begin:
    new_right = right[begin: end + 1]
else:
    new_right = [right[i % r_len] for i in range(begin, r_len + end + 1)]
</code>```

Which looks pretty ugly to me, but it seems to hold up to my tests.
Is there a better way to do this?

EDIT:
There were two working solutions to this.

```<code>rbegin = right.index(rt)
rend = right.index(rb)
if rend >= rbegin:
    new_right = right[rbegin: rend + 1]
else:
    new_right = [right[i % r_len] for i in range(rbegin, r_len + rend + 1)]
</code>```

Which is obscenely complicated compared to:

```<code>if rend > rbegin:
    new_right = right[rbegin: rend + 1]
else:
    new_right = right[rbegin:] + right[:rend + 1]
</code>```

答:
You can add the trailing and leading slices instead of using a comprehension.  Using your code structure:</p>

```<code>begin = right.index(rt)
end = right.index(rb)
if end > begin:
    new_right = right[begin: end + 1]
else:
    new_right = right[begin:] + right[:end + 1]
</code>```

Body:
Given two elements in an ordered list, I want to make a  new list consisting of everything between (and including) those elements.
The problem comes if the second point comes before the first point in the list.
right is my existing sorted list of objects. rt is the beginning boundary and rb is the end boundary.
new_right = right[right.index(rt): right.index(rb) + 1]

This snippet works except in the case

right = [a, rb, c, rt, d, e]

where I get [rt, d, e] instead of the wrapped [rt, d, e, a, rb]

Is there a way to do this without creating a complicated method? Some other people's problems were solved by list comprehension. Looking into it, I was able to come up with

begin = right.index(rt)
end = right.index(rb)
if end > begin:
    new_right = right[begin: end + 1]
else:
    new_right = [right[i % r_len] for i in range(begin, r_len + end + 1)]

Which looks pretty ugly to me, but it seems to hold up to my tests.
Is there a better way to do this?

EDIT:
There were two working solutions to this.

rbegin = right.index(rt)
rend = right.index(rb)
if rend >= rbegin:
    new_right = right[rbegin: rend + 1]
else:
    new_right = [right[i % r_len] for i in range(rbegin, r_len + rend + 1)]

Which is obscenely complicated compared to:

if rend > rbegin:
    new_right = right[rbegin: rend + 1]
else:
    new_right = right[rbegin:] + right[:rend + 1]

Body:
You can add the trailing and leading slices instead of using a comprehension.  Using your code structure:

begin = right.index(rt)
end = right.index(rb)
if end > begin:
    new_right = right[begin: end + 1]
else:
    new_right = right[begin:] + right[:end + 1]


问:
Looking for free collection of different vCards (*.vcf)
I am currently working on a vCard parser. For the testing of the different edge cases of vCards (the standard allows a high variance) I need a collection of vCards from different sources.
At the moment I am working with some vCards I created on my own and was wondering if there is a free collection of vCards (*.vcf) in the web which I can use for testing purposes.</p>

答:
Here is a LGPL vcard test suite for testing vCard parsers:

https://gitlab.com/pwithnall/vcard-test-suite/-/tree/master

It cover valid and invalid card and looks extensive.


问:
What is wrong in this C++ code snippet with template<class Vector>
Here I am just using test() function and passing vector to it.
in test function using decltype() to deduce the type but output is completely mysterious. </p>

```<code>#include <vector>
#include <stdio.h>

template<class Vector>
void test(Vector& vec)
{
    using E = decltype(vec[0]);
    for (int i=0; i < 10; ++i) {
        vec.push_back(E(i));
    }
}

int main() {
    std::vector<double> v;
    test(v);
    for (int i=0; i < 10; ++i) {
        printf("%f\n", v[i]);
    }
}
</code>```

答:
E is double&, not double, as shown when you change the push_back line to

```<code>vec.push_back(static_cast<E>(i));
</code>```

"error: invalid static_cast from type ‘int’ to type ‘E’ {aka ‘double&’}"

Because of this, you are actually modifying the internal representation of double, as if you were using reinterpret_cast. You should use static_cast to convert between values.

Use either of these definitions instead:

```<code>using E = std::remove_reference_t<decltype(vec.at(0))>;
using E = typename Vector::value_type;
</code>```

Body:
Here I am just using test() function and passing vector to it.
in test function using decltype() to deduce the type but output is completely mysterious.

#include <vector>
#include <stdio.h>

template<class Vector>
void test(Vector& vec)
{
    using E = decltype(vec[0]);
    for (int i=0; i < 10; ++i) {
        vec.push_back(E(i));
    }
}

int main() {
    std::vector<double> v;
    test(v);
    for (int i=0; i < 10; ++i) {
        printf("%f\n", v[i]);
    }
}

Body:
E is double&, not double, as shown when you change the push_back line to

vec.push_back(static_cast<E>(i));

"error: invalid static_cast from type ‘int’ to type ‘E’ {aka ‘double&’}"

Because of this, you are actually modifying the internal representation of double, as if you were using reinterpret_cast. You should use static_cast to convert between values.

Use either of these definitions instead:

using E = std::remove_reference_t<decltype(vec.at(0))>;
using E = typename Vector::value_type;


问:
Double spacing lines in a Linux terminal
Does anyone know if it's possible to force terminal to append a \n to every line it prints (or something similar)?

I'm trying to debug some insane code which gives me errors the full width of my (24") screen and three lines long, so I'd appreciate not having to copy things into gedit and manually spacing them out every time I press make.

Cheers, Ed

N.B. I'm using "make 2>&1 | more" so I can't just do "| sed G"

(EDITED for clarity)

答:
If you just want to double space the output of a command or something, you can pipe it through sed to double space:

$> your_command | sed G

OwnerDisplayName: Ed Woodcock

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Ed Woodcock

OwnerDisplayName: sykora


问:
Lambda function is triggering twice on DynamoDB event
I have Lambda Function which attached to DynamoDB change event.
The Lambda is triggering twice when I change/modify an item in the Test-machines table in the DynamoDB.

I am modifying IsMachineOn value from True to False, It is trigger Test-Machine-On-alert-status Lambda function twice.

I am not understanding why two-time lambda is a trigger.

I observed a small change in the records in the event parameter of Lambda.

For first trigger,

Value of NewImage["IsMachineOn"]["BOOL"] is False

Value of OldImage["IsMachineOn"]["BOOL"] is True

For Second trigger,

Value of NewImage["IsMachineOn"]["BOOL"] is False

Value of OldImage["IsMachineOn"]["BOOL"] is False

I have business logic on NewImage["IsMachineOn"]["BOOL"]==False so that my business logic is running twice.

There are two things:

Why Lambda is running twice?

What will be a workaround to fix this issue?

答:
I also would check, if the record has changed!
Therefore I wrote the following code in Python 3.6

old_sites = set()
    new_sites = set()

    # Calculate the disjoint quantity of NEW & OLD mappings
    for image_name in ['OldImage', 'NewImage']:
        if record['dynamodb'] is not None and image_name in record['dynamodb']:
            ddb_entry = record['dynamodb'][image_name]
            mappings = ddb_entry[value_key]['L']
            print(f"mappings: {mappings}")

            for mapping in mappings:
                old_sites.add(mapping['S']) if image_name == 'OldImage' else new_sites.add(mapping['S'])

    changed_mappings = old_sites.symmetric_difference(new_sites)
```


问:
SwiftUI - How can a TextField increase dynamically its height based on its content?
I am trying to build a "chat" view using SwiftUI and I would like to know how can I do in order to increase the height dynamically of a TextField where the users should write their messages.

I have defined a minHeight expecting that the TextField could increase its height based on its intrinsic content.

My current view code:

```<code>struct MessageSenderView: View {
    @Binding var userTextInput: String

    var body: some View {
        VStack {
            HStack(alignment: .center, spacing: 17) {
                senderPlusImage()
                ZStack {
                    Capsule()
                        .fill(Color("messagesBankDetailColor"))
                        .frame(minHeight: 34, alignment: .bottom)
                    HStack(spacing: 15){
                        Spacer()
                        ZStack(alignment: .leading) {
                            if userTextInput.isEmpty { Text(Constants.Login.Text.userPlaceHolder).foregroundColor(Color.white) }
                            TextField(" ", text: $userTextInput)
                                .multilineTextAlignment(.leading)
                                .frame(minHeight: CGFloat(34))
                                .foregroundColor(Color.white)
                                .background(Color("messagesBankDetailColor"))
                                .onAppear { self.userTextInput = "" }
                        }
                        arrowImage()
                    }
                    .frame(minHeight: CGFloat(34))
                    .padding(.trailing, 16)
                    .layoutPriority(100)
                }
            }
            .padding(16)
        }
        .background(Color("mainBackgroundColor"))
    }
}
</code>```

And here is how it looks like:

Thank you!!!!

答:
For this purpose, you should use UITextfield with the UIViewRepresentable protocol.
Maybe this tutorial can help you : Dynamic TextField SwiftUI

Body:
I am trying to build a "chat" view using SwiftUI and I would like to know how can I do in order to increase the height dynamically of a TextField where the users should write their messages.

I have defined a minHeight expecting that the TextField could increase its height based on its intrinsic content.

My current view code:

struct MessageSenderView: View {
    @Binding var userTextInput: String

    var body: some View {
        VStack {
            HStack(alignment: .center, spacing: 17) {
                senderPlusImage()
                ZStack {
                    Capsule()
                        .fill(Color("messagesBankDetailColor"))
                        .frame(minHeight: 34, alignment: .bottom)
                    HStack(spacing: 15){
                        Spacer()
                        ZStack(alignment: .leading) {
                            if userTextInput.isEmpty { Text(Constants.Login.Text.userPlaceHolder).foregroundColor(Color.white) }
                            TextField(" ", text: $userTextInput)
                                .multilineTextAlignment(.leading)
                                .frame(minHeight: CGFloat(34))
                                .foregroundColor(Color.white)
                                .background(Color("messagesBankDetailColor"))
                                .onAppear { self.userTextInput = "" }
                        }
                        arrowImage()
                    }
                    .frame(minHeight: CGFloat(34))
                    .padding(.trailing, 16)
                    .layoutPriority(100)
                }
            }
            .padding(16)
        }
        .background(Color("mainBackgroundColor"))
    }
}

And here is how it looks like:

Thank you!!!!


问:
Java "Formatter" vs. "FileOutputStream": Very simple explanation desired of when to use which
I am learning the basics of Java IO and cannot find what I would think would be covered in basic discussions of IO in java: without getting into subtleties or complexities (unless necessary), what is the very basic explanation of when you would choose one vs. when you would choose the other for output to a file (Formatter vs. FileOutputStream)?

I assume the same explanation will hold for Scanner vs. FileInputStream.

答:
You use an OutputStream (possibly a FileOutputStream) to write bytes.

You use a Formatter to write formatted text.

The first is very efficient but you have to know what bytes to write. The second gives you flexible formatting features, but is limited in what it can write, and is likely to be less efficient than the first.


问:
Is ISTIO internal traffic routing possible with custom gateway?
Is ISTIO internal traffic routing to different versions possible even when I use custom gateways? (Azure App gateway). Below is my use case. I have two different versions of deployments (Kubernetes) with the labels app:myapp & version: v1 and version: v2 [v1 label for one deployment and v2 label for another]. The traffic is currently evenly distributed between these two and the same can be seen in kiali dashboard too. I want to route traffic only to v2. Below are my virtual service and destination rules.

VIRTUAL SERVICE:

```<code>apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: myvirtualservice
  namespace: mynamespace # Use same namespace with backend service
spec:
  hosts:
  - myservice.namespace.svc.cluster.local
  ingress:
  - appgw # define ingress name
  http:
  - match:
    - uri:
        prefix: "/"
    route:
    - destination:
        port:
          number: 80 # Backend service port
        host: myservice.namespace.svc.cluster.local # Backend service name
        subset: v2
</code>```

DESTINATION RULE:

```<code>apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
  name: mydestrule
spec:
  host: myservice.namespace.svc.cluster.local
  subsets:
  - name: v2
    labels:
      version: v2
</code>```

Currently in the kiali dashboard too my azure ingress gateway is shown as "unknown" resource.

答:
If I see it correctly you are missing the subset selector in the Destination of the VirtualService.
If you configure the VirtualService like this it should work better:

```<code>apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: myvirtualservice
  namespace: mynamespace # Use same namespace with backend service
spec:
  hosts:
  - myservice.namespace.svc.cluster.local
  ingress:
  - appgw # define ingress name
  http:
  - match:
    - uri:
        prefix: "/"
    route:
    - destination:
        port:
          number: 80
        host: myservice.namespace.svc.cluster.local
        subset: v2 # <- Route to the subset v2 and enable endpoint select by label
</code>```

See https://istio.io/docs/reference/config/networking/virtual-service/#Destination

Body:
Is ISTIO internal traffic routing to different versions possible even when I use custom gateways? (Azure App gateway). Below is my use case. I have two different versions of deployments (Kubernetes) with the labels app:myapp & version: v1 and version: v2 [v1 label for one deployment and v2 label for another]. The traffic is currently evenly distributed between these two and the same can be seen in kiali dashboard too. I want to route traffic only to v2. Below are my virtual service and destination rules.

VIRTUAL SERVICE:

apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: myvirtualservice
  namespace: mynamespace # Use same namespace with backend service
spec:
  hosts:
  - myservice.namespace.svc.cluster.local
  ingress:
  - appgw # define ingress name
  http:
  - match:
    - uri:
        prefix: "/"
    route:
    - destination:
        port:
          number: 80 # Backend service port
        host: myservice.namespace.svc.cluster.local # Backend service name
        subset: v2

DESTINATION RULE:

apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
  name: mydestrule
spec:
  host: myservice.namespace.svc.cluster.local
  subsets:
  - name: v2
    labels:
      version: v2

Currently in the kiali dashboard too my azure ingress gateway is shown as "unknown" resource.

Body:
If I see it correctly you are missing the subset selector in the Destination of the VirtualService.
If you configure the VirtualService like this it should work better:

apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: myvirtualservice
  namespace: mynamespace # Use same namespace with backend service
spec:
  hosts:
  - myservice.namespace.svc.cluster.local
  ingress:
  - appgw # define ingress name
  http:
  - match:
    - uri:
        prefix: "/"
    route:
    - destination:
        port:
          number: 80
        host: myservice.namespace.svc.cluster.local
        subset: v2 # <- Route to the subset v2 and enable endpoint select by label

See https://istio.io/docs/reference/config/networking/virtual-service/#Destination


问:
Laravel query join 1 table in 2 tables at single query
I have a complex query and it works, now i need to join users table and get 2 different value of it based on 2 different tables here is where things messed up.

Code

I have commented issue part as well as data that should be returned

```<code>$datas = DB::table('projects')
    ->orderBy('projects.id', 'desc')
    ->join('customers', 'projects.customer_id', '=', 'customers.id')
    ->leftjoin('project_schedules', 'projects.id', '=', 'project_schedules.project_id')
    ->leftjoin('project_schedule_details', 'project_schedules.id', '=', 'project_schedule_details.schedule_id')
    ->leftjoin('project_schedule_visits', 'projects.id', '=', 'project_schedule_visits.project_id')

    // issue tables (project_admins) and (project_shoppers)
    ->leftjoin('project_admins', 'projects.id', '=', 'project_admins.project_id')
    ->leftjoin('project_shoppers', 'projects.id', '=', 'project_shoppers.project_id')

    ->groupBy('projects.id')
    ->select(
        'projects.name as project',
        'customers.companyName as customer',
        'project_schedule_details.date as schedule_date',
        'project_schedule_details.description as schedule_description',
        'project_schedule_details.actual_cost as schedule_actual_cost',
        'project_schedule_visits.from_date as visit_from_date',
        'project_schedule_visits.to_date as visit_to_date',
        'project_schedule_visits.description as visit_description'
        // 'project_admins.user.username as admin'  //i.e. user 1
        // 'project_shoppers.user.username as shopper' // i.e user 2
    )
    ->get();
</code>```

Explanation:

I need to join users table to project_admins table as well as project_shoppers table and return related users to those tables.

Then I would have user 1 returned based on project_admins table
And user 2 based on project_shoppers table.

Any idea how to achieve that goal?

答:
Under the leftJoins you can add the extra joins for getting the users:

```<code>->leftJoin('users','users2.id','=','project_admins.user_id')
->leftJoin('users AS users2','users2.id','=','project_shoppers.user_id')
</code>```

In your select you can get the details like this:

```<code>->select(
...,
'users.username AS admin',
'users2.username AS shopper'
)
</code>```

Body:
I have a complex query and it works, now i need to join users table and get 2 different value of it based on 2 different tables here is where things messed up.

Code

I have commented issue part as well as data that should be returned

$datas = DB::table('projects')
    ->orderBy('projects.id', 'desc')
    ->join('customers', 'projects.customer_id', '=', 'customers.id')
    ->leftjoin('project_schedules', 'projects.id', '=', 'project_schedules.project_id')
    ->leftjoin('project_schedule_details', 'project_schedules.id', '=', 'project_schedule_details.schedule_id')
    ->leftjoin('project_schedule_visits', 'projects.id', '=', 'project_schedule_visits.project_id')

    // issue tables (project_admins) and (project_shoppers)
    ->leftjoin('project_admins', 'projects.id', '=', 'project_admins.project_id')
    ->leftjoin('project_shoppers', 'projects.id', '=', 'project_shoppers.project_id')

    ->groupBy('projects.id')
    ->select(
        'projects.name as project',
        'customers.companyName as customer',
        'project_schedule_details.date as schedule_date',
        'project_schedule_details.description as schedule_description',
        'project_schedule_details.actual_cost as schedule_actual_cost',
        'project_schedule_visits.from_date as visit_from_date',
        'project_schedule_visits.to_date as visit_to_date',
        'project_schedule_visits.description as visit_description'
        // 'project_admins.user.username as admin'  //i.e. user 1
        // 'project_shoppers.user.username as shopper' // i.e user 2
    )
    ->get();

Explanation:

I need to join users table to project_admins table as well as project_shoppers table and return related users to those tables.

Then I would have user 1 returned based on project_admins table
And user 2 based on project_shoppers table.

Any idea how to achieve that goal?

Body:
Under the leftJoins you can add the extra joins for getting the users:

->leftJoin('users','users2.id','=','project_admins.user_id')
->leftJoin('users AS users2','users2.id','=','project_shoppers.user_id')

In your select you can get the details like this:

->select(
...,
'users.username AS admin',
'users2.username AS shopper'
)


问:
How to separate longitude and latitude from OpenLayers coordinates
The openLayers mousePosition returns the coordinates x,y of the cursor position. </p>

```<code>var mousePosition = new ol.control.MousePosition({
        undefinedHTML: ' ',
        projection: 'EPSG:4326',
        coordinateFormat: function(coordinate) {
                        return ol.coordinate.format(coordinate, '{x}, {y}', 6);
                      },
        className: 'ol-mouse-position',
        target: document.getElementById('myposition'),
      });
</code>```

<p>What is the easiest way to extract longitude and latitude and use both values for displaying in a form? What is the structure of coordinateFormat? </p>

答:
Many thanks! I was thinking too complicated. Sorry.
I am using it here
map.on('click', function(evt){var lonlat=(ol.proj.transform(evt.coordinate,  'EPSG:3857', 'EPSG:4326'));
coordlon=(lonlat['0']).toFixed(6);
coordlat=(lonlat['1']).toFixed(6); document.getElementById('lat').innerHTML=coordlat; document.getElementById('lon').innerHTML=coordlon;});
Again, thanks for the hint!

Body:
The openLayers mousePosition returns the coordinates x,y of the cursor position.

var mousePosition = new ol.control.MousePosition({
        undefinedHTML: ' ',
        projection: 'EPSG:4326',
        coordinateFormat: function(coordinate) {
                        return ol.coordinate.format(coordinate, '{x}, {y}', 6);
                      },
        className: 'ol-mouse-position',
        target: document.getElementById('myposition'),
      });

What is the easiest way to extract longitude and latitude and use both values for displaying in a form? What is the structure of coordinateFormat?


问:
I want to pass data from step one to the reader of step 2
I use spring batch in order to do the workflow below:

step 1: read a large CSV and put it into Map

step 2: from the previous map I have to do a business logic.

I created a bean named CourseCsvRepository in order to save the mapped csv to this map (Singleton bean):

```<code>@Component
public class CourseCsvRepository {

    private Map<String, List<Course>> courseMappedByKey = new HashMap<>();

    public void addToMap(Course course){

        String key = "";
        key= key.concat(String.valueOf(course.getCodeStifLigne())).concat(course.getAntenne()).concat(String.valueOf(course.getIdtm())).concat(String.valueOf(course.getIdmiss())).concat(String.valueOf(course.getCourse())).concat(course.getNommiss());

        if(courseMappedByKey.containsKey(key)){
            courseMappedByKey.get(key).add(course);
        }else {
            final ArrayList<Course> list = new ArrayList<>();
            list.add(course);
            courseMappedByKey.put(key, list);
        }
    }

    public Map<String, List<Course>> getMap(){
        return this.courseMappedByKey;
    }

    public List<Course> getByKey(String key){
        return this.courseMappedByKey.get(key);
    }

}
</code>```

my second reader (Of step 2) is as bellow:

```<code>@Bean
public ItemReader<List<Course>> readFromMap(){

    ListItemReader<List<Course>> reader = new ListItemReader<List<Course>>(new ArrayList(courseCsvRepository.getMap().values()));

    return reader;
}
</code>```

but always courseCsvRepository.getMap() return null, because my bean is created before I do step 1(which used to fill our map)

```<code>@Bean
public Job writeCsvToDbJob() {
    return jobBuilderFactory.get("writeCsvToDbJob")
            .incrementer(new RunIdIncrementer())
            .start(step1())
            .next(step2())
            .build();
}
</code>```

答:
I want to share with you the answer of the previous probelem:

my beans need to be step scoped so that they will be able to receive the stepExecutionContext params, at every step. If they would not be step scoped, their beans will be created initially, and won't accept the filled map at step level.

@StepScope: How Does Spring Batch Step Scope Work

```<code>@Bean
@StepScope
public ItemReader<List<Course>> readFromMap(){

    ListItemReader<List<Course>> reader = new ListItemReader<List<Course>>(new ArrayList(courseCsvRepository.getMap().values()));

    return reader;
}
</code>```

Body:
I use spring batch in order to do the workflow below:

step 1: read a large CSV and put it into Map

step 2: from the previous map I have to do a business logic.

I created a bean named CourseCsvRepository in order to save the mapped csv to this map (Singleton bean):

@Component
public class CourseCsvRepository {

    private Map<String, List<Course>> courseMappedByKey = new HashMap<>();

    public void addToMap(Course course){

        String key = "";
        key= key.concat(String.valueOf(course.getCodeStifLigne())).concat(course.getAntenne()).concat(String.valueOf(course.getIdtm())).concat(String.valueOf(course.getIdmiss())).concat(String.valueOf(course.getCourse())).concat(course.getNommiss());

        if(courseMappedByKey.containsKey(key)){
            courseMappedByKey.get(key).add(course);
        }else {
            final ArrayList<Course> list = new ArrayList<>();
            list.add(course);
            courseMappedByKey.put(key, list);
        }
    }

    public Map<String, List<Course>> getMap(){
        return this.courseMappedByKey;
    }

    public List<Course> getByKey(String key){
        return this.courseMappedByKey.get(key);
    }

}

my second reader (Of step 2) is as bellow:

@Bean
public ItemReader<List<Course>> readFromMap(){

    ListItemReader<List<Course>> reader = new ListItemReader<List<Course>>(new ArrayList(courseCsvRepository.getMap().values()));

    return reader;
}

but always courseCsvRepository.getMap() return null, because my bean is created before I do step 1(which used to fill our map)

@Bean
public Job writeCsvToDbJob() {
    return jobBuilderFactory.get("writeCsvToDbJob")
            .incrementer(new RunIdIncrementer())
            .start(step1())
            .next(step2())
            .build();
}

Body:
I want to share with you the answer of the previous probelem:

my beans need to be step scoped so that they will be able to receive the stepExecutionContext params, at every step. If they would not be step scoped, their beans will be created initially, and won't accept the filled map at step level.

@StepScope: How Does Spring Batch Step Scope Work

@Bean
@StepScope
public ItemReader<List<Course>> readFromMap(){

    ListItemReader<List<Course>> reader = new ListItemReader<List<Course>>(new ArrayList(courseCsvRepository.getMap().values()));

    return reader;
}


问:
How do i return data where that contain empty string instead of NULL in laravel
I want to get my data from database where one of my attribute was empty string instead of null....but my code return all data where NULL and empty string combined...here is my code</p>

```<code>public function findAllPersons2(){
        return $this->where('pi_person_type','3')
                     ->where('pi_vendor_id','!=' , '')
                    ->orderBy('pi_name', 'asc')
                    ->get();
    }

</code>```

答:
Try as below.</p>

```<code>$this->where('pi_person_type','3')
                     ->where(function($q){
                         $q->whereNull('pi_vendor_id')->orwhere('pi_vendor_id','');
                     })

                    ->orderBy('pi_name', 'asc')
                    ->get();
</code>```

Body:
I want to get my data from database where one of my attribute was empty string instead of null....but my code return all data where NULL and empty string combined...here is my code

public function findAllPersons2(){
        return $this->where('pi_person_type','3')
                     ->where('pi_vendor_id','!=' , '')
                    ->orderBy('pi_name', 'asc')
                    ->get();
    }

Body:
Try as below.

$this->where('pi_person_type','3')
                     ->where(function($q){
                         $q->whereNull('pi_vendor_id')->orwhere('pi_vendor_id','');
                     })

                    ->orderBy('pi_name', 'asc')
                    ->get();


问:
Page Redirection
To help better explain my Question, here is what i have:

I am using a Precoded service, on it i have access to the Template HTML Files Only.

The URL to the Login page is : DynamicPage.aspx?Site=Mysite&WebCode=LoginRequired

The Main site URL would look like : DynamicPage.aspx?Site=Mysite&WebCode= or DynamicPage.aspx?Site=Mysite

What i need is a JavaScript I could put into the main header template file that would view "WebCode" And depending on whats entered redirect to a certain page.

I got from "Sitifensys" a code

Sitifensys

if (window.location.href!="foo.bar/login.php") window.location.href="login.php";

The problem with this code is even when i go to the main page it still redirects me to login.php which i do not want it to. I need this code to Read the "WebCode" If it is "LoginRequired" Redirect to "Login.php" else if redirect to "Test.php"

Hope this explanation is a bit better.

答:
Don't do this that way. If you do anything in JavaScript it may be easily blocked by user. Better add and if() in your PHP code and then redirect to login, if user don't have specific session key:</p>

```<code>if(!(isset($_SESSION['logged_in']) && true == $_SESSION['logged_in']))
    {
    header('Location: login.php');
    die();
    }
</code>```

Title: Page Redirection

Body:
Don't do this that way. If you do anything in JavaScript it may be easily blocked by user. Better add and if() in your PHP code and then redirect to login, if user don't have specific session key:

if(!(isset($_SESSION['logged_in']) && true == $_SESSION['logged_in']))
    {
    header('Location: login.php');
    die();
    }


问:
I am getting some error when building my angular universal app with npm run build:prerender
i am trying to build my angular universal app using npm run build:prerender but i am seeing two errors here.

errors

It complains of not seeing the rout path i set as "**" for null page

It displaying this below error too .

binding.copyFile(src, dest, flags);
                                       ^
Error: EPERM: operation not permitted, copyfile 'C:\wamp64\www\naipod4\dist\browser\assets' -> 'C:\wamp64\www\naipod4\dist\static\assets'

please what should i do, i am stuck here for almost one week now

答:
I had this same error when I upgraded node to > v8

```<code>fs.js:1919
  binding.copyFile(src, dest, flags);
</code>```

The solution was to upgrade my npm packages using npm audit fix I am not sure which of the many packages upgraded solved the problem

Body:
I had this same error when I upgraded node to > v8

fs.js:1919
  binding.copyFile(src, dest, flags);

The solution was to upgrade my npm packages using npm audit fix I am not sure which of the many packages upgraded solved the problem


问:
Dynamodb query all records as per no-sql design
I know writing queries in dynamodb but I am still new. Now for a project rather
than simply creating a table with a partition key and sort key, I have designed
a no-sql data-model data structure for my table. Accordingly, I have implemented
list/add/update/delete dynamodb queries.

My Question is how to query all records, for example query all products. For the Admin panel of my application, I need to display all the records of an entity type, for each  type of Entity.

I know querying all records has  been basically asked before at Retrieve all items from DynamoDB using query?.

However, I am posting this question of doing this without scan operation; how to do in terms of or in the light of considering a proper/complete nosql design. Specifically, I am asking because I am currently using a static value for partition key.

I have followed single table design( in any case, the recommendation is most well-designed applications use only 1 table ). As part of this, at this link https://www.trek10.com/blog/dynamodb-single-table-relational-modeling/ it is recommended to use a static value for sort key, which will become primary key of (reverse lookup) Index. Thereby allowing querying all "Products", for example.

My application, will have "Categories". It will also have "Surveys" created, with each Survey belonging to  a Category. For the admin panel, I need to display all Categories and also all Surveys.

What I have done currently:

I) Table Design:

table : tbl_surveys

Partition Key: tbl_pk_surv

Sort Key:tbl_sk_surv

One "Data" Attribute: data_attr

I created a GSI with tbl_sk_surv as Partition Key and data_attr as Sortkey.

II) For example, for Categories, Category records would look like this:

tbl_pk_surv     | tbl_sk_surv    | data_attr  | cat_name | status
Cat-1VqNAF3Vi1  | ADMIN_CATEGORY | 1565673999 | Cat1     | 1
Cat-QUTQHQwd42  | ADMIN_CATEGORY | 1565950613 | Cat2     | 1

I am querying GSI with 'ADMIN_CATEGORY' as the value for GSI Hash key(tbl_sk_surv).

Please let me know how else this could be done. In general, please provide guidance on nosql data-modelling.

I have followed following documentation for nosql design

https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-general-nosql-design.html

https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-modeling-nosql.html

https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-modeling-nosql-B.html

https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-adjacency-graphs.html#bp-adjacency-lists

https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-relational-modeling.html

https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-gsi-overloading.html

https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-partition-key-design.html

https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-sort-keys.html

https://www.trek10.com/blog/dynamodb-single-table-relational-modeling/

https://aws.amazon.com/blogs/database/using-sort-keys-to-organize-data-in-amazon-dynamodb/

Update:
On more searching, I find that the below question is similar to mine. But I am asking more specifically, because I am using GSI. Whichever way, please guide:

How to design key schema to have only one DynamoDB table per application?

答:
I guess by today, 5 month from your question you already are an dynamodb modeling expert :) I will give my point just for future visitors looking for the same question and as an exercise for my self.

1- First Step (after get all your use cases of course) is design your ERM, it will be really helpful.
2- List all your access patterns, is very important to know first what do you want to get from your data before you model your database.
3- Then you can decide your PK and SK(if necessary) for your items and your GSIs(also if needed)

You can say SK is you GSI PK and query the GSI like this:

"PK = ADMIN_CATEGORY" from GSI


问:
Refresh only a few lines on Bash Script
So this is my output...

```<code>00-
01-  Wallet : 123456789123465789
02-
03- --------------------
04- Server Stats Update:
05- --------------------
06-  Work Units : 0 (cancelled:0 | completed:0)
07-  Average Complete Time : 0
08-
09- -------------
10- Stats Update:
11- -------------
12-  Work Units : 0 (ondemand:0 | precache:0 | paid:0)
13-  Prize Pool : 0%    -    Earned : 0
14-
</code>```

I need the lines 06,07,12 and 13 to keep refreshing... the only method I found so far is by making a loop and clearing the output every two seconds...

Also I found that printf \033[A could be useful but I couldn't figure how to implement it here...

My code...

```<code>while true: do
  echo -e "\n Wallet : ${Address} \n"
  echo --------------------
  echo Server Stats Update:
  echo --------------------
  echo -e " Work Units : ${ServerOverallWU} (cancelled:${Cancelled} | completed:${Completed}) "
  echo -e " Average Complete Time : ${AvgCompTime} "
  echo
  echo -------------
  echo Stats Update:
  echo -------------
  echo -e " Work Units : ${SaveOverallWU} (ondemand:${SaveOnDemand} | precache:${SavePreCache} | paid:${SavePaidWU}) "
  echo -en " Prize Pool : ${SavePrizePool}%   -    Earned : ${SaveEarned} "
done
</code>```

Ps: Fixed... just put the clear on the right stop and now it runs smooth as butter

答:
I've got a function for that

```<code>XY () { printf "\e[$2;${1}H$3"; }
</code>```

Usage

```<code>XY 1 13 "Hello World!"
</code>```

It'll print 'Hello World!' on column 1 of line 13.
Comparing this with tput

```<code>for i in {1..100}; {
    tput cup $1 $2; printf "Hello World!"
}

real    0m0,130s
user    0m0,079s
sys     0m0,055s

for i in {1..100}; {
    XY $1 2 "Hello World!"
}

real    0m0,002s
user    0m0,002s
sys     0m0,000s
</code>```

Title: Refresh only a few lines on Bash Script

Body:
So this is my output...

00-
01-  Wallet : 123456789123465789
02-
03- --------------------
04- Server Stats Update:
05- --------------------
06-  Work Units : 0 (cancelled:0 | completed:0)
07-  Average Complete Time : 0
08-
09- -------------
10- Stats Update:
11- -------------
12-  Work Units : 0 (ondemand:0 | precache:0 | paid:0)
13-  Prize Pool : 0%    -    Earned : 0
14-

I need the lines 06,07,12 and 13 to keep refreshing... the only method I found so far is by making a loop and clearing the output every two seconds...

Also I found that printf \033[A could be useful but I couldn't figure how to implement it here...

My code...

while true: do
  echo -e "\n Wallet : ${Address} \n"
  echo --------------------
  echo Server Stats Update:
  echo --------------------
  echo -e " Work Units : ${ServerOverallWU} (cancelled:${Cancelled} | completed:${Completed}) "
  echo -e " Average Complete Time : ${AvgCompTime} "
  echo
  echo -------------
  echo Stats Update:
  echo -------------
  echo -e " Work Units : ${SaveOverallWU} (ondemand:${SaveOnDemand} | precache:${SavePreCache} | paid:${SavePaidWU}) "
  echo -en " Prize Pool : ${SavePrizePool}%   -    Earned : ${SaveEarned} "
done

Ps: Fixed... just put the clear on the right stop and now it runs smooth as butter

Body:
I've got a function for that

XY () { printf "\e[$2;${1}H$3"; }

Usage

XY 1 13 "Hello World!"

It'll print 'Hello World!' on column 1 of line 13.
Comparing this with tput

for i in {1..100}; {
    tput cup $1 $2; printf "Hello World!"
}

real    0m0,130s
user    0m0,079s
sys     0m0,055s

for i in {1..100}; {
    XY $1 2 "Hello World!"
}

real    0m0,002s
user    0m0,002s
sys     0m0,000s


问:
How to return bool value with navigator.pop?
I'm trying to return a bool value from the dialogbox but I do not understand why the value does not return as need. I have tried returning as a future value and returning the values together with context after popping the dialogbox.</p>

```<code>final bool delete = await _showDialog();
print(delete);

Future<bool> _showDialog() {
bool result;

showDialog(
  context: context,
  builder: (BuildContext context) {
    return AlertDialog(
      title: Text('Delete Appointment'),
      content: Text(
        'Are you sure? \nThis action cannot undo.',
        style: TextStyle(
          color: Colors.red,
          fontSize: 20
        ),
      ),
      actions: <Widget>[
        FlatButton(
          color: Colors.blue,
          child: Text(
            'CANCEL',
            style: TextStyle(
              color: Colors.white,
              fontSize: 20
            ),
          ),
          onPressed: () {
            setState(() => result = false);
            //print(result);
            Navigator.pop(context, result);
            return Future.value(result);
          },
        ),
        SizedBox(
          width: 50,
        ),
        FlatButton(
          color: Colors.red,
          child: Text(
            'CONFIRM',
            style: TextStyle(
              color: Colors.white,
              fontSize: 20
            ),
          ),
          onPressed: () {
            setState(() => result = true);
            //print(result);
            Navigator.pop(context, result);
            return Future.value(result);
          },
        )
      ],
    );
  }
);
}
</code>```

答:
Here's a working example based on your code:</p>

```<code>@override
Widget build(BuildContext context) {
  return Container(
    child: RaisedButton(onPressed: () async {
      bool delete = await _showDialog(context);
      print(delete);
    })
  );
}

Future<bool> _showDialog(context) {
  return showDialog(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        title: Text('Delete Appointment'),
        content: Text(
          'Are you sure? \nThis action cannot undo.',
          style: TextStyle(
            color: Colors.red,
            fontSize: 20
          ),
        ),
        actions: <Widget>[
          FlatButton(
            color: Colors.blue,
            child: Text(
              'CANCEL',
              style: TextStyle(
                color: Colors.white,
                fontSize: 20
              ),
            ),
            onPressed: () {
              Navigator.pop(context, false);
            },
          ),
          SizedBox(
            width: 50,
          ),
          FlatButton(
            color: Colors.red,
            child: Text(
              'CONFIRM',
              style: TextStyle(
                color: Colors.white,
                fontSize: 20
              ),
            ),
            onPressed: () {
              Navigator.pop(context, true);
            },
          )
        ],
      );
    }
  );
}
</code>```

Body:
I'm trying to return a bool value from the dialogbox but I do not understand why the value does not return as need. I have tried returning as a future value and returning the values together with context after popping the dialogbox.

final bool delete = await _showDialog();
print(delete);

Future<bool> _showDialog() {
bool result;

showDialog(
  context: context,
  builder: (BuildContext context) {
    return AlertDialog(
      title: Text('Delete Appointment'),
      content: Text(
        'Are you sure? \nThis action cannot undo.',
        style: TextStyle(
          color: Colors.red,
          fontSize: 20
        ),
      ),
      actions: <Widget>[
        FlatButton(
          color: Colors.blue,
          child: Text(
            'CANCEL',
            style: TextStyle(
              color: Colors.white,
              fontSize: 20
            ),
          ),
          onPressed: () {
            setState(() => result = false);
            //print(result);
            Navigator.pop(context, result);
            return Future.value(result);
          },
        ),
        SizedBox(
          width: 50,
        ),
        FlatButton(
          color: Colors.red,
          child: Text(
            'CONFIRM',
            style: TextStyle(
              color: Colors.white,
              fontSize: 20
            ),
          ),
          onPressed: () {
            setState(() => result = true);
            //print(result);
            Navigator.pop(context, result);
            return Future.value(result);
          },
        )
      ],
    );
  }
);
}

Body:
Here's a working example based on your code:

@override
Widget build(BuildContext context) {
  return Container(
    child: RaisedButton(onPressed: () async {
      bool delete = await _showDialog(context);
      print(delete);
    })
  );
}

Future<bool> _showDialog(context) {
  return showDialog(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        title: Text('Delete Appointment'),
        content: Text(
          'Are you sure? \nThis action cannot undo.',
          style: TextStyle(
            color: Colors.red,
            fontSize: 20
          ),
        ),
        actions: <Widget>[
          FlatButton(
            color: Colors.blue,
            child: Text(
              'CANCEL',
              style: TextStyle(
                color: Colors.white,
                fontSize: 20
              ),
            ),
            onPressed: () {
              Navigator.pop(context, false);
            },
          ),
          SizedBox(
            width: 50,
          ),
          FlatButton(
            color: Colors.red,
            child: Text(
              'CONFIRM',
              style: TextStyle(
                color: Colors.white,
                fontSize: 20
              ),
            ),
            onPressed: () {
              Navigator.pop(context, true);
            },
          )
        ],
      );
    }
  );
}


问:
Customizing wordpress navigation header with woocommerce my account
I am new to wordpress and I was creating a eCommerce website with woocommerce, then I have an idea to make an custom navigation header where when user is not log in it will show login/register and when login it will show to name of the customer.

答:
There are a few ways you can achieve this.

The easiest option is to use any one of the below plugins. Using these plugins, you can show/hide menu items based on their login status. These plugins also allow you to customize the menu based on User roles as well.

https://wordpress.org/plugins/nav-menu-roles/

https://wordpress.org/plugins/user-menus/

Or you can assign a custom class to the menu item and then you can hide/show them using CSS. "logged-in" class is added to the BODY tag when a user is logged in.


问:
How to create, structure, maintain and update data codebooks in R?
In the interest of replication I like to keep a codebook with meta data for each data frame. A data codebook is:

a written or computerized list that provides a clear and comprehensive description of the variables that will be included in the database.  Marczyk et al (2010)

I like to document the following attributes of a variable:

name

description (label, format, scale, etc)

source (e.g. World bank)

source media (url and date accessed, CD and ISBN, or whatever)

file name of the source data on disk (helps when merging codebooks)

notes

For example, this is what I am implementing to document the variables in data frame mydata1 with 8 variables:

```<code>code.book.mydata1 <- data.frame(variable.name=c(names(mydata1)),
     label=c("Label 1",
              "State name",
              "Personal identifier",
              "Income per capita, thousand of US$, constant year 2000 prices",
              "Unique id",
              "Calendar year",
              "blah",
              "bah"),
      source=rep("unknown",length(mydata1)),
      source_media=rep("unknown",length(mydata1)),
      filename = rep("unknown",length(mydata1)),
      notes = rep("unknown",length(mydata1))
)
</code>```

I write a different codebook for each data set I read.  When I merge data frames I will also merge the relevant aspects of their associated codebook, to document the final database.  I do this by essentially copy pasting the code above and changing the arguments.

答:
As of 2020, there are R packages directly dedicated to codebooks that may fit your needs.

The codebooks package is a comprehensive package that can generate codebooks (with common attributes plus descriptive statistics) in different formats. It has a website and a paper (Arslan, 2019, How to Automatically Document Data With the codebook Package to Facilitate Data Reuse. The paper has, in Figure 1, also a comparison of different approaches.

Here is an example.

The dataspice package (featured by rOpenSci) is particularly dedicated to generating metadata that can be found by search engines on the web. It has a website.

Here is an example.

The dataMaid package can generate a report containing metadata and descriptive statistics, and it can perform certain checks. It's on CRAN and GitHub, and it has a JSS paper (Petersen & Ekstrøm, 2019, dataMaid: Your Assistant for Documenting Supervised Data Quality Screening in R).

Here is an example.

The memisc package has a lot of functionality for working with survey data and also comes with a codebook function. It has a website.

Here is an example.

There is also a blog post by Marta Kołczyńska with a lightweight function that generates a data frame with metadata (which can be exported, e.g., to an Excel file).

Here is an example.

Body:
In the interest of replication I like to keep a codebook with meta data for each data frame. A data codebook is:

a written or computerized list that provides a clear and comprehensive description of the variables that will be included in the database.  Marczyk et al (2010)

I like to document the following attributes of a variable:

name

description (label, format, scale, etc)

source (e.g. World bank)

source media (url and date accessed, CD and ISBN, or whatever)

file name of the source data on disk (helps when merging codebooks)

notes

For example, this is what I am implementing to document the variables in data frame mydata1 with 8 variables:

code.book.mydata1 <- data.frame(variable.name=c(names(mydata1)),
     label=c("Label 1",
              "State name",
              "Personal identifier",
              "Income per capita, thousand of US$, constant year 2000 prices",
              "Unique id",
              "Calendar year",
              "blah",
              "bah"),
      source=rep("unknown",length(mydata1)),
      source_media=rep("unknown",length(mydata1)),
      filename = rep("unknown",length(mydata1)),
      notes = rep("unknown",length(mydata1))
)

I write a different codebook for each data set I read.  When I merge data frames I will also merge the relevant aspects of their associated codebook, to document the final database.  I do this by essentially copy pasting the code above and changing the arguments.


问:
get data from client with regional language in nodejs
client side data sample as below

```<code>{name:'ABC',age:24,language:'ಕನ್ನಡ'}
</code>```

i need to send language value to another service
but in node console cannot print as above
instead of ಕನ್ನಡ it prints like  {name:'ABC',age:24,language:'����ͷ�'}
my express setup like

```<code>    var express = require('express');
    var bodyParser = require('body-parser');
    var app = express();

    app.use(bodyParser.json({
            limit: '2mb'
        }));
        app.use(bodyParser.urlencoded({
            limit: '900kb',
            extended: true
        }));
    app.use((req, res, next) => {
    req.header("Content-Type",  "application/json;charset=UTF-8");
    next();
});
</code>```

this is indian kannada language.I try with locale module but no luck.
 how to set accept-language please help me to solve

答:
Use req.headers["accept-language"] to get the language the user has set in his browser.

For easier support look into a locale module.

Body:
client side data sample as below

{name:'ABC',age:24,language:'ಕನ್ನಡ'}

i need to send language value to another service
but in node console cannot print as above
instead of ಕನ್ನಡ it prints like  {name:'ABC',age:24,language:'����ͷ�'}
my express setup like

    var express = require('express');
    var bodyParser = require('body-parser');
    var app = express();

    app.use(bodyParser.json({
            limit: '2mb'
        }));
        app.use(bodyParser.urlencoded({
            limit: '900kb',
            extended: true
        }));
    app.use((req, res, next) => {
    req.header("Content-Type",  "application/json;charset=UTF-8");
    next();
});

this is indian kannada language.I try with locale module but no luck.
 how to set accept-language please help me to solve