问:
mapping array of keys to array of values for substitution
Given this data, which is two distinct objects, one having an array of keys and the other a dictionary of key value pairs:

```<code>{
  "servers": [
    {
      "location": "server4",
      "services": [
        "srv07",
        "srv06",
        "srv01",
        "srv04"
      ]
    },
    {
      "location": "server2",
      "services": [
        "srv07",
        "srv02",
        "srv05",
        "srv03"
      ]
    }
  ],
  "release": {
    "id": "release1",
    "services": [
      {
        "service": "srv01",
        "URL": "/srv01_service/v1.20.0"
      },
      {
        "service": "srv02",
        "URL": "/srv02_service/v1.14.0"
      },
      {
        "service": "srv03",
        "URL": "/srv03_service/v1.15.0"
      },
      {
        "service": "srv04",
        "URL": "/srv04_service/v1.18.0"
      },
      {
        "service": "srv05",
        "URL": "/srv05_service/v1.14.0"
      },
      {
        "service": "srv06",
        "URL": "/srv06_serv/v1.13.0"
      },
      {
        "service": "srv07",
        "URL": "/srv07_service/v1.19.0"
      }
    ]
  }
}
</code>```

I am trying to produce this, the first object with the keys replaced with the values from the dictionary.  NOTE:  I would be fine with renaming services[] to URLs[] if it makes things easier.

```<code>{
  "servers": [
    {
      "location": "server4",
      "services": [
        "/srv07_service/v1.19.0",
        "/srv06_serv/v1.13.0",
        "/srv01_service/v1.20.0",
        "/srv04_service/v1.18.0"
      ]
    },
    {
      "location": "server2",
      "services": [
        "/srv07_service/v1.19.0",
        "/srv02_service/v1.14.0",
        "/srv05_service/v1.14.0",
        "/srv03_service/v1.15.0"
      ]
    }
  ]
}
</code>```

My latest attempt is close but returns something akin to a Cartesian.

```<code>. |  .servers[].services[] = (.servers[] as $s | .release.services[] | select(.service as $v | $s.services[] | index($v)).URL) | {servers}
</code>```

答:
Create an INDEX to lookup in, then map each element you want to change according to the index.

jq '
  INDEX(.release.services[]; .service) as $index
  | {servers} | .servers[].services[] |= $index[.].URL
'
```
<pre class="lang-json prettyprint-override"><code>{
  "servers": [
    {
      "location": "server4",
      "services": [
        "/srv07_service/v1.19.0",
        "/srv06_serv/v1.13.0",
        "/srv01_service/v1.20.0",
        "/srv04_service/v1.18.0"
      ]
    },
    {
      "location": "server2",
      "services": [
        "/srv07_service/v1.19.0",
        "/srv02_service/v1.14.0",
        "/srv05_service/v1.14.0",
        "/srv03_service/v1.15.0"
      ]
    }
  ]
}
</code>```

Demo

Body:
Given this data, which is two distinct objects, one having an array of keys and the other a dictionary of key value pairs:

{
  "servers": [
    {
      "location": "server4",
      "services": [
        "srv07",
        "srv06",
        "srv01",
        "srv04"
      ]
    },
    {
      "location": "server2",
      "services": [
        "srv07",
        "srv02",
        "srv05",
        "srv03"
      ]
    }
  ],
  "release": {
    "id": "release1",
    "services": [
      {
        "service": "srv01",
        "URL": "/srv01_service/v1.20.0"
      },
      {
        "service": "srv02",
        "URL": "/srv02_service/v1.14.0"
      },
      {
        "service": "srv03",
        "URL": "/srv03_service/v1.15.0"
      },
      {
        "service": "srv04",
        "URL": "/srv04_service/v1.18.0"
      },
      {
        "service": "srv05",
        "URL": "/srv05_service/v1.14.0"
      },
      {
        "service": "srv06",
        "URL": "/srv06_serv/v1.13.0"
      },
      {
        "service": "srv07",
        "URL": "/srv07_service/v1.19.0"
      }
    ]
  }
}

I am trying to produce this, the first object with the keys replaced with the values from the dictionary.  NOTE:  I would be fine with renaming services[] to URLs[] if it makes things easier.

{
  "servers": [
    {
      "location": "server4",
      "services": [
        "/srv07_service/v1.19.0",
        "/srv06_serv/v1.13.0",
        "/srv01_service/v1.20.0",
        "/srv04_service/v1.18.0"
      ]
    },
    {
      "location": "server2",
      "services": [
        "/srv07_service/v1.19.0",
        "/srv02_service/v1.14.0",
        "/srv05_service/v1.14.0",
        "/srv03_service/v1.15.0"
      ]
    }
  ]
}

My latest attempt is close but returns something akin to a Cartesian.

. |  .servers[].services[] = (.servers[] as $s | .release.services[] | select(.service as $v | $s.services[] | index($v)).URL) | {servers}

Body:
Create an INDEX to lookup in, then map each element you want to change according to the index.

jq '
  INDEX(.release.services[]; .service) as $index
  | {servers} | .servers[].services[] |= $index[.].URL
'

{
  "servers": [
    {
      "location": "server4",
      "services": [
        "/srv07_service/v1.19.0",
        "/srv06_serv/v1.13.0",
        "/srv01_service/v1.20.0",
        "/srv04_service/v1.18.0"
      ]
    },
    {
      "location": "server2",
      "services": [
        "/srv07_service/v1.19.0",
        "/srv02_service/v1.14.0",
        "/srv05_service/v1.14.0",
        "/srv03_service/v1.15.0"
      ]
    }
  ]
}

Demo


来源: stackexchange

问:
TypeError: Inputs to a layer should be tensors. Got: <PrefetchDataset shapes:
I am trying to read data from a few files with tf data pipeline and train a multi input neural network. I train model successfully but when I want to test model then I get this error:

```<code>TypeError: Inputs to a layer should be tensors. Got: <PrefetchDataset shapes: (((None, None), (None, None)), (None,)), types: ((tf.float32, tf.float32), tf.float32)>
</code>```

Preprocessing Functions:

```<code>def split_chr_by_tab(*lines):
    sep = ","
    features = [tf.strings.to_number(tf.strings.split(line, sep=sep), out_type=tf.float32) for line in lines]
    return tf.concat(features, axis=0)

def separate_input_output(input):
    return tuple([input[:-6], input[-6:-1]]), input[-1]
</code>```

Data Pipeline:

```<code>Train_dataset = tf.data.Dataset.list_files(Train_file_list)
Train_dataset= Train_dataset.shuffle(epoch).repeat(epoch).interleave(lambda filename: tf.data.TextLineDataset(filename).skip(1), num_parallel_calls=25)
Train_dataset= Train_dataset.map(split_chr_by_tab,num_parallel_calls=tf.data.experimental.AUTOTUNE).map(separate_input_output,num_parallel_calls=tf.data.experimental.AUTOTUNE)
Train_dataset= Train_dataset.batch(batch_size).prefetch(buffer_size=tf.data.experimental.AUTOTUNE)

Test_dataset = tf.data.Dataset.list_files(Test_file_list)
Test_dataset= Test_dataset.interleave(lambda filename: tf.data.TextLineDataset(filename).skip(1), num_parallel_calls=25)
Test_dataset= Test_dataset.map(split_chr_by_tab,num_parallel_calls=tf.data.experimental.AUTOTUNE).map(separate_input_output,num_parallel_calls=tf.data.experimental.AUTOTUNE)
Test_dataset= Test_dataset.batch(batch_size).prefetch(buffer_size=tf.data.experimental.AUTOTUNE)
</code>```

Model Training and Evaluation (I get error when predicting on test data):

```<code>inp1 = Input(shape=(1000, ),name="inp1")
inp2 = Input(shape=(4, ),name="inp2")
merge1=concatenate([inp1, inp2])
first_dense = Dense(32,kernel_initializer=initializer, )(merge1)
output=dense(1,)(first_dense)
model = Model(inputs=[inp1, inp2], outputs=output)
model.fit(Train_dataset,callbacks=callbacks_list,verbose=1,epochs=epoch,steps_per_epoch=10)
prediction = model(Test_dataset)
</code>```

Could you please tell me why I get error during prediction? For some reasons, I need to use model(Test_dataset) instead of model.predict(Test_dataset).  Also, how can I store prediction values and true labels?

答:
You can also use:

```<code>Test_dataset.map(model)
</code>```

assuming Test_dataset is already batched

ContentLicense: CC BY-SA 4.0

Body:
I am trying to read data from a few files with tf data pipeline and train a multi input neural network. I train model successfully but when I want to test model then I get this error:

TypeError: Inputs to a layer should be tensors. Got: <PrefetchDataset shapes: (((None, None), (None, None)), (None,)), types: ((tf.float32, tf.float32), tf.float32)>

Preprocessing Functions:

def split_chr_by_tab(*lines):
    sep = ","
    features = [tf.strings.to_number(tf.strings.split(line, sep=sep), out_type=tf.float32) for line in lines]
    return tf.concat(features, axis=0)

def separate_input_output(input):
    return tuple([input[:-6], input[-6:-1]]), input[-1]

Data Pipeline:

Train_dataset = tf.data.Dataset.list_files(Train_file_list)
Train_dataset= Train_dataset.shuffle(epoch).repeat(epoch).interleave(lambda filename: tf.data.TextLineDataset(filename).skip(1), num_parallel_calls=25)
Train_dataset= Train_dataset.map(split_chr_by_tab,num_parallel_calls=tf.data.experimental.AUTOTUNE).map(separate_input_output,num_parallel_calls=tf.data.experimental.AUTOTUNE)
Train_dataset= Train_dataset.batch(batch_size).prefetch(buffer_size=tf.data.experimental.AUTOTUNE)

Test_dataset = tf.data.Dataset.list_files(Test_file_list)
Test_dataset= Test_dataset.interleave(lambda filename: tf.data.TextLineDataset(filename).skip(1), num_parallel_calls=25)
Test_dataset= Test_dataset.map(split_chr_by_tab,num_parallel_calls=tf.data.experimental.AUTOTUNE).map(separate_input_output,num_parallel_calls=tf.data.experimental.AUTOTUNE)
Test_dataset= Test_dataset.batch(batch_size).prefetch(buffer_size=tf.data.experimental.AUTOTUNE)

Model Training and Evaluation (I get error when predicting on test data):

inp1 = Input(shape=(1000, ),name="inp1")
inp2 = Input(shape=(4, ),name="inp2")
merge1=concatenate([inp1, inp2])
first_dense = Dense(32,kernel_initializer=initializer, )(merge1)
output=dense(1,)(first_dense)
model = Model(inputs=[inp1, inp2], outputs=output)
model.fit(Train_dataset,callbacks=callbacks_list,verbose=1,epochs=epoch,steps_per_epoch=10)
prediction = model(Test_dataset)

Could you please tell me why I get error during prediction? For some reasons, I need to use model(Test_dataset) instead of model.predict(Test_dataset).  Also, how can I store prediction values and true labels?

Body:
You can also use:

Test_dataset.map(model)

assuming Test_dataset is already batched


问:
C++ How do I create objects from different classes in another class?
I have a program with two classes, one for points and one for a rectangle. I need to make two objects of point class within my rectangle class and make them private. I can't figure out how to use the rectangle constructor to make the points with the points constructor, every time I do so I get the error "no default constructor exists for class "Point2d"". Even when I make a default constructor I still get this. I'm at a loss here.</p>
```<code>#include <iostream>
#include <cmath>
using namespace std;

class point2D {
private:
    int x = 0;
    int y = 0;

public:
    int getX() {
        return x;
    }
    int getY() {
        return y;
    }
    point2D(int ax, int ay) {
        x = ax;
        y = ay;
    }
};

class rectangleType {
private:
    point2D p0;
    point2D p1;

public:
    int getX0() {
        return p0.getX();
    }
    int getY0() {
        return p0.getY();
    }
    int getX1() {
        return p1.getX();
    }
    int getY1() {
        return p1.getY();
    }
    int getWidth() {
        return abs(getX1() - getX0());
    }
    int getLength() {
        return abs(getY1() - getY0());
    }
    int getPerimeter() {
        return 2 * (getWidth() + getLength());
    }
    int getArea() {
        return (getWidth() * getLength());
    }
    rectangleType(int ax0, int ay0, int ax1, int ay1) {
        point2D p0(ax0, ay0);
        point2D p1(ax1, ay1);
    }
};
</code>```

答:
your constructor should look like this:

```<code>rectangleType(int ax0, int ay0, int ax1, int ay1)
    : p0 {ax0, ay0},
      p1 {ax1, ay1}
{}
</code>```

this is a member initialization list, you initialize values p0 and p1 by passing the arguments to their respective construcotrs

Body:
I have a program with two classes, one for points and one for a rectangle. I need to make two objects of point class within my rectangle class and make them private. I can't figure out how to use the rectangle constructor to make the points with the points constructor, every time I do so I get the error "no default constructor exists for class "Point2d"". Even when I make a default constructor I still get this. I'm at a loss here.

#include <iostream>
#include <cmath>
using namespace std;

class point2D {
private:
    int x = 0;
    int y = 0;

public:
    int getX() {
        return x;
    }
    int getY() {
        return y;
    }
    point2D(int ax, int ay) {
        x = ax;
        y = ay;
    }
};

class rectangleType {
private:
    point2D p0;
    point2D p1;

public:
    int getX0() {
        return p0.getX();
    }
    int getY0() {
        return p0.getY();
    }
    int getX1() {
        return p1.getX();
    }
    int getY1() {
        return p1.getY();
    }
    int getWidth() {
        return abs(getX1() - getX0());
    }
    int getLength() {
        return abs(getY1() - getY0());
    }
    int getPerimeter() {
        return 2 * (getWidth() + getLength());
    }
    int getArea() {
        return (getWidth() * getLength());
    }
    rectangleType(int ax0, int ay0, int ax1, int ay1) {
        point2D p0(ax0, ay0);
        point2D p1(ax1, ay1);
    }
};

Body:
your constructor should look like this:

rectangleType(int ax0, int ay0, int ax1, int ay1)
    : p0 {ax0, ay0},
      p1 {ax1, ay1}
{}

this is a member initialization list, you initialize values p0 and p1 by passing the arguments to their respective construcotrs


问:
C++/Visual Studio 2005 - Template Class skipped during compilation of debug configuration
I have a template class, which had always been able to be compiled in Debug, with no problems. All of a sudden though, it refuses to detect changes to the class and skips it, unless I Rebuild. There's no problem with other non-template classes, and this problem doesn't occur when compiling in Release, so I'm just using that for now.

The weird thing is, I've created a new project, and the same problem occurs.

Any ideas?

Thanks lots. :)

答: I've tried disabling minimal rebuild, and it seems to have fixed the problem. Thanks! </p>

ContentLicense: CC BY-SA 3.0


问:
How to convert an integer into an array of digits
I want to convert an integer, say 12345, to an array like [1,2,3,4,5].

I have tried the below code, but is there a better way to do this?

```<code>var n = 12345;
var arr = n.toString().split('');
for (i = 0; i < arr.length; i++) arr[i] = +arr[i] | 0;
</code>```

答:
Without to string solution.

This method is faster than method with toString transform. Approximately 3-4 times. You can see benchmarks here or on screen below.

const numberToArray = (number) => {
    var arr = [];
    while(number>0) { arr.push(number%10); number = number/10|0; }
    return arr.reverse();
}
```

Body:
I want to convert an integer, say 12345, to an array like [1,2,3,4,5].

I have tried the below code, but is there a better way to do this?

var n = 12345;
var arr = n.toString().split('');
for (i = 0; i < arr.length; i++) arr[i] = +arr[i] | 0;


问:
Multiple joins trough array field
noSQL beginner here.

For a current use case we are syncing an external relational DB (dataverse) with a changing schema to an mongoDB instance. Because we have no control over the schema and each entity on his one can change we aren't able to normalize the data leading me to the need for nested lookups from an array.

i have created an sample playground to illustrate an rough example of the data structure: https://mongoplayground.net/p/ObWOC5choPq

I need to return the data in roughly the following format:

```<code>{
    orderID,
    products: [
        {
          productID,
          pictureURL,
        },
        {
          productID,
          pictureURL,
        }
       ]
}
</code>```

I'm able to perform both lookups seperatly but aren't able to return the picture data as part of an product object in the products array. Could anyone point me in the right direction?

Kind regards,

Nomis

答:
Maybe something like this:

```<code> db.orders.aggregate([
 {
 "$lookup": {
   "from": "products",
   "localField": "products.productID",
   "foreignField": "_id",
   "as": "products"
  }
  },
  {
   $unwind: {
    path: "$products",
    preserveNullAndEmptyArrays: true
  }
  },
  {
   "$lookup": {
    "from": "pictures",
    "localField": "products.pictureID",
    "foreignField": "_id",
    "as": "products.pictures"
   }
   },
   {
    $unwind: {
      path:"$products.pictures",
      preserveNullAndEmptyArrays: true
    }
   },
   {
   $project: {
    _id: 1,
     products: {
     productID: "$products._id",
     pictureURL: "$products.pictures.bloburl"
    }
   }
  },
  {
   $group: {
   _id: "$_id",
    products: {
    $push: "$products"
   }
  }
  },
  {
   $project: {
   orderID: "$_id",
   products: 1,
   _id: 0
   }
   }
  ])
</code>```

$lookup orders with products

unwind to convert products to object

$lookup orders with pictures to nested in products

$unwind pictures to object

$project the fields as expected in the final result

$group by order_id.

$project one more time to rename order _id to orders

playground

Title: Multiple joins trough array field

Body:
noSQL beginner here.

For a current use case we are syncing an external relational DB (dataverse) with a changing schema to an mongoDB instance. Because we have no control over the schema and each entity on his one can change we aren't able to normalize the data leading me to the need for nested lookups from an array.

i have created an sample playground to illustrate an rough example of the data structure: https://mongoplayground.net/p/ObWOC5choPq

I need to return the data in roughly the following format:

{
    orderID,
    products: [
        {
          productID,
          pictureURL,
        },
        {
          productID,
          pictureURL,
        }
       ]
}

I'm able to perform both lookups seperatly but aren't able to return the picture data as part of an product object in the products array. Could anyone point me in the right direction?

Kind regards,

Nomis

Body:
Maybe something like this:

 db.orders.aggregate([
 {
 "$lookup": {
   "from": "products",
   "localField": "products.productID",
   "foreignField": "_id",
   "as": "products"
  }
  },
  {
   $unwind: {
    path: "$products",
    preserveNullAndEmptyArrays: true
  }
  },
  {
   "$lookup": {
    "from": "pictures",
    "localField": "products.pictureID",
    "foreignField": "_id",
    "as": "products.pictures"
   }
   },
   {
    $unwind: {
      path:"$products.pictures",
      preserveNullAndEmptyArrays: true
    }
   },
   {
   $project: {
    _id: 1,
     products: {
     productID: "$products._id",
     pictureURL: "$products.pictures.bloburl"
    }
   }
  },
  {
   $group: {
   _id: "$_id",
    products: {
    $push: "$products"
   }
  }
  },
  {
   $project: {
   orderID: "$_id",
   products: 1,
   _id: 0
   }
   }
  ])

$lookup orders with products

unwind to convert products to object

$lookup orders with pictures to nested in products

$unwind pictures to object

$project the fields as expected in the final result

$group by order_id.

$project one more time to rename order _id to orders

playground


问:
I can't get an image to appear when hovering on another image, Cargo
I'm having issues trying to make an image {image 16} appear when hovering on another image with a link {image 15}. I'm building my website on Cargo, as I don't know much about coding. This site-builder is limiting my options to only place my images in grids, and as these grids already have a div class each, i can't get Cargo to accept the div classes im making for each image- probably because i'm doing it wrong. To top it all off, Cargo doesn't allow me to see all of the HTML, just specific parts. Any help would be super welcomed, thank you in advance!

HTML:

```<code><div class="image-gallery" gid="21">

<div class="hover-image">{image 16}</div>

</div> <br>

<br><br>
<br>
<div grid-row="" grid-pad="0" grid-gutter="0" grid-responsive="">
    <div grid-col="x12" grid-pad="0"></div>
</div><br>
<div grid-row="" grid-pad="0" grid-gutter="0" grid-responsive="">
    <div grid-col="x12" grid-pad="0"><div style="text-align: left"><div class="image-gallery" gid="22">

<div class="hover-title">
<a rel="history" href="enlightened-type" class="image-link">{image 15}</a>
</div>

{image 5}
{image 13}
{image 14}
{image 12}
{image 11}
</div><br></div>
</div>
</div>
<br><div class="image-gallery" gid="23">
{image 17}
</div>2
</code>```

CSS:

```<code>.hover-title {
    display: inline;
    pointer-events: auto;
    cursor: pointer;
}

.hover-image {
    visibility: hidden;
}

body:not(.mobile) .hover-title:hover + .hover-image {
    visibility: visible;
    pointer-events: none;
}

.hover-image {
    display: flex;
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: -1;
    pointer-events: none;
    flex-direction: column;
    align-items: center;
    justify-content: center;

/* Change width and height to scale images */
    width: 90vw;
    height: 90vh;
}

.hover-image img {
    max-width: 100% !important;
    max-height: 100% !important;
    width: auto !important;
    height: auto !important;
    margin-bottom: 0;
}
</code>```

答:
You're going to need some javascript.

Add an id to image16

```<code><div class="hover-image" id="myhoverimage">{image 16}</div>
</code>```

Add some event listeners to  image15

```<code> <a rel="history" href="enlightened-type" onmouseover="showImg()" onmouseout="hideImg()" class="image-link">{image 15}</a>
</code>```

The Javascript. (Put at the bottom of your html)

```<code>  <script>

    var hoverImg = document.getElementById("myhoverimage");

    function showImg(x) {
      hoverImg.style.visibility = "visible";
    }

    function hideImg(x) {
      hoverImg.style.visibility = "hidden";
    }

  </script>
</code>```

Body:
I'm having issues trying to make an image {image 16} appear when hovering on another image with a link {image 15}. I'm building my website on Cargo, as I don't know much about coding. This site-builder is limiting my options to only place my images in grids, and as these grids already have a div class each, i can't get Cargo to accept the div classes im making for each image- probably because i'm doing it wrong. To top it all off, Cargo doesn't allow me to see all of the HTML, just specific parts. Any help would be super welcomed, thank you in advance!

HTML:

{image 16}

{image 15}

{image 5}
{image 13}
{image 14}
{image 12}
{image 11}

{image 17}

2

CSS:

.hover-title {
    display: inline;
    pointer-events: auto;
    cursor: pointer;
}

.hover-image {
    visibility: hidden;
}

body:not(.mobile) .hover-title:hover + .hover-image {
    visibility: visible;
    pointer-events: none;
}

.hover-image {
    display: flex;
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: -1;
    pointer-events: none;
    flex-direction: column;
    align-items: center;
    justify-content: center;

/* Change width and height to scale images */
    width: 90vw;
    height: 90vh;
}

.hover-image img {
    max-width: 100% !important;
    max-height: 100% !important;
    width: auto !important;
    height: auto !important;
    margin-bottom: 0;
}

Body:
You're going to need some javascript.

Add an id to image16

<div class="hover-image" id="myhoverimage">{image 16}</div>

Add some event listeners to  image15

 <a rel="history" href="enlightened-type" onmouseover="showImg()" onmouseout="hideImg()" class="image-link">{image 15}</a>

The Javascript. (Put at the bottom of your html)

  <script>

    var hoverImg = document.getElementById("myhoverimage");

    function showImg(x) {
      hoverImg.style.visibility = "visible";
    }

    function hideImg(x) {
      hoverImg.style.visibility = "hidden";
    }

  </script>


问:
How to check HTTP status of a file online without fully downloading the file?
I have a database of thousands of files online, and I want to check what their status is (e.g. if the file exists, if it sends us to a 404, etc.) and update this in my database.

I've used urllib.request to download files to a python script. However, obviously downloading terabytes of files is going to take a long time. Parallelizing the process would help, but ultimately I just don't want to download all the data, just check the status. Is there an ideal way to check (using urllib or another package) the HTTP response code of a certain URL?

Additionally, if I can get the file size from the server (which would be in the HTTP response), then I can also update this in my database.

答: If your web server is standards-based, you can use a HEAD request instead of a GET.  It returns the same status without actually fetching the page.</p>


问:
How to change the color of single characters in a cell in excel with python win32com?
I have a question regarding the win32com bindings for excel. I set up early bindings and followed some examples from the "Python Programming on Win32" book from O'Reilly.

The following code works fine:

```<code>book2.xlApp.Worksheets('Sheet1').Cells(1,1).Font.ColorIndex = 1
book2.xlApp.Worksheets('Sheet1').Cells(1,1).Font.ColorIndex = 2
</code>```

It changes the font color of the whole cell according to the number.
However this does not work:

```<code>book2.xlApp.Worksheets('Sheet1').Cells(1,1).Characters(start,length).Font.ColorIndex = 1
</code>```

I get the following callback:

```<code>Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
AttributeError: Characters instance has no __call__ method
</code>```

However in Excels VBA the code works. Can anybody point me to the solution?
I really need to change parts of a string in an excel cell.

Thank you very much.

答:
use GetCharacters:</p>

```<code>Cells(1,1).GetCharacters(start,length).Font.ColorIndex = 1
</code>```

Body:
I have a question regarding the win32com bindings for excel. I set up early bindings and followed some examples from the "Python Programming on Win32" book from O'Reilly.

The following code works fine:

book2.xlApp.Worksheets('Sheet1').Cells(1,1).Font.ColorIndex = 1
book2.xlApp.Worksheets('Sheet1').Cells(1,1).Font.ColorIndex = 2

It changes the font color of the whole cell according to the number.
However this does not work:

book2.xlApp.Worksheets('Sheet1').Cells(1,1).Characters(start,length).Font.ColorIndex = 1

I get the following callback:

Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
AttributeError: Characters instance has no __call__ method

However in Excels VBA the code works. Can anybody point me to the solution?
I really need to change parts of a string in an excel cell.

Thank you very much.

Body:
use GetCharacters:

Cells(1,1).GetCharacters(start,length).Font.ColorIndex = 1


问:
Unmutable field on python's dataclass
I have this dataclass:

```<code>@dataclass
class Couso:
    nome: str
    date: str = field(default=datetime.now(), init = False)
    id_: str = field(default=key())
</code>```

Being key() a simple function that returns a str on len 32.

And when i create multiple classes of it (without specifing the id_ obviously) they all share the same id_

But why does it work this way? I cant understand.

Also, would this happen again with the attribute date?

答:
key is called before field is called to create the field, so that every instance will have the same default id_ attribute. It's the same as if you had written

```<code>x = key()

@dataclass
class Couso:
    ...
    id_ : str = field(default=x)
</code>```

If you want to call key each time you create a new instance, use default_factory instead.

```<code>id_: str = field(default_factory=key)  # key is not called; it's passed as an object.
</code>```

The same goes for datetime.now:

```<code>date: str = field(default_factory=datetime.now, init = False)
</code>```

Title: Unmutable field on python's dataclass

Body:
I have this dataclass:

@dataclass
class Couso:
    nome: str
    date: str = field(default=datetime.now(), init = False)
    id_: str = field(default=key())

Being key() a simple function that returns a str on len 32.

And when i create multiple classes of it (without specifing the id_ obviously) they all share the same id_

But why does it work this way? I cant understand.

Also, would this happen again with the attribute date?

Body:
key is called before field is called to create the field, so that every instance will have the same default id_ attribute. It's the same as if you had written

x = key()

@dataclass
class Couso:
    ...
    id_ : str = field(default=x)

If you want to call key each time you create a new instance, use default_factory instead.

id_: str = field(default_factory=key)  # key is not called; it's passed as an object.

The same goes for datetime.now:

date: str = field(default_factory=datetime.now, init = False)


问:
I can't get my export to work for my Sequelize model
I'm creating an e-commerce site for a school project and I'm trying to connect my GoogleStrategy to my sqlite database so I can store the users in a table. But for some reason I get an error when calling the variable in my passport-setup file.

The error occurs when i try to call my exported User variable from user-model.js -> passport-setup.js

user-model.js:

```<code>const { Sequelize, DataTypes } = require('sequelize');
const sequelize = new Sequelize('./database.sqlite');

const User = sequelize.define('User', {
    googleId: {
        type:DataTypes.STRING,
        allowNull: false
    },
    displayName: {
        type: DataTypes.STRING,
        allowNull: false
    },
    email: {
        type: DataTypes.STRING,
        allowNull: false
    },
    photo: {
        type: DataTypes.STRING,
        allowNull: false
    },
});

console.log(User === sequelize.models.User); //true

module.exports = User;
</code>```

passport-setup.js:

```<code>const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20');
const keys = require ('./keys');
const User = require('./user-model');

passport.use(
    new GoogleStrategy ({
        //options for the strategy
        callbackURL:'/redirect/',
        clientID: keys.google.clientID,
        clientSecret: keys.google.clientSecret,
    }, (accessToken, refreshToken, profile, done) => {

        console.log('passport callback function fired');
        console.log(profile)
    })
)
</code>```

sequelize connection in index.js:

```<code>//initialize sequelize
const { Sequelize } = require('sequelize');
const sequelize = new Sequelize({
    dialect: 'sqlite',
    storage: './database.sqlite'
  });

//check sequelize connection
  try {
    sequelize.authenticate();
    console.log('Connection has been established successfully.');
  } catch (error) {
    console.error('Unable to connect to the database:', error);
  }

</code>```

Error:

```<code>[nodemon] starting `node index.js`
C:\Users\karwa\Studier\År 3\GIK2PG (Projektbaserad systemutveckling)\Sneakers-Project\node_modules\sequelize\dist\lib\sequelize.js:56
      options.dialect = urlParts.protocol.replace(/:$/, "");
                                          ^

TypeError: Cannot read property 'replace' of null
    at new Sequelize (C:\Users\karwa\Studier\År 3\GIK2PG (Projektbaserad systemutveckling)\Sneakers-Project\node_modules\sequelize\dist\lib\sequelize.js:56:43)
    at Object.<anonymous> (C:\Users\karwa\Studier\År 3\GIK2PG (Projektbaserad systemutveckling)\Sneakers-Project\passport-setup.js:24:19)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:12)
    at Module.require (internal/modules/cjs/loader.js:974:19)
    at require (internal/modules/cjs/helpers.js:93:18)
    at Object.<anonymous> (C:\Users\karwa\Studier\År 3\GIK2PG (Projektbaserad systemutveckling)\Sneakers-Project\index.js:10:23)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
[nodemon] app crashed - waiting for file changes before starting...
</code>```

I'm following this tutorial but i'm trying to implement sqlite3 and sequelize instead of mongodb and mongoose.

答:
You need to export sequelize instance in index.js and use it in user-model.js instead of creating one more Sequelize instance there:

const sequelize = require('./index');

const User = sequelize.define('User', {
...
```

Body:
I'm creating an e-commerce site for a school project and I'm trying to connect my GoogleStrategy to my sqlite database so I can store the users in a table. But for some reason I get an error when calling the variable in my passport-setup file.

The error occurs when i try to call my exported User variable from user-model.js -> passport-setup.js

user-model.js:

const { Sequelize, DataTypes } = require('sequelize');
const sequelize = new Sequelize('./database.sqlite');

const User = sequelize.define('User', {
    googleId: {
        type:DataTypes.STRING,
        allowNull: false
    },
    displayName: {
        type: DataTypes.STRING,
        allowNull: false
    },
    email: {
        type: DataTypes.STRING,
        allowNull: false
    },
    photo: {
        type: DataTypes.STRING,
        allowNull: false
    },
});

console.log(User === sequelize.models.User); //true

module.exports = User;

passport-setup.js:

const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20');
const keys = require ('./keys');
const User = require('./user-model');

passport.use(
    new GoogleStrategy ({
        //options for the strategy
        callbackURL:'/redirect/',
        clientID: keys.google.clientID,
        clientSecret: keys.google.clientSecret,
    }, (accessToken, refreshToken, profile, done) => {

        console.log('passport callback function fired');
        console.log(profile)
    })
)

sequelize connection in index.js:

//initialize sequelize
const { Sequelize } = require('sequelize');
const sequelize = new Sequelize({
    dialect: 'sqlite',
    storage: './database.sqlite'
  });

//check sequelize connection
  try {
    sequelize.authenticate();
    console.log('Connection has been established successfully.');
  } catch (error) {
    console.error('Unable to connect to the database:', error);
  }

Error:

[nodemon] starting `node index.js`
C:\Users\karwa\Studier\År 3\GIK2PG (Projektbaserad systemutveckling)\Sneakers-Project\node_modules\sequelize\dist\lib\sequelize.js:56
      options.dialect = urlParts.protocol.replace(/:$/, "");
                                          ^

TypeError: Cannot read property 'replace' of null
    at new Sequelize (C:\Users\karwa\Studier\År 3\GIK2PG (Projektbaserad systemutveckling)\Sneakers-Project\node_modules\sequelize\dist\lib\sequelize.js:56:43)
    at Object.<anonymous> (C:\Users\karwa\Studier\År 3\GIK2PG (Projektbaserad systemutveckling)\Sneakers-Project\passport-setup.js:24:19)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:12)
    at Module.require (internal/modules/cjs/loader.js:974:19)
    at require (internal/modules/cjs/helpers.js:93:18)
    at Object.<anonymous> (C:\Users\karwa\Studier\År 3\GIK2PG (Projektbaserad systemutveckling)\Sneakers-Project\index.js:10:23)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
[nodemon] app crashed - waiting for file changes before starting...

I'm following this tutorial but i'm trying to implement sqlite3 and sequelize instead of mongodb and mongoose.


问:
Highcharts area-spline fill gradient possibly undefined error
So I'm working with highcharts on angular 12 and trying to fill the area spline color with a gradient and I'm getting this error any idea how to solve this or what I could possibly be doing wrong ?

Any help would be appreciated ,Thanks in advance

答:
What you see here is the beauty of TypeScript as it warns you during compile time that one part of your chain could return undefined and therefore lead to an error that aborts your script.

Use a guard clause to show the compiler you checked for undefined values.

```<code>if (!Highcharts?.getOptions()?.colors) {
  return;
}

// ... here comes your code
// the compiler will no longer show errors
</code>```

Or make sure to have a proper default value, like this:

```<code>let color = '#615E9B';
if (Highcharts?.getOptions()?.colors) {
  color = Highcharts.getOptions().colors[0];
}

// Your code, but use color variable instead of Highcharts.getOptions().colors[0]
</code>```

That is also possible inline, but hard to read and to maintain. I would suggest you to stick to few more lines of code that are easy to understand.

Body:
What you see here is the beauty of TypeScript as it warns you during compile time that one part of your chain could return undefined and therefore lead to an error that aborts your script.

Use a guard clause to show the compiler you checked for undefined values.

if (!Highcharts?.getOptions()?.colors) {
  return;
}

// ... here comes your code
// the compiler will no longer show errors

Or make sure to have a proper default value, like this:

let color = '#615E9B';
if (Highcharts?.getOptions()?.colors) {
  color = Highcharts.getOptions().colors[0];
}

// Your code, but use color variable instead of Highcharts.getOptions().colors[0]

That is also possible inline, but hard to read and to maintain. I would suggest you to stick to few more lines of code that are easy to understand.


问:
Using Regex how to extract a string until a character only if present, else till end
I am trying to extract string using Regex in python, that starts with word 'swap' till first '/' if present, or till end

For example:

str1: 'abcd/swap 12345 ijkl/mnop/tyuio'

str2: 'abcd/swap ijkl 1234'

str3: 'swap ijklm nop'

Required Output:

from str1: 'swap 12345 ijkl'

from str2: 'swap ijkl 1234'

from str3: 'swap ijklm nop'

I am new to regex and tried many combinations but cant get all 3 situations.

答:
An efficient ways to do this is

r"swap.*?(?:/|$)"

https://regex101.com/r/ght9hu/1

or  r"swap.*?(?=/|$)" with no match of the ender.

https://regex101.com/r/VSX1hp/1


问:
Adding a dimension to a numpy arrray
I'm working on the MNIST dataset and have my train_x.shape = (60000, 28, 28, ),

but my model requires a shape (60000, 28, 28, 1).

So my questions are:

Why does it have a 'null' dimension instead of just (60000, 28, 28)?

How can I convert the same? Is there some way I can loop through the first dimension in the array? (Or a better solution?)
Thanks in advance!

答:
Answer to question 1: it has a null dimension because it is in some sense a row vector rather than a column vector. I say "in some sense" because row and column only make sense for 1 dimensional arrays, so let me illustrate with 1 dimensional arrays.

```<code>x = np.array([1,1,1])
print(x)       # array([1, 1, 1])
print(x.shape) # (3,) <-- note the the null dimension.

x.reshape((3,1)) # This answers your second question, btw.
print(x)         # array([[1],
                 #        [1],
                 #        [1]]) <-- a column vector.
</code>```

To reiterate: the reshape command is what you use to do the conversion you require.

Title: Adding a dimension to a numpy arrray

Body:
Answer to question 1: it has a null dimension because it is in some sense a row vector rather than a column vector. I say "in some sense" because row and column only make sense for 1 dimensional arrays, so let me illustrate with 1 dimensional arrays.

x = np.array([1,1,1])
print(x)       # array([1, 1, 1])
print(x.shape) # (3,) <-- note the the null dimension.

x.reshape((3,1)) # This answers your second question, btw.
print(x)         # array([[1],
                 #        [1],
                 #        [1]]) <-- a column vector.

To reiterate: the reshape command is what you use to do the conversion you require.


问:
How to install redis extension for php 7
Referred this link https://anton.logvinenko.name/en/blog/how-to-install-redis-and-redis-php-client.html

And done following steps

PhpRedis for PHP 7 (Skip it if you have different PHP version)

Install required package

```<code>apt-get install php7.0-dev
</code>```

Download PhpRedis

```<code>cd /tmp
wget https://github.com/phpredis/phpredis/archive/php7.zip -O phpredis.zip
</code>```

But, https://github.com/phpredis/phpredis/archive/php7.zip file not found for installation.

答:
Install redis with a command:</p>
```<code>sudo apt-get install php7.0-redis
</code>```

Body:
Referred this link https://anton.logvinenko.name/en/blog/how-to-install-redis-and-redis-php-client.html

And done following steps

PhpRedis for PHP 7 (Skip it if you have different PHP version)

Install required package

apt-get install php7.0-dev

Download PhpRedis

cd /tmp
wget https://github.com/phpredis/phpredis/archive/php7.zip -O phpredis.zip

But, https://github.com/phpredis/phpredis/archive/php7.zip file not found for installation.

Body:
Install redis with a command:

sudo apt-get install php7.0-redis


问:
Your build failed to run: Couldn't read commit xxxxxxxx
I'm trying to build and deploy an image on GCP with cloud build.
I have a rails api repo on bitbucket running on docker, the repo is synced with google cloud repository

I configured a trigger on cloud build when a commit is made on my master branch.

Trigger Configuration:

Service account permissions:

But when the master branch gets a commit, the triggers returns the following error:
our build failed to run:
Couldn't read commit xxxxxxxx

Build Error:

I tried checked the GCP doc and I can't find anything. I think the issue might be on the IAM level, maybe the service account needs more credentials.

答: For me the Cloud Build API needed to be enabled.  Once I did this my build ran, I didn't need to do anything special for permissions.</p>


问:
Get different data via Retrofit for the Fragment in FragmentPagerAdapter for the several tablayout tabs
Conditions:
I have an Activity and I'm creating PagerAdapter extends FragmentPagerAdapter with one Fragment class. TabLayout includes 10 tabs. I have TabLayout.addOnTabSelectedListener and there in onTabSelected() I am updating some custom variable in app's SharedPreferences which depends on current tab name and tab index. Tab's names are not static - there are loading from server too.

My task:
With this value I should make a retrofit2 Call to my server and load values in adapter with recyclerview for my Fragment.

My problem:
I am loading the same data for the different tabs, which should contatin different data! I am understand that this happens because in all cases I have the same SharedPreferences variable's value so I am making retrofit Call with same conditions.

setOffscreenPageLimit() can't be setted to 0  - default is 1 according documentation:
https://developer.android.com/reference/kotlin/androidx/viewpager/widget/ViewPager#setoffscreenpagelimit;

setUserVisibleHint() on SO I've found this like some variant for solving my problem, but it can't be overrided because is deprecated now.

Solution:
I think I should save previous and next tab name in some way and then I can make different parallel retrofit Calls with different conditions. When tab selected I can get current, previous and next tab name. But how, where and when I should make two more retrofit calls?

UPD 08.02.2022: Still thinking about this problem.

Code:

SomeActivity.java

```<code>public class SomeActivity extends BaseActivity  {

    private String TAG="SomeActivity";
    private Context context;

    private TabLayout tabs;
    private ViewPager viewpager;
    private ProgressBar PBLoading;
    private PagerAdapter_SomePAdapter adapter;

    List<String> names = new ArrayList<>();
    private String[] tabTitles;

    public String previousTabName;
    public String nextTabName;
    public int counterForPreviousTabName;
    public int counterForNextTabName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_layout);
        context = getApplicationContext();

        String categories = AppPreferences.getCategories(context);
        tabTitles = categories.split(";");

        tabs = findViewById(R.id.tabs);
        viewpager = findViewById(R.id.viewpager);
        PBLoading = findViewById(R.id.PBLoading);
        tabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                Log.d(TAG, "onTabSelected");
                AppPreferences.setCurrentValueForRetrofit(getApplicationContext(), tab.getPosition());

                counterForPreviousTabName = tmpTab.getPosition() - 1;
                counterForNextTabName = tmpTab.getPosition() + 1;

                //here I can get tab names.
            }
        });

        adapter = new PagerAdapter_SomePAdapter(getSupportFragmentManager(), SomeActivity.this);
        viewpager.setAdapter(adapter);
        adapter.updateTitleData(tabTitles);
        tabs.setupWithViewPager(viewpager);
        adapter.notifyDataSetChanged();

    }
}
</code>```

PagerAdapter_SomePAdapter.java:

```<code>public class PagerAdapter_SomePAdapter  extends FragmentPagerAdapter {

    int PAGE_COUNT = 2;
    private String[] tabTitles = new String[] { "", ""};
    private Context mContext;
    Fragment_fragment fragment_fragment;

    String TAG = "PagerAdapter_SomePAdapter";

    public PagerAdapter_SomePAdapter(FragmentManager fm, Context context) {
        super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
        mContext = context;
        fragment_fragment = new Fragment_fragment();
    }

    @Override public int getCount() {
        return PAGE_COUNT;
    }

    @Override public Fragment getItem(int position) {
        return fragment_fragment.newInstance(position + 1, tabTitles[position]);
    }

    @Override public CharSequence getPageTitle(int position) {
        return tabTitles[position];
    }

    public void updateTitleData(String[] tabTitlesNew) {
        tabTitles = tabTitlesNew;
        PAGE_COUNT = tabTitlesNew.length;
        notifyDataSetChanged();
    }

}
</code>```

Fragment_fragment.java:

```<code>public class Fragment_fragment extends Fragment {
    private String TAG = "Fragment_fragment";
    private static final String ARG_PAGE = "ARG_PAGE";
    private int mPage;
    private View rootView;
    private RecyclerView RV;
    private Adapter_Items adapter;

    public static Fragment_fragment newInstance(int page, String tabName) {
        Bundle args = new Bundle();
        args.putInt(ARG_PAGE, page);
        Fragment_fragment fragment = new Fragment_fragment();
        fragment.setArguments(args);

        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mPage = getArguments().getInt(ARG_PAGE);
        }
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        mContext=context;
    }

    @SuppressLint("ClickableViewAccessibility")
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.content_list, container, false);
        RV = rootView.findViewById(R.id.recycler_view);
        new loadDataAS().execute();
        return rootView;
    }

    private void loadData(){
        //retrofit call code;
    }

    class loadDataAS extends AsyncTask<Void, Void, Void> {
        final ProgressDialog progress = new ProgressDialog(mContext);
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }
        @Override
        protected Void doInBackground(Void... arg0) {
            loadData();
            return null;
        }
        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            adapter = new Adapter_Items(arguments, arguments2, arguments3);
            RV.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        }
    }
}
</code>```

Adapter_Items:

```<code>public class Adapter_Items extends RecyclerView.Adapter<Adapter_Items.ViewHolder>{

    private LayoutInflater mInflater;
    private Context mContext;
    private static String TAG = "Adapter_Items";

    public Adapter_Items(List<Integer>arguments, List<String>arguments2, List<String>arguments3){
        //initializing arguments
    }

    // inflates the row layout from xml when needed
    @NotNull
    @Override
    public ViewHolder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.recycle_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

        //setting view's information

    }

    @Override
    public int getItemCount() {
        return arguments.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        ViewHolder(View itemView) {
            super(itemView);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {

        }
    }

}
</code>```

答:
First thing,

fragment should contain different data

Saving tab name after tab selected will not work. You should remove this

```<code>AppPreferences.setCurrentValueForRetrofit(getApplicationContext(),
tab.getPosition());
</code>```

You should call retrofit code inside the fragment with the tabName (Not from sharedPref) to get data for that tab.

For this, make the following changes,

You are already passing the tabName to fragment instance

```<code>newInstance(int page, String tabName)
</code>```

use that tabName and pass to your AsyncTask -> loadData() as

```<code>loadData(tabName);
</code>```

Then you can use that in your retrofit call and get the data.

Note:

```<code>setOffscreenPageLimit()
</code>```

This method will load fragments just before they are completely visible. It would be useful and a great user experience to display data directly rather than fetching only when user selects the tab.

Body:
Conditions:
I have an Activity and I'm creating PagerAdapter extends FragmentPagerAdapter with one Fragment class. TabLayout includes 10 tabs. I have TabLayout.addOnTabSelectedListener and there in onTabSelected() I am updating some custom variable in app's SharedPreferences which depends on current tab name and tab index. Tab's names are not static - there are loading from server too.

My task:
With this value I should make a retrofit2 Call to my server and load values in adapter with recyclerview for my Fragment.

My problem:
I am loading the same data for the different tabs, which should contatin different data! I am understand that this happens because in all cases I have the same SharedPreferences variable's value so I am making retrofit Call with same conditions.

setOffscreenPageLimit() can't be setted to 0  - default is 1 according documentation:
https://developer.android.com/reference/kotlin/androidx/viewpager/widget/ViewPager#setoffscreenpagelimit;

setUserVisibleHint() on SO I've found this like some variant for solving my problem, but it can't be overrided because is deprecated now.

Solution:
I think I should save previous and next tab name in some way and then I can make different parallel retrofit Calls with different conditions. When tab selected I can get current, previous and next tab name. But how, where and when I should make two more retrofit calls?

UPD 08.02.2022: Still thinking about this problem.

Code:

SomeActivity.java

public class SomeActivity extends BaseActivity  {

    private String TAG="SomeActivity";
    private Context context;

    private TabLayout tabs;
    private ViewPager viewpager;
    private ProgressBar PBLoading;
    private PagerAdapter_SomePAdapter adapter;

    List<String> names = new ArrayList<>();
    private String[] tabTitles;

    public String previousTabName;
    public String nextTabName;
    public int counterForPreviousTabName;
    public int counterForNextTabName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_layout);
        context = getApplicationContext();

        String categories = AppPreferences.getCategories(context);
        tabTitles = categories.split(";");

        tabs = findViewById(R.id.tabs);
        viewpager = findViewById(R.id.viewpager);
        PBLoading = findViewById(R.id.PBLoading);
        tabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                Log.d(TAG, "onTabSelected");
                AppPreferences.setCurrentValueForRetrofit(getApplicationContext(), tab.getPosition());

                counterForPreviousTabName = tmpTab.getPosition() - 1;
                counterForNextTabName = tmpTab.getPosition() + 1;

                //here I can get tab names.
            }
        });

        adapter = new PagerAdapter_SomePAdapter(getSupportFragmentManager(), SomeActivity.this);
        viewpager.setAdapter(adapter);
        adapter.updateTitleData(tabTitles);
        tabs.setupWithViewPager(viewpager);
        adapter.notifyDataSetChanged();

    }
}

PagerAdapter_SomePAdapter.java:

public class PagerAdapter_SomePAdapter  extends FragmentPagerAdapter {

    int PAGE_COUNT = 2;
    private String[] tabTitles = new String[] { "", ""};
    private Context mContext;
    Fragment_fragment fragment_fragment;

    String TAG = "PagerAdapter_SomePAdapter";

    public PagerAdapter_SomePAdapter(FragmentManager fm, Context context) {
        super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
        mContext = context;
        fragment_fragment = new Fragment_fragment();
    }

    @Override public int getCount() {
        return PAGE_COUNT;
    }

    @Override public Fragment getItem(int position) {
        return fragment_fragment.newInstance(position + 1, tabTitles[position]);
    }

    @Override public CharSequence getPageTitle(int position) {
        return tabTitles[position];
    }

    public void updateTitleData(String[] tabTitlesNew) {
        tabTitles = tabTitlesNew;
        PAGE_COUNT = tabTitlesNew.length;
        notifyDataSetChanged();
    }

}

Fragment_fragment.java:

public class Fragment_fragment extends Fragment {
    private String TAG = "Fragment_fragment";
    private static final String ARG_PAGE = "ARG_PAGE";
    private int mPage;
    private View rootView;
    private RecyclerView RV;
    private Adapter_Items adapter;

    public static Fragment_fragment newInstance(int page, String tabName) {
        Bundle args = new Bundle();
        args.putInt(ARG_PAGE, page);
        Fragment_fragment fragment = new Fragment_fragment();
        fragment.setArguments(args);

        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mPage = getArguments().getInt(ARG_PAGE);
        }
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        mContext=context;
    }

    @SuppressLint("ClickableViewAccessibility")
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.content_list, container, false);
        RV = rootView.findViewById(R.id.recycler_view);
        new loadDataAS().execute();
        return rootView;
    }

    private void loadData(){
        //retrofit call code;
    }

    class loadDataAS extends AsyncTask<Void, Void, Void> {
        final ProgressDialog progress = new ProgressDialog(mContext);
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }
        @Override
        protected Void doInBackground(Void... arg0) {
            loadData();
            return null;
        }
        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            adapter = new Adapter_Items(arguments, arguments2, arguments3);
            RV.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        }
    }
}

Adapter_Items:

public class Adapter_Items extends RecyclerView.Adapter<Adapter_Items.ViewHolder>{

    private LayoutInflater mInflater;
    private Context mContext;
    private static String TAG = "Adapter_Items";

    public Adapter_Items(List<Integer>arguments, List<String>arguments2, List<String>arguments3){
        //initializing arguments
    }

    // inflates the row layout from xml when needed
    @NotNull
    @Override
    public ViewHolder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.recycle_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

        //setting view's information

    }

    @Override
    public int getItemCount() {
        return arguments.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        ViewHolder(View itemView) {
            super(itemView);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {

        }
    }

}

Body:
First thing,

fragment should contain different data

Saving tab name after tab selected will not work. You should remove this

AppPreferences.setCurrentValueForRetrofit(getApplicationContext(),
tab.getPosition());

You should call retrofit code inside the fragment with the tabName (Not from sharedPref) to get data for that tab.

For this, make the following changes,

You are already passing the tabName to fragment instance

newInstance(int page, String tabName)

use that tabName and pass to your AsyncTask -> loadData() as

loadData(tabName);

Then you can use that in your retrofit call and get the data.

Note:

setOffscreenPageLimit()

This method will load fragments just before they are completely visible. It would be useful and a great user experience to display data directly rather than fetching only when user selects the tab.


问:
Why snsClient.unsubscribe(request) did give me a error on snsClient.unsubscribe(request)?
I'm trying to use:

```<code>  UnsubscribeRequest request = UnsubscribeRequest.builder()
                .subscriptionArn("arn:aws:sns:us-east-1:9999999999:myTopic")
                .build();

  UnsubscribeResponse result = snsClient.unsubscribe(request);
</code>```

But I received an error:

software.amazon.awssdk.services.sns.model.InvalidParameterException: Invalid parameter: SubscriptionId (Service: Sns, Status Code: 400, Request ID: 08d4fa07-be89-5b3d-bd81-a07bcf09de7a, Extended Request ID: null)
at software.amazon.awssdk.core.internal.http.CombinedResponseHandler.handleErrorResponse(CombinedResponseHandler.java:123) ~[sdk-core-2.17.46.jar:na]

Can you help me to solve this problem?

答:
You're using the ARN of the topic, not the ARN of the subscription.  Each subscription has an ARN too.  For example, if I create a topic named generic-topic the ARN for it looks like:

```<code>arn:aws:sns:us-west-2:1234567890:generic-topic
</code>```

Then, when I create a subscription (in this case an SQS queue) the subscription ARN looks like:

```<code>arn:aws:sns:us-west-2:1234567890:generic-topic:dc1580a7-1234-4b3d-12340-abcd12345678
</code>```

If you're using the CLI you can see the subscriptions for a topic with something like:

```<code>aws sns list-subscriptions-by-topic --topic-arn arn:aws:sns:us-west-2:1234567890:generic-topic
</code>```

to get an output like:

```<code>{
    "Subscriptions": [
        {
            "SubscriptionArn": "arn:aws:sns:us-west-2:1234567890:generic-topic:dc1580a7-1234-4b3d-12340-abcd12345678",
            "Owner": "1234567890",
            "Protocol": "sqs",
            "Endpoint": "arn:aws:sqs:us-west-2:1234567890:generic-queue",
            "TopicArn": "arn:aws:sns:us-west-2:1234567890:generic-topic"
        }
    ]
}
</code>```

Body:
I'm trying to use:

  UnsubscribeRequest request = UnsubscribeRequest.builder()
                .subscriptionArn("arn:aws:sns:us-east-1:9999999999:myTopic")
                .build();

  UnsubscribeResponse result = snsClient.unsubscribe(request);

But I received an error:

software.amazon.awssdk.services.sns.model.InvalidParameterException: Invalid parameter: SubscriptionId (Service: Sns, Status Code: 400, Request ID: 08d4fa07-be89-5b3d-bd81-a07bcf09de7a, Extended Request ID: null)
at software.amazon.awssdk.core.internal.http.CombinedResponseHandler.handleErrorResponse(CombinedResponseHandler.java:123) ~[sdk-core-2.17.46.jar:na]

Can you help me to solve this problem?

Body:
You're using the ARN of the topic, not the ARN of the subscription.  Each subscription has an ARN too.  For example, if I create a topic named generic-topic the ARN for it looks like:

arn:aws:sns:us-west-2:1234567890:generic-topic

Then, when I create a subscription (in this case an SQS queue) the subscription ARN looks like:

arn:aws:sns:us-west-2:1234567890:generic-topic:dc1580a7-1234-4b3d-12340-abcd12345678

If you're using the CLI you can see the subscriptions for a topic with something like:

aws sns list-subscriptions-by-topic --topic-arn arn:aws:sns:us-west-2:1234567890:generic-topic

to get an output like:

{
    "Subscriptions": [
        {
            "SubscriptionArn": "arn:aws:sns:us-west-2:1234567890:generic-topic:dc1580a7-1234-4b3d-12340-abcd12345678",
            "Owner": "1234567890",
            "Protocol": "sqs",
            "Endpoint": "arn:aws:sqs:us-west-2:1234567890:generic-queue",
            "TopicArn": "arn:aws:sns:us-west-2:1234567890:generic-topic"
        }
    ]
}


问:
Is if(A | B) always faster than if(A || B)?
I am reading this book by Fedor Pikus and he has some very very interesting examples which for me were a surprise.

Particularly this benchmark caught me, where the only difference is that in one of them we use || in if and in another we use |.

```<code>void BM_misspredict(benchmark::State& state)
{

    std::srand(1);
    const unsigned int N = 10000;;
    std::vector<unsigned long> v1(N), v2(N);
    std::vector<int> c1(N), c2(N);

    for (int i = 0; i < N; ++i)
    {
        v1[i] = rand();
        v2[i] = rand();
        c1[i] = rand() & 0x1;
        c2[i] = !c1[i];
    }

    unsigned long* p1 = v1.data();
    unsigned long* p2 = v2.data();
    int* b1 = c1.data();
    int* b2 = c2.data();

    for (auto _ : state)
    {
        unsigned long a1 = 0, a2 = 0;
        for (size_t i = 0; i < N; ++i)
        {
            if (b1[i] || b2[i])  // Only difference
            {
                a1 += p1[i];
            }
            else
            {
                a2 *= p2[i];
            }
        }
        benchmark::DoNotOptimize(a1);
        benchmark::DoNotOptimize(a2);
        benchmark::ClobberMemory();

    }
    state.SetItemsProcessed(state.iterations());
}

void BM_predict(benchmark::State& state)
{

    std::srand(1);
    const unsigned int N = 10000;;
    std::vector<unsigned long> v1(N), v2(N);
    std::vector<int> c1(N), c2(N);

    for (int i = 0; i < N; ++i)
    {
        v1[i] = rand();
        v2[i] = rand();
        c1[i] = rand() & 0x1;
        c2[i] = !c1[i];
    }

    unsigned long* p1 = v1.data();
    unsigned long* p2 = v2.data();
    int* b1 = c1.data();
    int* b2 = c2.data();

    for (auto _ : state)
    {
        unsigned long a1 = 0, a2 = 0;
        for (size_t i = 0; i < N; ++i)
        {
            if (b1[i] | b2[i]) // Only difference
            {
                a1 += p1[i];
            }
            else
            {
                a2 *= p2[i];
            }
        }
        benchmark::DoNotOptimize(a1);
        benchmark::DoNotOptimize(a2);
        benchmark::ClobberMemory();

    }
    state.SetItemsProcessed(state.iterations());
}
</code>```

I will not go in all the details explained in the book why the latter is faster, but the idea is that hardware branch predictor is given 2 chances to misspredict in slower version and in the | (bitwise or) version. See the benchmark results below.

So the question is why don't we always use | instead of || in branches?

答:
Bitwise-or is a branchless arithmetic operator corresponding to a single ALU instruction. Logical-or is defined as implying shortcut evaluation, which involves a (costly) conditional branch. The effect of the two can differ when the evaluations of the operands have side effects.

In the case of two boolean variables, a smart compiler might evaluate logical-or as a bitwise-or, or using a conditional move, but who knows...

Body:
I am reading this book by Fedor Pikus and he has some very very interesting examples which for me were a surprise.

Particularly this benchmark caught me, where the only difference is that in one of them we use || in if and in another we use |.

void BM_misspredict(benchmark::State& state)
{

    std::srand(1);
    const unsigned int N = 10000;;
    std::vector<unsigned long> v1(N), v2(N);
    std::vector<int> c1(N), c2(N);

    for (int i = 0; i < N; ++i)
    {
        v1[i] = rand();
        v2[i] = rand();
        c1[i] = rand() & 0x1;
        c2[i] = !c1[i];
    }

    unsigned long* p1 = v1.data();
    unsigned long* p2 = v2.data();
    int* b1 = c1.data();
    int* b2 = c2.data();

    for (auto _ : state)
    {
        unsigned long a1 = 0, a2 = 0;
        for (size_t i = 0; i < N; ++i)
        {
            if (b1[i] || b2[i])  // Only difference
            {
                a1 += p1[i];
            }
            else
            {
                a2 *= p2[i];
            }
        }
        benchmark::DoNotOptimize(a1);
        benchmark::DoNotOptimize(a2);
        benchmark::ClobberMemory();

    }
    state.SetItemsProcessed(state.iterations());
}

void BM_predict(benchmark::State& state)
{

    std::srand(1);
    const unsigned int N = 10000;;
    std::vector<unsigned long> v1(N), v2(N);
    std::vector<int> c1(N), c2(N);

    for (int i = 0; i < N; ++i)
    {
        v1[i] = rand();
        v2[i] = rand();
        c1[i] = rand() & 0x1;
        c2[i] = !c1[i];
    }

    unsigned long* p1 = v1.data();
    unsigned long* p2 = v2.data();
    int* b1 = c1.data();
    int* b2 = c2.data();

    for (auto _ : state)
    {
        unsigned long a1 = 0, a2 = 0;
        for (size_t i = 0; i < N; ++i)
        {
            if (b1[i] | b2[i]) // Only difference
            {
                a1 += p1[i];
            }
            else
            {
                a2 *= p2[i];
            }
        }
        benchmark::DoNotOptimize(a1);
        benchmark::DoNotOptimize(a2);
        benchmark::ClobberMemory();

    }
    state.SetItemsProcessed(state.iterations());
}

I will not go in all the details explained in the book why the latter is faster, but the idea is that hardware branch predictor is given 2 chances to misspredict in slower version and in the | (bitwise or) version. See the benchmark results below.

So the question is why don't we always use | instead of || in branches?


问:
MySQL select all rows from last N groups
I have a dataset like this, where there can be multiple transactions per trade

```<code>| tx_id | trade_id |
--------------------
| 100   | 11       |
| 99    | 11       |
| 98    | 11       |
| 97    | 10       |
| 96    | 10       |
| 95    | 9        |
| 94    | 9        |
| 93    | 8        |
...
</code>```

I want to select all of the transactions from the last N trades. For instance if I wanted to select all rows from the last 2 trades, I would get:

```<code>| tx_id | trade_id |
--------------------
| 100   | 11       |
| 99    | 11       |
| 98    | 11       |
| 97    | 10       |
| 96    | 10       |
</code>```

I cannot guarantee that the trade_id will always have an interval of 1.

How can I accomplish this in mysql?

答:
You use DENSE_RANK on trade_id descending, then filter on your required X for "last X":

```<code>CREATE TABLE t (tx_id int, trade_id int);

INSERT INTO t (tx_id, trade_id) VALUES
(100,11),
(99,11),
(98,11),
(97,10),
(96,10),
(95,9),
(94,9),
(93,8);

SET @ngroups=2;

WITH dat
AS
(
SELECT tx_id, trade_id, DENSE_RANK() OVER (ORDER BY trade_id DESC) AS trade_id_rank
FROM t
)
SELECT tx_id, trade_id
FROM dat
WHERE trade_id_rank <= @ngroups;
</code>```

dbfiddle.uk

Body:
I have a dataset like this, where there can be multiple transactions per trade

| tx_id | trade_id |
--------------------
| 100   | 11       |
| 99    | 11       |
| 98    | 11       |
| 97    | 10       |
| 96    | 10       |
| 95    | 9        |
| 94    | 9        |
| 93    | 8        |
...

I want to select all of the transactions from the last N trades. For instance if I wanted to select all rows from the last 2 trades, I would get:

| tx_id | trade_id |
--------------------
| 100   | 11       |
| 99    | 11       |
| 98    | 11       |
| 97    | 10       |
| 96    | 10       |

I cannot guarantee that the trade_id will always have an interval of 1.

How can I accomplish this in mysql?

Body:
You use DENSE_RANK on trade_id descending, then filter on your required X for "last X":

CREATE TABLE t (tx_id int, trade_id int);

INSERT INTO t (tx_id, trade_id) VALUES
(100,11),
(99,11),
(98,11),
(97,10),
(96,10),
(95,9),
(94,9),
(93,8);

SET @ngroups=2;

WITH dat
AS
(
SELECT tx_id, trade_id, DENSE_RANK() OVER (ORDER BY trade_id DESC) AS trade_id_rank
FROM t
)
SELECT tx_id, trade_id
FROM dat
WHERE trade_id_rank <= @ngroups;

dbfiddle.uk


问:
r one sided geom_quasirandom
I am interested in plotting the distribution of some continuous variables by groups using the geom_quasirandom() function.

I would like to know how do plot only one side, for example only points on the right side rather than on both sides.

```<code>ggplot(iris,aes(Species, Sepal.Length)) + geom_quasirandom()
</code>```

I am interested in a plot like this. I am not interested in solutions based on geom_beeswarm because I have a lot of datapoints and geom_beeswarm just creates a crowded mess for my dataset. So any solution specific to geom_quasirandom() will be helpful. Thanks.

答:
Here's one approach, pulling the guts out of a beeswarm and using dplyr to adjust these manually, and adding the Species labels back manually.

```<code>ggplot_build(ggplot(iris,aes(Species, Sepal.Length)) +
  geom_quasirandom()) -> a

a$data[[1]] %>%
  group_by(group) %>%
  mutate(x_adj = group + abs(x - median(x))) %>%
  ungroup() %>%

  ggplot(aes(x_adj, y)) +
  geom_point() +
  scale_x_continuous(breaks = 1:3, labels = unique(iris$Species))
</code>```

...or a hack to keep the automatic labeling by using an invisible layer:

```<code>...
ggplot(aes(x, y)) +
  geom_point(alpha = 0) +
  geom_point(aes(x = x_adj))
</code>```

Title: r one sided geom_quasirandom

Body:
I am interested in plotting the distribution of some continuous variables by groups using the geom_quasirandom() function.

I would like to know how do plot only one side, for example only points on the right side rather than on both sides.

ggplot(iris,aes(Species, Sepal.Length)) + geom_quasirandom()

I am interested in a plot like this. I am not interested in solutions based on geom_beeswarm because I have a lot of datapoints and geom_beeswarm just creates a crowded mess for my dataset. So any solution specific to geom_quasirandom() will be helpful. Thanks.

Body:
Here's one approach, pulling the guts out of a beeswarm and using dplyr to adjust these manually, and adding the Species labels back manually.

ggplot_build(ggplot(iris,aes(Species, Sepal.Length)) +
  geom_quasirandom()) -> a

a$data[[1]] %>%
  group_by(group) %>%
  mutate(x_adj = group + abs(x - median(x))) %>%
  ungroup() %>%

  ggplot(aes(x_adj, y)) +
  geom_point() +
  scale_x_continuous(breaks = 1:3, labels = unique(iris$Species))

...or a hack to keep the automatic labeling by using an invisible layer:

...
ggplot(aes(x, y)) +
  geom_point(alpha = 0) +
  geom_point(aes(x = x_adj))


答:
If we assume the "last trades" are the ones with the highest trade_id numbers, then you can use DENSE_RANK().

For example:

```<code>select *
from (
  select *,
    dense_rank() over(order by trade_id desc) as dr
  from t
) x
where dr <= 2
</code>```

Title: MySQL select all rows from last N groups

Body:
If we assume the "last trades" are the ones with the highest trade_id numbers, then you can use DENSE_RANK().

For example:

select *
from (
  select *,
    dense_rank() over(order by trade_id desc) as dr
  from t
) x
where dr <= 2


问:
j2html nesting for tables
I am trying to use j2html to render a really simple table, but I have gotten completely stuck on the nesting and can not find any docs for this.

Trying to keep this short and to the point, this is the exact html that I want to achieve:

```<code><table border=0>
<tr>
<td style="vertical-align: top">
<b>Some Info:</b>
</td>
<td style="vertical-align: top">
<p>"some fetched info"</p>
</td>
</tr>
</table>
</code>```

Now, what I wrote is this (note that this is one of many attempts):

```<code>  table(),

 tr(
    b("Some Info: "),
    td().withStyle("vertical-align: top").withText("some fetched info")),
    br()
</code>```

The result I get is:

```<code><body>
<table>
</table>
<tr>
<b>Some Info: </b>
<td style="vertical-align: top">Some fetched info
</td>
</tr>
</code>```

I can not seem to get a grasp of the proper nesting for this problem (or how to add the table border attribute for that matter).

I wrote a very short example here hoping that someone could help, thinking that if I just get this one right the whole thing will probably click in my brain.

(Realizing just now I can't close the table bracket that way...)

答:
You would need to nest the tr within the table. Also, you can't have b("Some Info: ") directly within tr, it needs to be nested inside a td. Here is how the code should look:

```<code> table(
     tr(
         td().withStyle("vertical-align: top").withText(b("Some Info: ")),
         td().withStyle("vertical-align: top").withText(p("some fetched info"))))
</code>```

Title: j2html nesting for tables

Body:
I am trying to use j2html to render a really simple table, but I have gotten completely stuck on the nesting and can not find any docs for this.

Trying to keep this short and to the point, this is the exact html that I want to achieve:

Some Info:

"some fetched info"

Now, what I wrote is this (note that this is one of many attempts):

  table(),

 tr(
    b("Some Info: "),
    td().withStyle("vertical-align: top").withText("some fetched info")),
    br()

The result I get is:

Some Info:
Some fetched info

I can not seem to get a grasp of the proper nesting for this problem (or how to add the table border attribute for that matter).

I wrote a very short example here hoping that someone could help, thinking that if I just get this one right the whole thing will probably click in my brain.

(Realizing just now I can't close the table bracket that way...)

Body:
You would need to nest the tr within the table. Also, you can't have b("Some Info: ") directly within tr, it needs to be nested inside a td. Here is how the code should look:

 table(
     tr(
         td().withStyle("vertical-align: top").withText(b("Some Info: ")),
         td().withStyle("vertical-align: top").withText(p("some fetched info"))))


问:
CNN data doesn't fit in memory (kernel dies)
I am working on this dataset (the image part), normalized to 1103 images of size 1396 x 1676.
I am trying to feed it to a CNN (taken from here) of this shape:

```<code>n, w, h = X_train.shape # which is (n, 1396, 1676)
cnn = Sequential()
cnn.add(Conv2D(32, (3, 3), activation="relu", input_shape=(w, h, 1)))
cnn.add(MaxPooling2D(pool_size = (2, 2)))
cnn.add(Conv2D(32, (3, 3), activation="relu", input_shape=(w, h, 1)))
cnn.add(MaxPooling2D(pool_size = (2, 2)))
cnn.add(Conv2D(32, (3, 3), activation="relu", input_shape=(w, h, 1)))
cnn.add(MaxPooling2D(pool_size = (2, 2)))
cnn.add(Conv2D(64, (3, 3), activation="relu", input_shape=(w, h, 1)))
cnn.add(MaxPooling2D(pool_size = (2, 2)))
cnn.add(Conv2D(64, (3, 3), activation="relu", input_shape=(w, h, 1)))
cnn.add(MaxPooling2D(pool_size = (2, 2)))
cnn.add(Flatten())
cnn.add(Dense(activation = 'relu', units = 128))
cnn.add(Dense(activation = 'relu', units = 64))
cnn.add(Dense(activation = 'sigmoid', units = 1))
cnn.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

early = EarlyStopping(monitor="val_loss", mode="min", patience=3)
learning_rate_reduction = ReduceLROnPlateau(monitor='val_loss', patience=2, verbose=1,factor=0.3, min_lr=0.000001)
callbacks_list = [early, learning_rate_reduction]

cnn.fit(X_train, Y_train, epochs=25, validation_split=0.7, callbacks=callbacks_list)
</code>```

Both in Google Colab and on a Jupyter in my 16Gb machine, it produces a kernel death. I tried to use a generator to feed just 10 images at a time, but it doesn't produce any good result (0.5 accuracy).

Could you suggest a way to solve this? Maybe tweaking some parameters too

答: try to reduce the batch size for example use 16 also try to reduce the scale of image</p>

Body:
I am working on this dataset (the image part), normalized to 1103 images of size 1396 x 1676.
I am trying to feed it to a CNN (taken from here) of this shape:

n, w, h = X_train.shape # which is (n, 1396, 1676)
cnn = Sequential()
cnn.add(Conv2D(32, (3, 3), activation="relu", input_shape=(w, h, 1)))
cnn.add(MaxPooling2D(pool_size = (2, 2)))
cnn.add(Conv2D(32, (3, 3), activation="relu", input_shape=(w, h, 1)))
cnn.add(MaxPooling2D(pool_size = (2, 2)))
cnn.add(Conv2D(32, (3, 3), activation="relu", input_shape=(w, h, 1)))
cnn.add(MaxPooling2D(pool_size = (2, 2)))
cnn.add(Conv2D(64, (3, 3), activation="relu", input_shape=(w, h, 1)))
cnn.add(MaxPooling2D(pool_size = (2, 2)))
cnn.add(Conv2D(64, (3, 3), activation="relu", input_shape=(w, h, 1)))
cnn.add(MaxPooling2D(pool_size = (2, 2)))
cnn.add(Flatten())
cnn.add(Dense(activation = 'relu', units = 128))
cnn.add(Dense(activation = 'relu', units = 64))
cnn.add(Dense(activation = 'sigmoid', units = 1))
cnn.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

early = EarlyStopping(monitor="val_loss", mode="min", patience=3)
learning_rate_reduction = ReduceLROnPlateau(monitor='val_loss', patience=2, verbose=1,factor=0.3, min_lr=0.000001)
callbacks_list = [early, learning_rate_reduction]

cnn.fit(X_train, Y_train, epochs=25, validation_split=0.7, callbacks=callbacks_list)

Both in Google Colab and on a Jupyter in my 16Gb machine, it produces a kernel death. I tried to use a generator to feed just 10 images at a time, but it doesn't produce any good result (0.5 accuracy).

Could you suggest a way to solve this? Maybe tweaking some parameters too


问:
Is it possible to use a Stream to collect an Object into a hashmap, rather than casting?
I have a map myMap of type <String, Object> which looks like:

```<code>(
"header", "a string value"
"mapObject", {object which is always of type map<String, String>}
)
</code>```

I basically want to pull out the value of "mapObject" into a Map<String, String>

Initially I just cast it to an ImmutableMap like so:

```<code>(ImmutableMap<String, String>) myMap.get("mapObject");
</code>```

But am wondering if there is a way to do this by making use of Stream.

I've currently got:

```<code>myMap.entrySet()
   .stream()
   .collect(Collectors.toMap(Map.Entry::getKey, entry -> (String) entry.getValue()));
</code>```

But I'm getting the following exception:

class com.google.common.collect.RegularImmutableMap cannot be cast to class java.lang.String

Is there a way to do this or am I better just sticking with the cast?

答:
A possible solution could look like this:

```<code>Optional<Map<String, String>> result = myMap.entrySet()
    .stream()
    .filter(entry -> "mapObject".equals(entry.getKey()))
    .map(entry -> (Map<String, String>) entry.getValue())
    .findFirst();
</code>```

Your error message came from the cast of the second entry set (of type Map) to string here: entry -> (String) entry.getValue()

Update:

Like Holger stated the best solution nevertheless is myMap.get("mapObject"). The above solution is only to show how the problem could be solved using the Streams API.

Body:
I have a map myMap of type <String, Object> which looks like:

(
"header", "a string value"
"mapObject", {object which is always of type map<String, String>}
)

I basically want to pull out the value of "mapObject" into a Map<String, String>

Initially I just cast it to an ImmutableMap like so:

(ImmutableMap<String, String>) myMap.get("mapObject");

But am wondering if there is a way to do this by making use of Stream.

I've currently got:

myMap.entrySet()
   .stream()
   .collect(Collectors.toMap(Map.Entry::getKey, entry -> (String) entry.getValue()));

But I'm getting the following exception:

class com.google.common.collect.RegularImmutableMap cannot be cast to class java.lang.String

Is there a way to do this or am I better just sticking with the cast?

Body:
A possible solution could look like this:

Optional<Map<String, String>> result = myMap.entrySet()
    .stream()
    .filter(entry -> "mapObject".equals(entry.getKey()))
    .map(entry -> (Map<String, String>) entry.getValue())
    .findFirst();

Your error message came from the cast of the second entry set (of type Map) to string here: entry -> (String) entry.getValue()

Update:

Like Holger stated the best solution nevertheless is myMap.get("mapObject"). The above solution is only to show how the problem could be solved using the Streams API.


答:
This can be done with a CTE</p>
```<code>WITH trades AS
SELECT trade_id tid
FROM myTable
GROUP BY trade_id
ORDER BY trade_id
LIMIT 2
SELECT * FROM
trades
JOIN myTable ON trade_id = tid
ORDER BY tx_id;
</code>```

Body:
This can be done with a CTE

WITH trades AS
SELECT trade_id tid
FROM myTable
GROUP BY trade_id
ORDER BY trade_id
LIMIT 2
SELECT * FROM
trades
JOIN myTable ON trade_id = tid
ORDER BY tx_id;


问:
Change labels from data received from database in Altair bar graph
I am trying to edit the labels from the data a have received from a database. As of now I have tried using .transform_fold() but when I run my code the correct titles are appearing but with no data shown on the Graph.

With out the .transform_fold() the graph looks like the following:

And like the following with .transform_fold():

I would like to have the titles changed like so:

title from data
New title

audiobook_processed
Audiobooks processed

n_known_errors
Known Errors

n_unknown_errors
Unknown Errors

The data I receive is like the following:

date
value
name

2022-01-19
98
audiobook_processed

2022-01-19
69
n_known_errors

2022-01-19
2
n_unknown_errors

My code:

```<code>import altair as alt
import streamlit as st
import pandas as pd
import datetime

from xxx.input import get_xxx_metrics

def graph_visual_data():
    data = get_xxx_metrics('audiobook')
    data = data[data.name.isin(['audiobook_processed', 'n_unknown_errors', 'n_known_errors'])][['date','value','name']]

    data.date = data.date.dt.date
    data.value = data.value.astype(int)

    data = data.groupby(['date','name'], as_index=False).sum()

    fig = (alt.Chart(data).transform_fold(
    fold=['Audiobooks processed', 'Known Errors','Unknown Errors'],
    as_=['name', 'value']).mark_bar(size=15).encode(
        x=alt.X('date:T', axis=alt.Axis(format='%b %-d'), scale=alt.Scale(padding=15), title='Dates processed on'),
        y=alt.Y('value', title='Total amount'),
        color=alt.Color('name', title='Audiobooks processed and errors', sort=['audiobook_processed']),
        tooltip=['name', 'value', 'date']).properties(width=500))
    st.altair_chart(fig)
</code>```

答:
You could do this by replacing the values within the pandas dataframe before building the chart:

data['name'] = data['name'].replace({
    'audiobook_processed': 'Audiobook processed',
    'n_unknown_errors': 'Unknown Errors',
    'n_known_errors': 'Known Errors',
})
```

and then skip transform_fold, because it does not apply here.

Body:
I am trying to edit the labels from the data a have received from a database. As of now I have tried using .transform_fold() but when I run my code the correct titles are appearing but with no data shown on the Graph.

With out the .transform_fold() the graph looks like the following:

And like the following with .transform_fold():

I would like to have the titles changed like so:

title from data
New title

audiobook_processed
Audiobooks processed

n_known_errors
Known Errors

n_unknown_errors
Unknown Errors

The data I receive is like the following:

date
value
name

2022-01-19
98
audiobook_processed

2022-01-19
69
n_known_errors

2022-01-19
2
n_unknown_errors

My code:

import altair as alt
import streamlit as st
import pandas as pd
import datetime

from xxx.input import get_xxx_metrics

def graph_visual_data():
    data = get_xxx_metrics('audiobook')
    data = data[data.name.isin(['audiobook_processed', 'n_unknown_errors', 'n_known_errors'])][['date','value','name']]

    data.date = data.date.dt.date
    data.value = data.value.astype(int)

    data = data.groupby(['date','name'], as_index=False).sum()

    fig = (alt.Chart(data).transform_fold(
    fold=['Audiobooks processed', 'Known Errors','Unknown Errors'],
    as_=['name', 'value']).mark_bar(size=15).encode(
        x=alt.X('date:T', axis=alt.Axis(format='%b %-d'), scale=alt.Scale(padding=15), title='Dates processed on'),
        y=alt.Y('value', title='Total amount'),
        color=alt.Color('name', title='Audiobooks processed and errors', sort=['audiobook_processed']),
        tooltip=['name', 'value', 'date']).properties(width=500))
    st.altair_chart(fig)

Body:
You could do this by replacing the values within the pandas dataframe before building the chart:

data['name'] = data['name'].replace({
    'audiobook_processed': 'Audiobook processed',
    'n_unknown_errors': 'Unknown Errors',
    'n_known_errors': 'Known Errors',
})

and then skip transform_fold, because it does not apply here.


问:
Is my model overfitting or underfitting ? .How to identify it from this loss curve?
I have created a model based on the mobileNet architecture to classify images. I have used 209222 images for training and 40000 images for validation. After I trained the model the loss curve looks like below. Is this model overfitting or underfitting ? or as the validation and training loss curves are closer to each other and they are flat after some point, can I get this as a good model?. I have attached my loss curves below.
loss curve</p>

答: If loss is less then that means your solution might be converging. As your val_loss and train_loss don't have that much difference and both are converging then that implies that your model is not overfitting</p>


问:
React on UniqueKeyViolation in SQLAlchemy
I have 2 Tables in SQLAlchemy (using declerative_base()) that are joined via a seperate Table relationship

```<code># no comment on the wired naming....
site_word = Table('word_site', Base.metadata,
    Column('site_id', Integer, ForeignKey('sites.site_id'), nullable = False, primary_key = True),
    Column('word_id', Integer, ForeignKey('site_words.word_id'), nullable = False, primary_key = True))
</code>```

Word mapping

```<code>class Word(Base):
   # snip
   word =  Column('word', Text, nullable = False, unique = True)
   sites = relationship('Site', secondary = site_word, back_populates = 'words')
</code>```

Site mapping

```<code>class Site(Base):
   # snip
   words = relationship('Word', secondary = site_word, back_populates = 'sites')
</code>```

Inserting works like expected, inserting of already existing words fails of course due to unique in Word.word.

I tried using a before_insert event to check if the item already exists.

```<code>event.listen(Word, 'before_insert', some_event)
</code>```

I can get the information to identify the word uniquly as expected but I don't know how to add a new value to the join table (site_word).

I could write a trigger or procedure for the database but don't want to move too much logic into the database (don't know if this would be possible since the Site wouldn't be known at that time). I could remove the constraint for the word-column but I still can't figure out how to access the information (the other end of the join) to create an entry in the join table, but not in the Word table.

I am looking for a way to create a entry in the site_word and Site table only.

update 1:

I could attach the event to the Site but I don't see a possibility to get the information of the to-be-inserted Site. Is there a possibility to save the Site and create the join-relation afterwards?

答:
I managed to do it. Mark Gemmill's answer got me thinking in the right direction.

I need to listen to an AttributeEvent instead of an MapperEvent.

```<code>event.listen(Site.words, 'append', test_event, retval = True)
</code>```

Then I can do something like:

```<code>def test_event(target, value, initiator):
    try:
        return session.query(Word).filter(Word.word == value.word.lower()).one()
    except sqlalchemy.orm.exc.NoResultFound:
        return value
</code>```

This either returns the existing word from the table or simply returns the mapped object that needs to be persisted.

Body:
I have 2 Tables in SQLAlchemy (using declerative_base()) that are joined via a seperate Table relationship

# no comment on the wired naming....
site_word = Table('word_site', Base.metadata,
    Column('site_id', Integer, ForeignKey('sites.site_id'), nullable = False, primary_key = True),
    Column('word_id', Integer, ForeignKey('site_words.word_id'), nullable = False, primary_key = True))

Word mapping

class Word(Base):
   # snip
   word =  Column('word', Text, nullable = False, unique = True)
   sites = relationship('Site', secondary = site_word, back_populates = 'words')

Site mapping

class Site(Base):
   # snip
   words = relationship('Word', secondary = site_word, back_populates = 'sites')

Inserting works like expected, inserting of already existing words fails of course due to unique in Word.word.

I tried using a before_insert event to check if the item already exists.

event.listen(Word, 'before_insert', some_event)

I can get the information to identify the word uniquly as expected but I don't know how to add a new value to the join table (site_word).

I could write a trigger or procedure for the database but don't want to move too much logic into the database (don't know if this would be possible since the Site wouldn't be known at that time). I could remove the constraint for the word-column but I still can't figure out how to access the information (the other end of the join) to create an entry in the join table, but not in the Word table.

I am looking for a way to create a entry in the site_word and Site table only.

update 1:

I could attach the event to the Site but I don't see a possibility to get the information of the to-be-inserted Site. Is there a possibility to save the Site and create the join-relation afterwards?

Body:
I managed to do it. Mark Gemmill's answer got me thinking in the right direction.

I need to listen to an AttributeEvent instead of an MapperEvent.

event.listen(Site.words, 'append', test_event, retval = True)

Then I can do something like:

def test_event(target, value, initiator):
    try:
        return session.query(Word).filter(Word.word == value.word.lower()).one()
    except sqlalchemy.orm.exc.NoResultFound:
        return value

This either returns the existing word from the table or simply returns the mapped object that needs to be persisted.


问:
CUDA error: CUBLAS_STATUS_ALLOC_FAILED when calling cublasCreate(handle)
I got the following error when I ran my PyTorch deep learning model in Google Colab

```<code>/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py in linear(input, weight, bias)
   1370         ret = torch.addmm(bias, input, weight.t())
   1371     else:
-> 1372         output = input.matmul(weight.t())
   1373         if bias is not None:
   1374             output += bias

RuntimeError: CUDA error: CUBLAS_STATUS_ALLOC_FAILED when calling `cublasCreate(handle)`
</code>```

I even reduced batch size from 128 to 64 i.e., reduced to half,  but still, I got this error. Earlier, I ran the same code with a batch size of 128 but didn't get any error like this.

答:
I had the same problem while I don't know the reason to be exactly I know the cause,
my last line of the NN.module was

```<code> self.fc3 = nn.Linear(84, num_classes)
</code>```

I changed my real num_classes to be 2 times as much
but it did not change the value of the variable num_classes, this probably made a mistake when I was outputting the results somewhere.

after I fixed the value of num_classes it just worked out
i recommend going over the numbers in your model again

Body:
I got the following error when I ran my PyTorch deep learning model in Google Colab

/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py in linear(input, weight, bias)
   1370         ret = torch.addmm(bias, input, weight.t())
   1371     else:
-> 1372         output = input.matmul(weight.t())
   1373         if bias is not None:
   1374             output += bias

RuntimeError: CUDA error: CUBLAS_STATUS_ALLOC_FAILED when calling `cublasCreate(handle)`

I even reduced batch size from 128 to 64 i.e., reduced to half,  but still, I got this error. Earlier, I ran the same code with a batch size of 128 but didn't get any error like this.

Body:
I had the same problem while I don't know the reason to be exactly I know the cause,
my last line of the NN.module was

 self.fc3 = nn.Linear(84, num_classes)

I changed my real num_classes to be 2 times as much
but it did not change the value of the variable num_classes, this probably made a mistake when I was outputting the results somewhere.

after I fixed the value of num_classes it just worked out
i recommend going over the numbers in your model again


问:
Having problem in changing css using useState in react
I'm trying to build a modal in react. When it's opened, the background or the body color must change to a darker one and the modal should open, when closed, everything must go back to normal.
I tried to achieve this by this method:

```<code>const [modalState, setModalState] = useState(false);
const [modalBg, setModalbg] = useState(false);

function handleClick() {
    setModalState(true);
    setModalbg(true);

}
return (
  {
      !modalState ?
       null
       : <Modal modalState = {setModalState}/>
  }
  {
      !modalBg ?
       document.body.style.backgoundColor = "ffff"
      : document.body.style.backgoundColor = 'rgba(39, 38, 38, 0.616)'
  }
  <button onClick= {handleClick}>Open</button>

)
</code>```

The problem is, that instead of changing color of the body, it just renders text to the page like '#fff' or 'red'. I don't know why that happens, can anyone help?

Thanks!

答:
You should not set the background colour of the body in the return function. That is meant to return the JSX.

Try using a useEffect hook something like:

```<code>useEffect(() => {
  if (modalBg) {
    document.body.style.backgoundColor = "rgba(39, 38, 38, 0.616)";
  } else {
    document.body.style.backgoundColor = "ffff";
  }
}, [modalBg]);
</code>```

Body:
I'm trying to build a modal in react. When it's opened, the background or the body color must change to a darker one and the modal should open, when closed, everything must go back to normal.
I tried to achieve this by this method:

const [modalState, setModalState] = useState(false);
const [modalBg, setModalbg] = useState(false);

function handleClick() {
    setModalState(true);
    setModalbg(true);

}
return (
  {
      !modalState ?
       null
       : <Modal modalState = {setModalState}/>
  }
  {
      !modalBg ?
       document.body.style.backgoundColor = "ffff"
      : document.body.style.backgoundColor = 'rgba(39, 38, 38, 0.616)'
  }
  <button onClick= {handleClick}>Open</button>

)

The problem is, that instead of changing color of the body, it just renders text to the page like '#fff' or 'red'. I don't know why that happens, can anyone help?

Thanks!

Body:
You should not set the background colour of the body in the return function. That is meant to return the JSX.

Try using a useEffect hook something like:

useEffect(() => {
  if (modalBg) {
    document.body.style.backgoundColor = "rgba(39, 38, 38, 0.616)";
  } else {
    document.body.style.backgoundColor = "ffff";
  }
}, [modalBg]);


问:
Is there a way to easilly create union type from enum in Typescript?
often when I'm writing Typescript I'm running into situations where I have enum of some sort and from this enum I want to generate union type. I tried looking for utility type which would do it for me but I wasn't able to find any. Is there an easier way of doing so?

```<code>enum Person {
  Name = "Adam",
  Age = 32
}

type Something = Person.Name | Person.Age;
</code>```

I know that this example is rather simple but often I have enums with a tone of entries and doing it by hand is neither enjoyable nor maintainable.

答:
An enum type is itself already equivalent to the union of all members of that enum.

You can even see this in action if you try to use Exclude to remove a member from the enum:

```<code>enum Person {
  Name = "Adam",
  Age = 32
}

type Something = Exclude<Person, Person.Age> // Person.Name
</code>```

Playground Link

Body:
often when I'm writing Typescript I'm running into situations where I have enum of some sort and from this enum I want to generate union type. I tried looking for utility type which would do it for me but I wasn't able to find any. Is there an easier way of doing so?

enum Person {
  Name = "Adam",
  Age = 32
}

type Something = Person.Name | Person.Age;

I know that this example is rather simple but often I have enums with a tone of entries and doing it by hand is neither enjoyable nor maintainable.

Body:
An enum type is itself already equivalent to the union of all members of that enum.

You can even see this in action if you try to use Exclude to remove a member from the enum:

enum Person {
  Name = "Adam",
  Age = 32
}

type Something = Exclude<Person, Person.Age> // Person.Name

Playground Link