问:
Getting an error Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured
The full error is

```<code>Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class
</code>```

I have the following datasource set up in my application.yml

```<code>spring:
  datasource:
    reader:
      username: admin
      password: password
      driver-class-name: com.mysql.cj.jdbc.Driver
      jdbcUrl: jdbc:mysql://<aurora-mysql-reader-endpoint_instance>:3306/credentialdb
      pattern: get*,find*
    writer:
      username: admin
      password: password
      driver-class-name: com.mysql.cj.jdbc.Driver
      jdbcUrl: jdbc:mysql://<aurora-mysql-reader-endpoint_instance>/credentialdb
      pattern: add*,update*
  jpa:
    hibernate:
      ddl-auto: update
</code>```

I did google and the number one comment is

```<code>@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
</code>```

But causes the following code to fall over

```<code>public interface CredentialRepository extends CrudRepository<CredentialEntity, Long> {
}
</code>```
```<code>@Service
public class CredentialServicesImpl implements CredentialServices {

    @Autowired
    CredentialRepository credentialrepository;

</code>```

With the exception

```<code>NoSuchBeanDefinitionException: No qualifying bean of type 'com.opsec.shared.harvesting.fetcher.credentialmanger.repository.CredentialRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
</code>```

So ho how do I get around the original exception
Failed to configure a DataSource: 'url' attribute is not specified

I think it may be a dependency issue i am trying to connect to a AWS RDS aurora mysql but my dependency is

```<code> <!-- spring  -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <!-- SQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.15</version>
        </dependency>
</code>```

答:
Ok the data source is as

```<code>spring:
  datasource:
    url: jdbc:mysql://<aurora-mysql-reader-endpoint_instance>:3306/credentialdb?sslMode=DISABLED
    username: admin
    password: password
    driver-class-name: com.mysql.cj.jdbc.Driver
  jpa:
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQL5Dialect
  hibernate:
    ddl-auto: update
</code>```

Connects to the aurora db

Body:
The full error is

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class

I have the following datasource set up in my application.yml

spring:
  datasource:
    reader:
      username: admin
      password: password
      driver-class-name: com.mysql.cj.jdbc.Driver
      jdbcUrl: jdbc:mysql://<aurora-mysql-reader-endpoint_instance>:3306/credentialdb
      pattern: get*,find*
    writer:
      username: admin
      password: password
      driver-class-name: com.mysql.cj.jdbc.Driver
      jdbcUrl: jdbc:mysql://<aurora-mysql-reader-endpoint_instance>/credentialdb
      pattern: add*,update*
  jpa:
    hibernate:
      ddl-auto: update

I did google and the number one comment is

@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})

But causes the following code to fall over

public interface CredentialRepository extends CrudRepository<CredentialEntity, Long> {
}

@Service
public class CredentialServicesImpl implements CredentialServices {

    @Autowired
    CredentialRepository credentialrepository;

With the exception

NoSuchBeanDefinitionException: No qualifying bean of type 'com.opsec.shared.harvesting.fetcher.credentialmanger.repository.CredentialRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

So ho how do I get around the original exception
Failed to configure a DataSource: 'url' attribute is not specified

I think it may be a dependency issue i am trying to connect to a AWS RDS aurora mysql but my dependency is

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.15</version>
        </dependency>

Body:
Ok the data source is as

spring:
  datasource:
    url: jdbc:mysql://<aurora-mysql-reader-endpoint_instance>:3306/credentialdb?sslMode=DISABLED
    username: admin
    password: password
    driver-class-name: com.mysql.cj.jdbc.Driver
  jpa:
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQL5Dialect
  hibernate:
    ddl-auto: update

Connects to the aurora db


来源: stackexchange

问:
Is there a way to use python in android applications programming?
I am working on an application that uses eye-tracking technology to detect eye movements..
what I want to ask, is there any way to use python to develop Android application? or integrate it with android studio?

and what is best language to develop an application with an eye tracking feature?

答:
You can use a few languages.
Kotlin - to create UI
C++ - to create native lib
If you want to detect something you can use tenderflow

ContentLicense: CC BY-SA 4.0


问:
How to apply styles on shadow DOM
I'm trying to apply some styles on the shadow DOM. I have this example:

const existingElement = document.getElementById("foo");
const shadow = existingElement.attachShadow({ mode: "open" });
const message = document.createElement("p");

message.setAttribute("class", "text");
message.textContent = "Hello World!";
shadow.appendChild(message);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#foo::shadow .text{
  color: blue; //not working
}</code>```

```

In the snippet I'm generating a
Hello World!
 in the shadow root inside that

I need to apply styles to that class text but as it is inside the shadow DOM I can't apply any styles directly. I have tried with ::shadow, ::ng-deep, ::content but no results yet. Any idea?

答:
I have been trying to find some information about this. And what I can find is that a shadow element is completly seperate from the other parts of the environment. Though as the link below stats

It’s worth noting that inheritable styles like color, font and line-height are still inherited in a shadow DOM. To prevent that, use all: initial  or, preferably, all: revert once it has better browser support.

Styling in the Shadow DOM With CSS Shadow Parts

I played around with some of your code and made something like this. Which makes the external css have effect over the shadow dom.

const existingElement = document.getElementById("foo");
const shadow = existingElement.attachShadow({ mode: "open" });
const message = document.createElement("p");

message.setAttribute("part", "text");
message.textContent = "Hello World!";
shadow.appendChild(message);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#foo::part(text) {
  color: blue;
}</code>```

```

Instead of having the setAttribute set a class, you set a part. This seems to get the desired effect that you want. It also needs to be said that you are able to set a attribute in JavaScript to apply style to it directly.

Title: How to apply styles on shadow DOM

Body:
I'm trying to apply some styles on the shadow DOM. I have this example:

const existingElement = document.getElementById("foo");
const shadow = existingElement.attachShadow({ mode: "open" });
const message = document.createElement("p");

message.setAttribute("class", "text");
message.textContent = "Hello World!";
shadow.appendChild(message);

#foo::shadow .text{
  color: blue; //not working
}

In the snippet I'm generating a
Hello World!
 in the shadow root inside that

I need to apply styles to that class text but as it is inside the shadow DOM I can't apply any styles directly. I have tried with ::shadow, ::ng-deep, ::content but no results yet. Any idea?

Body:
I have been trying to find some information about this. And what I can find is that a shadow element is completly seperate from the other parts of the environment. Though as the link below stats

It’s worth noting that inheritable styles like color, font and line-height are still inherited in a shadow DOM. To prevent that, use all: initial  or, preferably, all: revert once it has better browser support.

Styling in the Shadow DOM With CSS Shadow Parts

I played around with some of your code and made something like this. Which makes the external css have effect over the shadow dom.

const existingElement = document.getElementById("foo");
const shadow = existingElement.attachShadow({ mode: "open" });
const message = document.createElement("p");

message.setAttribute("part", "text");
message.textContent = "Hello World!";
shadow.appendChild(message);

#foo::part(text) {
  color: blue;
}

<div id="foo"></div>

Instead of having the setAttribute set a class, you set a part. This seems to get the desired effect that you want. It also needs to be said that you are able to set a attribute in JavaScript to apply style to it directly.


问:
How does one update a stored procedure or a table to mimic a clone in another database?
We have three main servers we use for a project: development, preproduction and production.

We need the "preproduction" server to be as much as possible in sync with the production server, so we plan to, every two weeks, update everything in the database to match any new changes made in production in that period of time.

For the database information, we're using Linked servers, to retrieve the latest data from production. The problem is, how to do something similar for the stored procedures?

Is there a way to make it so that, if a change was made to a production server stored procedure, such change would be made also to preproduction without doing it manually? It can be somewhat slow, since we would do it throughout the night.

Same thing with any changes made to a table structure in that time, is there any way to detect it and run it? We would like a script we could run every two weeks, but if not possible, we could look into other options.

答:
SqlPackage is the native SQL Server tool to generate schema drift scripts, and to deploy database schema changes.

Note you should deploy your changes to non-prod environments first, not last.


问:
Filtering data based on value from other data frame using dplyr
I want to detect outliers from a data frame with grouping.
Here is the data:

```<code># create 3 outliers for each group
df <- data.frame(factor = rep(c("A", "B", "C", "D"), each = 15),
                 value = c(rnorm(12, 10, 1), rnorm(3, 16.8, 1),
                           rnorm(12, 10.4, 1), rnorm(3, 17.6, 1),
                           rnorm(12, 9.7, 1), rnorm(3, 17.7, 1),
                           rnorm(12, 9.8, 1), rnorm(3, 17.8, 1)))
</code>```

Using interquartile (IQR) method to determine outliers, I created a new data frame that contain "upper limit" and "lower limit" for outliers for each group.

```<code>quant <- group_by(df, factor) %>%
         summarise(q25 = quantile(value, 0.25),
                   q75 = quantile(value, 0.75),
                   iqr = IQR(value),
                   up = q75 + 1.5*iqr,
                   low = q25 - 1.5*iqr)
</code>```

I would like to filter df data frame using value from quant to determine what data points count as outliers. For example, group A in df should be filtered based on value of "up" and "low" from group A in quant. Here is the rough idea of what I want to do (however, this code doesn't work as intended).

```<code># detect outliers
df %>% group_by(factor) %>% filter(value > quant$up | value < quant$low)

# remove outliers
df %>% group_by(factor) %>% filter(value < quant$up & value > quant$low)
</code>```

答:
I would recommend starting by joining the two data frames together:

output = df %>%
  left_join(quant, by = "factor")
```
<p>You can then filter as required:</p>
<pre class="lang-r prettyprint-override"><code>output %>%
  mutate(is_outlier = value > up | value < low) %>%
  filter(!is_outlier)
</code>```

Body:
I want to detect outliers from a data frame with grouping.
Here is the data:

# create 3 outliers for each group
df <- data.frame(factor = rep(c("A", "B", "C", "D"), each = 15),
                 value = c(rnorm(12, 10, 1), rnorm(3, 16.8, 1),
                           rnorm(12, 10.4, 1), rnorm(3, 17.6, 1),
                           rnorm(12, 9.7, 1), rnorm(3, 17.7, 1),
                           rnorm(12, 9.8, 1), rnorm(3, 17.8, 1)))

Using interquartile (IQR) method to determine outliers, I created a new data frame that contain "upper limit" and "lower limit" for outliers for each group.

quant <- group_by(df, factor) %>%
         summarise(q25 = quantile(value, 0.25),
                   q75 = quantile(value, 0.75),
                   iqr = IQR(value),
                   up = q75 + 1.5*iqr,
                   low = q25 - 1.5*iqr)

I would like to filter df data frame using value from quant to determine what data points count as outliers. For example, group A in df should be filtered based on value of "up" and "low" from group A in quant. Here is the rough idea of what I want to do (however, this code doesn't work as intended).

# detect outliers
df %>% group_by(factor) %>% filter(value > quant$up | value < quant$low)

# remove outliers
df %>% group_by(factor) %>% filter(value < quant$up & value > quant$low)

Body:
I would recommend starting by joining the two data frames together:

output = df %>%
  left_join(quant, by = "factor")

You can then filter as required:

output %>%
  mutate(is_outlier = value > up | value < low) %>%
  filter(!is_outlier)


问:
Understanding conflicting Interfaces
I am trying to understand the interface concept.
The following is my test code:

```<code>package main

import "fmt"

//interface
type InterfaceA interface {
    A() string
}

//interface
type InterfaceB interface {
    A() string
}

//user defined type structure
type structure struct {
    a string
}

//implementing A(), but which A() ?
func (strt structure) A() string {
    return strt.a
}

func main() {
    fmt.Println("Start")
    variable := structure{"hello"}
    fmt.Println(variable.A())
}

</code>```

As per the documentation, I understand that there is no explicit mention of "Implements" like in other languages. But when I call variable.A() which interface is my type structure using? InterfaceA or InterfaceB ? Plus, am I actually implementing the interface properly?

答:
When you call variable.A(), you are not using any interfaces. You are calling a method of the type structure.

You can call the same method using an interface:

```<code>variable := structure{"hello"}
var ia InterfaceA
ia=variable
ia.A() // This calls variable.A
var ib InterfaceB
ib=variable
ib.A() // This also calls variable.A
</code>```

Title: Understanding conflicting Interfaces

Body:
I am trying to understand the interface concept.
The following is my test code:

package main

import "fmt"

//interface
type InterfaceA interface {
    A() string
}

//interface
type InterfaceB interface {
    A() string
}

//user defined type structure
type structure struct {
    a string
}

//implementing A(), but which A() ?
func (strt structure) A() string {
    return strt.a
}

func main() {
    fmt.Println("Start")
    variable := structure{"hello"}
    fmt.Println(variable.A())
}

As per the documentation, I understand that there is no explicit mention of "Implements" like in other languages. But when I call variable.A() which interface is my type structure using? InterfaceA or InterfaceB ? Plus, am I actually implementing the interface properly?

Body:
When you call variable.A(), you are not using any interfaces. You are calling a method of the type structure.

You can call the same method using an interface:

variable := structure{"hello"}
var ia InterfaceA
ia=variable
ia.A() // This calls variable.A
var ib InterfaceB
ib=variable
ib.A() // This also calls variable.A


问:
How do I explicitely initialize the copy constructor for a class that inherits from std::enable_shared_from_this
Consider the following test code:

```<code>#include <memory>

class C : public std::enable_shared_from_this<C>
{
    public:
    C(C const& c){}
};

int main()
{

}
</code>```

Compiling this with -Wextra will generate the following warning

warning: base class 'class std::enable_shared_from_this' should be explicitly initialized in the copy constructor [-Wextra]

How do I do this correctly? Is there anything that I could trip over in more complicated classes?

答:
You can explicitly initialize it by calling its default constructor like this:

```<code>C(C const& c) : enable_shared_from_this() {}
</code>```

You can also do it by calling its copy constructor like this:

```<code>C(C const& c) : enable_shared_from_this(c) {}
</code>```

The copy constructor actually does the same thing as the default constructor (it marks the current object as not being owned by a shared_ptr) This ensures that the following will do the sensible thing:

```<code>C(C const& c) = default;  // also calls the copy constructor of the enable_shared_from_this base
</code>```

When an object is copied, you get a new object, so, obviously, it's not owned by the same shared_ptr that the other object is.

Body:
Consider the following test code:

#include <memory>

class C : public std::enable_shared_from_this<C>
{
    public:
    C(C const& c){}
};

int main()
{

}

Compiling this with -Wextra will generate the following warning

warning: base class 'class std::enable_shared_from_this' should be explicitly initialized in the copy constructor [-Wextra]

How do I do this correctly? Is there anything that I could trip over in more complicated classes?

Body:
You can explicitly initialize it by calling its default constructor like this:

C(C const& c) : enable_shared_from_this() {}

You can also do it by calling its copy constructor like this:

C(C const& c) : enable_shared_from_this(c) {}

The copy constructor actually does the same thing as the default constructor (it marks the current object as not being owned by a shared_ptr) This ensures that the following will do the sensible thing:

C(C const& c) = default;  // also calls the copy constructor of the enable_shared_from_this base

When an object is copied, you get a new object, so, obviously, it's not owned by the same shared_ptr that the other object is.


问:
How to call random number from contact list? [Flutter]
Using FlutterPhoneDirectCaller, I'm looking for a way to randomly selected phone number from contact list and make a direct call.

getContacts() worked properly getting all the phone numbers from my phone, though I'm having trouble making var list for randomly selecting number from the list.

```<code>import 'package:permission_handler/permission_handler.dart';
import 'package:contacts_service/contacts_service.dart';
import 'package:flutter_phone_direct_caller/flutter_phone_direct_caller.dart';

    var contacts = ContactsService.getContacts();
    var list = [contacts];
      final _random = new Random();
    var element = list[_random.nextInt(list.length)];

    void checkContactPermission() async {
      var status = await Permission.contacts.status;
      if (status.isGranted) {
        FlutterPhoneDirectCaller(_random.nextInt(list.length));
      }
</code>```

答:
After getting the contacts, you need to pass number on FlutterPhoneDirectCaller. Based on documentation, you need to use like.

  const number =  _random.nextInt(list.length - 1);
  bool res = await FlutterPhoneDirectCaller.callNumber(number);
```

Body:
Using FlutterPhoneDirectCaller, I'm looking for a way to randomly selected phone number from contact list and make a direct call.

getContacts() worked properly getting all the phone numbers from my phone, though I'm having trouble making var list for randomly selecting number from the list.

import 'package:permission_handler/permission_handler.dart';
import 'package:contacts_service/contacts_service.dart';
import 'package:flutter_phone_direct_caller/flutter_phone_direct_caller.dart';

    var contacts = ContactsService.getContacts();
    var list = [contacts];
      final _random = new Random();
    var element = list[_random.nextInt(list.length)];

    void checkContactPermission() async {
      var status = await Permission.contacts.status;
      if (status.isGranted) {
        FlutterPhoneDirectCaller(_random.nextInt(list.length));
      }


问:
NiFi - How can i change ReplacementValue on ReplaceText?
I'm using ExecuteSQL,SplitAvro,ConvertAvroToJSON,EvaluateJsonPath,ReplaceText,ExecuteSQL.

I am trying to replace the content in the flowfile using replaceText processor.

Now, i can replace like this. -> INSERT INTO values (${id},'${name}') . ReplaceText process send excute sql like this :

INSERT into x values(1,'xx')

INSERT into x values(2,'yy')

INSERT into x values(3,'zz')

I'm sending INSERT query for each line.

But i want to send executesql process like this

INSERT INTO x values (1,'xx'),(2,'yy'),(3,'zz')

答:
i'm not sure it's the best approach but you could do this:

SplitAvro           # i guess you are splitting the records here (here you should get fragment.* attributes)
ConvertAvroToJSON   # converting each record to json
EvaluateJsonPath    # getting id,name values from json
ReplaceText         # (${id}, '${name}')
MergeContent        # merge rows back to single file with header and delimiter
   Binary Concatenation
   Header = Insert into X values
   Demarcator = ,
ExecuteSQL
```


问:
R: Add a table1 to ggdraw figure
I am trying to make a figure that includes a table1 (here is my example table1: mtcars table1) and some plots using ggdraw.

```<code>library(htmlTable)
library(table1)
library(tibble)
library(Hmisc)
library(cowplot)
mtcars
table_mtcars <- table1(~cyl +disp + hp, data = mtcars)
table_mtcars
mtcars_plot <- ggplot(mtcars, aes(x = cyl, y = disp)) +
  geom_jitter()
mtcars_plot

mtcars_plot2 <- ggplot(mtcars, aes(x = cyl, y = hp)) +
  geom_jitter() +
  ggtitle('with hp')
mtcars_plot2

ggdraw() +
  draw_plot(table_mtcars, x = 0, y = .5, width = .5, height = .5) +
  draw_plot(mtcars_plot, x = .5, y = .5, width = .5, height = .5) +
  draw_plot(mtcars_plot2, x = 0, y = 0, width = 1, height = 0.5) +
  draw_plot_label(label = c("A", "B", "C"), size = 15,
                  x = c(0, 0.5, 0), y = c(1, 1, 0.5))

</code>```

Unfortunately, only the plots show up here: ggdraw example image. Is there a way to insert a table into a ggdraw image? Thank you.

答:
One option to achieve your desired result using cowplot and table1 would be to convert your table to a flextable via table1::t1flex which allows to follow the answer referenced by @DanAdams in his comment, i.e. converting the flextable to a raster image via flextable::as_raster and adding it to the plot grid as a grid::rasterGrob.

Note: I added some padding around the table by adjusting the width and height and the position. But you could set that as you like.

library(table1)
library(cowplot)
library(ggplot2)
library(magrittr)
library(flextable)

table_mtcars <- table1(~cyl +disp + hp, data = mtcars) %>%
  t1flex() %>%
  flextable::as_raster()

mtcars_plot <- ggplot(mtcars, aes(x = cyl, y = disp)) +
  geom_jitter()

mtcars_plot2 <- ggplot(mtcars, aes(x = cyl, y = hp)) +
  geom_jitter() +
  ggtitle('with hp')

ggdraw() +
  draw_plot(grid::rasterGrob(table_mtcars), x = 0.025, y = .525, width = .45, height = .45) +
  draw_plot(mtcars_plot, x = .5, y = .5, width = .5, height = .5) +
  draw_plot(mtcars_plot2, x = 0, y = 0, width = 1, height = 0.5) +
  draw_plot_label(label = c("A", "B", "C"), size = 15,
                  x = c(0, 0.5, 0), y = c(1, 1, 0.5))
```

Title: R: Add a table1 to ggdraw figure

Body:
I am trying to make a figure that includes a table1 (here is my example table1: mtcars table1) and some plots using ggdraw.

library(htmlTable)
library(table1)
library(tibble)
library(Hmisc)
library(cowplot)
mtcars
table_mtcars <- table1(~cyl +disp + hp, data = mtcars)
table_mtcars
mtcars_plot <- ggplot(mtcars, aes(x = cyl, y = disp)) +
  geom_jitter()
mtcars_plot

mtcars_plot2 <- ggplot(mtcars, aes(x = cyl, y = hp)) +
  geom_jitter() +
  ggtitle('with hp')
mtcars_plot2

ggdraw() +
  draw_plot(table_mtcars, x = 0, y = .5, width = .5, height = .5) +
  draw_plot(mtcars_plot, x = .5, y = .5, width = .5, height = .5) +
  draw_plot(mtcars_plot2, x = 0, y = 0, width = 1, height = 0.5) +
  draw_plot_label(label = c("A", "B", "C"), size = 15,
                  x = c(0, 0.5, 0), y = c(1, 1, 0.5))

Unfortunately, only the plots show up here: ggdraw example image. Is there a way to insert a table into a ggdraw image? Thank you.


问:
Add "id" to the first in each object in an array (JavaScript)
I could add "id" to each object in the array "data":

const data = [
  { name: "John", age: 24 },
  { name: "Marry", age: 18 },
  { name: "Tom", age: 15 },
]

for(const key in data) {
  data[key]['id'] = key;
}

console.log(data);```
</div>
</div>
</p>
<p>But <strong>"id"</strong> is added to the last in each object in the array <strong>"data"</strong>:</p>
<pre class="lang-js prettyprint-override"><code>[
  { name: "John", age: 24, id: "0" },
  { name: "Marry", age: 18, id: "1" },
  { name: "Tom", age: 15, id: "2" }
]
</code>```

My desired result is this below adding "id" to the first in each object in the array "data":

[
  { id: "0", name: "John", age: 24 },
  { id: "1", name: 'Marry', age: 18 },
  { id: "2", name: 'Tom', age: 15 }
]
```

Are there any ways to do that?

答:
Create the array "newData" with "id" and the array "data":

const data = [
  { name: "John", age: 24 },
  { name: "Marry", age: 18 },
  { name: "Tom", age: 15 },
]

const newData = [];

for(const key in data) {

  const obj = {
    id: key,
    ...data[key]
  }

  newData.push(obj);
}

console.log(newData);```
</div>
</div>
</p>
<p>This is the result:</p>
<pre class="lang-js prettyprint-override"><code>[
  { id: "0", name: "John", age: 24 },
  { id: "1", name: 'Marry', age: 18 },
  { id: "2", name: 'Tom', age: 15 }
]
</code>```

In addition, if you want "id" of Number type, use "Number()":

const data = [
  { name: "John", age: 24 },
  { name: "Marry", age: 18 },
  { name: "Tom", age: 15 },
]

const newData = [];

for(const key in data) {

  const obj = {
    id: Number(key), // Here
    ...data[key]
  }

  newData.push(obj);
}

console.log(newData);```
</div>
</div>
</p>
<p>This is the result:</p>
<pre class="lang-js prettyprint-override"><code>[
  { id: 0, name: "John", age: 24 },
  { id: 1, name: 'Marry', age: 18 },
  { id: 2, name: 'Tom', age: 15 }
]
</code>```

Body:
I could add "id" to each object in the array "data":

const data = [
  { name: "John", age: 24 },
  { name: "Marry", age: 18 },
  { name: "Tom", age: 15 },
]

for(const key in data) {
  data[key]['id'] = key;
}

console.log(data);

But "id" is added to the last in each object in the array "data":

[
  { name: "John", age: 24, id: "0" },
  { name: "Marry", age: 18, id: "1" },
  { name: "Tom", age: 15, id: "2" }
]

My desired result is this below adding "id" to the first in each object in the array "data":

[
  { id: "0", name: "John", age: 24 },
  { id: "1", name: 'Marry', age: 18 },
  { id: "2", name: 'Tom', age: 15 }
]

Are there any ways to do that?

Body:
Create the array "newData" with "id" and the array "data":

const data = [
  { name: "John", age: 24 },
  { name: "Marry", age: 18 },
  { name: "Tom", age: 15 },
]

const newData = [];

for(const key in data) {

  const obj = {
    id: key,
    ...data[key]
  }

  newData.push(obj);
}

console.log(newData);

This is the result:

[
  { id: "0", name: "John", age: 24 },
  { id: "1", name: 'Marry', age: 18 },
  { id: "2", name: 'Tom', age: 15 }
]

In addition, if you want "id" of Number type, use "Number()":

const data = [
  { name: "John", age: 24 },
  { name: "Marry", age: 18 },
  { name: "Tom", age: 15 },
]

const newData = [];

for(const key in data) {

  const obj = {
    id: Number(key), // Here
    ...data[key]
  }

  newData.push(obj);
}

console.log(newData);

This is the result:

[
  { id: 0, name: "John", age: 24 },
  { id: 1, name: 'Marry', age: 18 },
  { id: 2, name: 'Tom', age: 15 }
]


问:
how fix cycle in django?
I have problem with cycle in djano(Maybe I dont understand this).I have cycle in template and it must to output value from database,but Idk how I can create cycle,which may output value from (id = 1),because this cycle output value (id = 0) again and again.

vds.html

```<code>{% for item in allobjects %}

  <div class="container-fluid">
        <div class="body2">
      <li class="title">{{item.title}}</li>
      <li class="listram">{{item.ram}}<small>ГБ(озу)</small></li>
      <img class="ram2"width="51px" height="49px" src="/static/main/images/ram.png" ></img>
      <li class="cpu">{{item.cpu}} vCore</li>
      <img class="cpu1"width="51px" height="50px"  src="/static/main/images/cpu.png" ></img>
     <li class="hdd">{{item.hdd}}<small> ГБ(ssd)</small></li>
     <img class="hdd1"width="51px" height="50px" src="/static/main/images/hdd.png" ></img>
     <li class="os">Установка любой ос</li>
     <img  class="os1 " width="47px" height="49px"src="/static/main/images/os.png"/>
     <li class="os">Виртуализация KVM</li>
     <img  class="os1 " width="47px" height="49px"src="/static/main/images/vds.png"/>
     <form action="https://billing.king-host.ru">
         <button type="submit" name="buy">Купить</button>
         </form>
     <li class= "prise">{{item.name}}₽/месяц</li>
  </div>
  </div>

  <div class="container-fluid">
        <div class="body3">
      <li class="title">{{item.title}}</li>
      <li class="listram"><small>ГБ(озу)</small></li>
      <img class="ram2"width="51px" height="49px" src="/static/main/images/ram.png" ></img>
      <li class="cpu">2 vCore</li>
      <img class="cpu1"width="51px" height="50px"  src="/static/main/images/cpu.png" ></img>
     <li class="hdd">40<small> ГБ(ssd)</small></li>
     <img class="hdd1"width="51px" height="50px" src="/static/main/images/hdd.png" ></img>
     <li class="os">Установка любой ос</li>
     <img  class="os1 " width="47px" height="49px"src="/static/main/images/os.png"/>
     <li class="os">Виртуализация KVM</li>
     <img  class="os1 " width="47px" height="49px"src="/static/main/images/vds.png"/>
     <form action="https://billing.king-host.ru">
         <button type="submit" name="buy">Купить</button>
         </form>
     <li class= "prise">600 ₽/месяц</li>
  </div>
  </div>
{% endfor %}
</code>```

models.py

```<code>class VDSTARIFS( models.Model):
    id = models.CharField(max_length=40, primary_key= True,serialize=True)
    name = models.CharField(max_length=20, verbose_name = 'Цены')
    choosen = models.CharField(max_length= 20, choices = CHOOSE, verbose_name = 'Тариф', help_text='Выбор тарифного плана.')
    title = models.CharField(max_length= 15)
    ram = models.CharField(max_length=10)
    hdd = models.CharField(max_length= 10)
    cpu = models.CharField(max_length=10)

    def __str__(self):
        return str(self.title)

</code>```

views.py

```<code>def vds(request):
    servers = VDSTARIFS.objects.all() ##Maybe filter
    context1 = {
        'allobjects': servers
    }
    return render(request,'vds.html',context1)
</code>```

答: I solved my problem, problem was because of wrong request.If someone will have this problem, solving this problem was used slices</p>

Title: how fix cycle in django?

Body:
I have problem with cycle in djano(Maybe I dont understand this).I have cycle in template and it must to output value from database,but Idk how I can create cycle,which may output value from (id = 1),because this cycle output value (id = 0) again and again.

vds.html

{% for item in allobjects %}

{{item.title}}

{{item.ram}}ГБ(озу)

{{item.cpu}} vCore

{{item.hdd}} ГБ(ssd)

Установка любой ос

Виртуализация KVM

     <form action="https://billing.king-host.ru">
         <button type="submit" name="buy">Купить</button>
         </form>

{{item.name}}₽/месяц

{{item.title}}

ГБ(озу)

2 vCore

40 ГБ(ssd)

Установка любой ос

Виртуализация KVM

     <form action="https://billing.king-host.ru">
         <button type="submit" name="buy">Купить</button>
         </form>

600 ₽/месяц

{% endfor %}

models.py

class VDSTARIFS( models.Model):
    id = models.CharField(max_length=40, primary_key= True,serialize=True)
    name = models.CharField(max_length=20, verbose_name = 'Цены')
    choosen = models.CharField(max_length= 20, choices = CHOOSE, verbose_name = 'Тариф', help_text='Выбор тарифного плана.')
    title = models.CharField(max_length= 15)
    ram = models.CharField(max_length=10)
    hdd = models.CharField(max_length= 10)
    cpu = models.CharField(max_length=10)

    def __str__(self):
        return str(self.title)

views.py

def vds(request):
    servers = VDSTARIFS.objects.all() ##Maybe filter
    context1 = {
        'allobjects': servers
    }
    return render(request,'vds.html',context1)


问:
Is the C# static constructor thread safe?
In other words, is this Singleton implementation thread safe:</p>

```<code>public class Singleton
{
    private static Singleton instance;

    private Singleton() { }

    static Singleton()
    {
        instance = new Singleton();
    }

    public static Singleton Instance
    {
        get { return instance; }
    }
}
</code>```

答:
The Common Language Infrastructure specification guarantees that "a type initializer shall run exactly once for any given type, unless explicitly called by user code." (Section 9.5.3.1.) So unless you have some whacky IL on the loose calling Singleton::.cctor directly (unlikely) your static constructor will run exactly once before the Singleton type is used, only one instance of Singleton will be created, and your Instance property is thread-safe.

Note that if Singleton's constructor accesses the Instance property (even indirectly) then the Instance property will be null. The best you can do is detect when this happens and throw an exception, by checking that instance is non-null in the property accessor. After your static constructor completes the Instance property will be non-null.

As Zoomba's answer points out you will need to make Singleton safe to access from multiple threads, or implement a locking mechanism around using the singleton instance.

ContentLicense: CC BY-SA 2.5

Body:
In other words, is this Singleton implementation thread safe:

public class Singleton
{
    private static Singleton instance;

    private Singleton() { }

    static Singleton()
    {
        instance = new Singleton();
    }

    public static Singleton Instance
    {
        get { return instance; }
    }
}

LastEditorDisplayName: Dominic Cooney


问:
How can I change the inner image position of an UIImageView?
I have defined an UIImageView in my nib. After the app launches, I display an image in that UIImageView. Maybe I am on the wrong way, but what I want to do is the following:

The image which I load into the view is bigger than the view itself. I want that it is displayed in original size with hidden overlay. Then I want to slowly move that image inside that view in random directions.

Maybe you know html div containers with background images. there, you can set a position of that background image and change that position with JavaScript. I need something similar on iPhone.

Maybe an UIImageView is not the right thing for that? Or must I set the UIImageView to the full size of that image and then move the UIImageView around slowly? Could it be bigger than the iPhone's screen?

答: You need to crop the image. See Lounges' answer to this question.</p>

OwnerDisplayName: Unknown Individual

OwnerDisplayName: Can Berk Güder


问:
How can I print an array via pointer
Our teacher gave this code and we need to get this code operational.

How can I print the values inside of array?

```<code>cout << wizardsCollection->birthYear;
</code>```

is returns what I gave but wizardsCollection->nameSurname returns empty value.

Here's the rest of the code:

```<code>struct Wizard {
    string nameSurname;
    int birthYear;
    string hairColour;
};

struct Wizard *createWizards() {
    Wizard wizardsCollection[3];

    for (int index = 0; index < *(&wizardsCollection + 1) - wizardsCollection; index = index + 1) {
        wizardsCollection[index].nameSurname = "Name and surname of " + index;
        wizardsCollection[index].birthYear = 0;
        wizardsCollection[index].hairColour = "Hair colour of " + index;
    }

    return wizardsCollection;
}

int main()
{
    Wizard *wizardsCollection = createWizards();
    cout << wizardsCollection->nameSurname;
}
</code>```

答:
You have a huge problem here. wizardsCollection is created on the stack.  As soon as the function returns, that stack memory goes away.  Your pointer will be pointing into empty space.  You need to use a std::vector for this, to manage the memory.

```<code>#include <iostream>
#include <string>
#include <vector>

struct Wizard {
    std::string nameSurname;
    int birthYear;
    std::string hairColour;
};

void createWizards(std::vector<Wizard> & wizardsCollection) {
    wizardsCollection.clear();
    for (int index = 0; index < 3; index++ ) {
        wizardsCollection.push_back(Wizard({
            "Name and surname of " + std::to_string(index),
            0,
            "Hair colour of " + std::to_string(index)
        }));
    }
}

int main()
{
    std::vector<Wizard> wizardsCollection;
    createWizards(wizardsCollection);
    std::cout << wizardsCollection[0].nameSurname << "\n";
}
</code>```

There are other ways to do it, but this models what you had.

Title: How can I print an array via pointer

Body:
Our teacher gave this code and we need to get this code operational.

How can I print the values inside of array?

cout << wizardsCollection->birthYear;

is returns what I gave but wizardsCollection->nameSurname returns empty value.

Here's the rest of the code:

struct Wizard {
    string nameSurname;
    int birthYear;
    string hairColour;
};

struct Wizard *createWizards() {
    Wizard wizardsCollection[3];

    for (int index = 0; index < *(&wizardsCollection + 1) - wizardsCollection; index = index + 1) {
        wizardsCollection[index].nameSurname = "Name and surname of " + index;
        wizardsCollection[index].birthYear = 0;
        wizardsCollection[index].hairColour = "Hair colour of " + index;
    }

    return wizardsCollection;
}

int main()
{
    Wizard *wizardsCollection = createWizards();
    cout << wizardsCollection->nameSurname;
}

Body:
You have a huge problem here. wizardsCollection is created on the stack.  As soon as the function returns, that stack memory goes away.  Your pointer will be pointing into empty space.  You need to use a std::vector for this, to manage the memory.

#include <iostream>
#include <string>
#include <vector>

struct Wizard {
    std::string nameSurname;
    int birthYear;
    std::string hairColour;
};

void createWizards(std::vector<Wizard> & wizardsCollection) {
    wizardsCollection.clear();
    for (int index = 0; index < 3; index++ ) {
        wizardsCollection.push_back(Wizard({
            "Name and surname of " + std::to_string(index),
            0,
            "Hair colour of " + std::to_string(index)
        }));
    }
}

int main()
{
    std::vector<Wizard> wizardsCollection;
    createWizards(wizardsCollection);
    std::cout << wizardsCollection[0].nameSurname << "\n";
}

There are other ways to do it, but this models what you had.


问:
Angular: Navigating to location that requires visiting login page first
There's a common UX pattern where, if a user's navigation fails because they need to re-login, the app saves the desired URL and navigates to it once the user successfully submits their credentials on a login page. My first thought on how to do this in Angular is to navigate to the login component from the CanActivate guard (on auth failure) with the intended path supplied as a query parameter (e.g. '/login/?next=somepath'), so login component can complete the originally intended navigation. Is there a better practice for  implementing this pattern, maybe by utilizing state information in the router?</p>

答:
You could use a service to store the previously visited route/url and then, on successful authentication, retrieve that url and navigate to it.

I found this code for such a service a while ago in another site:

import { Injectable } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';

@Injectable({
  providedIn: 'root',
})
export class PreviousRouteService {
  private previousUrl: string;
  private currentUrl: string;

  constructor(private router: Router) {
    // Stores the very first navigated route
    this.currentUrl = this.router.url;

    router.events.subscribe((event) => {
      if (event instanceof NavigationEnd) {
        this.previousUrl = this.currentUrl;
        this.currentUrl = event.url;
      }
    });
  }

  public getPreviousUrl() {
    return this.previousUrl;
  }
}
```

So, you inject this service where you need it (i.e. your login component) and after user successfully authenticates, you can do router.navigateByUrl(this._previousService.getPreviousUrl())

Code originally fetched from https://dev.to/slk5611/how-to-access-the-previous-route-in-your-angular-app-5db0

Body:
You could use a service to store the previously visited route/url and then, on successful authentication, retrieve that url and navigate to it.

I found this code for such a service a while ago in another site:

import { Injectable } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';

@Injectable({
  providedIn: 'root',
})
export class PreviousRouteService {
  private previousUrl: string;
  private currentUrl: string;

  constructor(private router: Router) {
    // Stores the very first navigated route
    this.currentUrl = this.router.url;

    router.events.subscribe((event) => {
      if (event instanceof NavigationEnd) {
        this.previousUrl = this.currentUrl;
        this.currentUrl = event.url;
      }
    });
  }

  public getPreviousUrl() {
    return this.previousUrl;
  }
}

So, you inject this service where you need it (i.e. your login component) and after user successfully authenticates, you can do router.navigateByUrl(this._previousService.getPreviousUrl())

Code originally fetched from https://dev.to/slk5611/how-to-access-the-previous-route-in-your-angular-app-5db0


问:
Grouping nearby shapes
I have two shapes that are near each other, one of them is selected. I need to be able to group it together with the selected shape.

Thanks for your help!

Here's the code I came with but it doesn't seem to match the nearby shape.  In particular its not finding a 20ptx20pt rectangle offset about half its with to the left and half its height to the top:

```<code>Option Explicit
Sub Test()
Dim oSl As slide
Dim oSh As Shape
Dim oSh2 As Shape

Dim MainHeight As Long
Dim MainWidth As Long

MainHeight = 48.76
MainWidth = 88.45

Set oSl = Application.ActiveWindow.View.slide
Set oSh = ActiveWindow.Selection.ShapeRange(1)

        For Each oSh2 In oSl.Shapes
            If IsWithinRangey(oSh, oSh2, 0.4) Then
                oSh2.Select (False)
            End If
        Next
''        ActiveWindow.Selection.ShapeRange.Group

End Sub

Function IsWithinRangey(oSh As Shape, oSh2 As Shape, _
    AreaTolerance As Single) As Boolean
' Is the shape within the coordinates supplied?

    Dim WidthMin As Single
    Dim WidthMax As Single
    Dim HeightMin As Single
    Dim HeightMax As Single

    With oSh

        HeightMin = oSh.Height * (1 - AreaTolerance)
        HeightMax = oSh.Height * (1 + AreaTolerance)
        WidthMin = oSh.Width * (1 - AreaTolerance)
        WidthMax = oSh.Width * (1 + AreaTolerance)

        Debug.Print "==========================="
        Debug.Print "Shp: " & .Width & " x " & .Height
        Debug.Print "Min: " & WidthMin & " x " & HeightMin
        Debug.Print "Max: " & WidthMax & " x " & HeightMax
    End With

   With oSh2

        If oSh.Id <> oSh2.Id Then
            ShapeLeft = oSh.Left - (19.85) / 1
            ShapeTop = oSh.Top - (19.85) / 1

            Debug.Print ShapeLeft
            Debug.Print ShapeTop

            If .Left >= ShapeLeft And .Left < ShapeLeft + WidthMax Then
                If .Top >= ShapeTop And .Top < ShapeTop + HeightMax Then
                    If .Width >= WidthMin And .Width <= WidthMax Then
                        If .Height > HeightMin And .Height < HeightMax Then
                            IsWithinRangey = True
                    End If
                    End If
                End If
            End If
        End If
    End With

End Function
</code>```

答:
Thanks to @JohnKorchok! Final code follows</p>
```<code>Option Explicit

Dim WidthMax As Single
Dim HeightMax As Single
Dim ShapeLeft As Single
Dim ShapeTop As Single
Dim AreaTolerance As Single
Dim StepNumberWidth As Single
Dim StepNumberHeight As Single
Dim oNewShape As Shape

Sub GroupCloseShapes()
    Dim oSl As Slide
    Dim oSh As Shape
    Dim oSh2 As Shape
    Dim MainHeight As Long
    Dim MainWidth As Long

    MainHeight = 48.76
    MainWidth = 88.45
    StepNumberWidth = 19.85
    StepNumberHeight = 19.85

    Set oSl = Application.ActiveWindow.View.Slide
    Set oSh = ActiveWindow.Selection.ShapeRange(1)

    With oSh
        HeightMax = oSh.Height * (1 + AreaTolerance)
        WidthMax = oSh.Width * (1 + AreaTolerance)
        ShapeLeft = oSh.Left - StepNumberWidth / 1
        ShapeTop = oSh.Top - StepNumberHeight / 1

    End With

    For Each oSh2 In oSl.Shapes
        If oSh.Id <> oSh2.Id Then
            If IsWithinRangey(oSh, oSh2, 0.4) Then
                oSh2.Select (False)
            End If
        End If
    Next
'' ActiveWindow.Selection.ShapeRange.Group
End Sub

Function IsWithinRangey(oSh As Shape, oSh2 As Shape, AreaTolerance As Single) As Boolean ' Is the shape within the coordinates supplied?
    With oSh2
        If .Left >= ShapeLeft And .Left <= ShapeLeft + WidthMax Then
            If .Top >= ShapeTop And .Top <= ShapeTop + HeightMax Then
                If .Width <= WidthMax Then
                    If .Height <= HeightMax Then
                        IsWithinRangey = True
                    End If
                End If
            End If
        End If
    End With
End Function
</code>```

Title: Grouping nearby shapes

Body:
I have two shapes that are near each other, one of them is selected. I need to be able to group it together with the selected shape.

Thanks for your help!

Here's the code I came with but it doesn't seem to match the nearby shape.  In particular its not finding a 20ptx20pt rectangle offset about half its with to the left and half its height to the top:

Option Explicit
Sub Test()
Dim oSl As slide
Dim oSh As Shape
Dim oSh2 As Shape

Dim MainHeight As Long
Dim MainWidth As Long

MainHeight = 48.76
MainWidth = 88.45

Set oSl = Application.ActiveWindow.View.slide
Set oSh = ActiveWindow.Selection.ShapeRange(1)

        For Each oSh2 In oSl.Shapes
            If IsWithinRangey(oSh, oSh2, 0.4) Then
                oSh2.Select (False)
            End If
        Next
''        ActiveWindow.Selection.ShapeRange.Group

End Sub

Function IsWithinRangey(oSh As Shape, oSh2 As Shape, _
    AreaTolerance As Single) As Boolean
' Is the shape within the coordinates supplied?

    Dim WidthMin As Single
    Dim WidthMax As Single
    Dim HeightMin As Single
    Dim HeightMax As Single

    With oSh

        HeightMin = oSh.Height * (1 - AreaTolerance)
        HeightMax = oSh.Height * (1 + AreaTolerance)
        WidthMin = oSh.Width * (1 - AreaTolerance)
        WidthMax = oSh.Width * (1 + AreaTolerance)

        Debug.Print "==========================="
        Debug.Print "Shp: " & .Width & " x " & .Height
        Debug.Print "Min: " & WidthMin & " x " & HeightMin
        Debug.Print "Max: " & WidthMax & " x " & HeightMax
    End With

   With oSh2

        If oSh.Id <> oSh2.Id Then
            ShapeLeft = oSh.Left - (19.85) / 1
            ShapeTop = oSh.Top - (19.85) / 1

            Debug.Print ShapeLeft
            Debug.Print ShapeTop

            If .Left >= ShapeLeft And .Left < ShapeLeft + WidthMax Then
                If .Top >= ShapeTop And .Top < ShapeTop + HeightMax Then
                    If .Width >= WidthMin And .Width <= WidthMax Then
                        If .Height > HeightMin And .Height < HeightMax Then
                            IsWithinRangey = True
                    End If
                    End If
                End If
            End If
        End If
    End With

End Function

Body:
Thanks to @JohnKorchok! Final code follows

Option Explicit

Dim WidthMax As Single
Dim HeightMax As Single
Dim ShapeLeft As Single
Dim ShapeTop As Single
Dim AreaTolerance As Single
Dim StepNumberWidth As Single
Dim StepNumberHeight As Single
Dim oNewShape As Shape

Sub GroupCloseShapes()
    Dim oSl As Slide
    Dim oSh As Shape
    Dim oSh2 As Shape
    Dim MainHeight As Long
    Dim MainWidth As Long

    MainHeight = 48.76
    MainWidth = 88.45
    StepNumberWidth = 19.85
    StepNumberHeight = 19.85

    Set oSl = Application.ActiveWindow.View.Slide
    Set oSh = ActiveWindow.Selection.ShapeRange(1)

    With oSh
        HeightMax = oSh.Height * (1 + AreaTolerance)
        WidthMax = oSh.Width * (1 + AreaTolerance)
        ShapeLeft = oSh.Left - StepNumberWidth / 1
        ShapeTop = oSh.Top - StepNumberHeight / 1

    End With

    For Each oSh2 In oSl.Shapes
        If oSh.Id <> oSh2.Id Then
            If IsWithinRangey(oSh, oSh2, 0.4) Then
                oSh2.Select (False)
            End If
        End If
    Next
'' ActiveWindow.Selection.ShapeRange.Group
End Sub

Function IsWithinRangey(oSh As Shape, oSh2 As Shape, AreaTolerance As Single) As Boolean ' Is the shape within the coordinates supplied?
    With oSh2
        If .Left >= ShapeLeft And .Left <= ShapeLeft + WidthMax Then
            If .Top >= ShapeTop And .Top <= ShapeTop + HeightMax Then
                If .Width <= WidthMax Then
                    If .Height <= HeightMax Then
                        IsWithinRangey = True
                    End If
                End If
            End If
        End If
    End With
End Function


问:
Pyspark Cumulative sum within Partition for moving last 2 (N) rows
Let's say I have the following dataframe which is sorted for ease visually:

How would I utilize window functions to create a new column that sums the previous row ordered by Month column within each period partition:

The following is my attempt at it, but I'm obviously doing something wrong with respect to the rowsBetween function.

```<code>df = df.withColumn('CustLast2', sum('Cust').over(Window.partitionBy("period").orderBy('Month').rowsBetween(Window.currentRow, -1))
</code>```

答:
I think you're almost their, you just have to replace -1 by Window.unboundedPreceding

```<code>df = df.withColumn('CustLast2', sum('Cust').over(Window.partitionBy("period").orderBy('Month').rowsBetween(Window.unboundedPreceding, Window.currentRow))
</code>```

Otherwise you're just doing the sum on 2 consecutive rows within the same period.

Body:
Let's say I have the following dataframe which is sorted for ease visually:

How would I utilize window functions to create a new column that sums the previous row ordered by Month column within each period partition:

The following is my attempt at it, but I'm obviously doing something wrong with respect to the rowsBetween function.

df = df.withColumn('CustLast2', sum('Cust').over(Window.partitionBy("period").orderBy('Month').rowsBetween(Window.currentRow, -1))

Body:
I think you're almost their, you just have to replace -1 by Window.unboundedPreceding

df = df.withColumn('CustLast2', sum('Cust').over(Window.partitionBy("period").orderBy('Month').rowsBetween(Window.unboundedPreceding, Window.currentRow))

Otherwise you're just doing the sum on 2 consecutive rows within the same period.


问:
Why can't I vectorize Python's datetime.utcfromtimestamp()?
I have an array of Unix timestamps.  I can run datetime.utcfromtimestamp on each entry individually, but I cannot run them all from a numpy array.  Why does that happen?

MWE

import numpy as np
from datetime import datetime

times = np.array((1524967210, 1524967211, 1524967212))

# Works
for i in times:
    print(datetime.utcfromtimestamp(times[i]))

# Does not work
print(datetime.utcfromtimestamp(times[:]))
```

The second example issues: TypeError: only integer scalar arrays can be converted to a scalar index rather than an array of times.  A Unix timestamp conversion seems straightforward to implement as a vectorized operation (see source code here), so why does it not work here?  Is there something I can do to alter this which will enable vectorized operation?

答:
You can use .astype('datetime64[s]'), then .tolist() to achieve the same result (a list of Python datetime objects, naive but representing UTC). A little %timeit comparison:

```<code>import numpy as np
from datetime import datetime
func = np.vectorize(datetime.utcfromtimestamp)

N = 1000000
times = np.linspace(1524967210, 1524967210+N, N)

%timeit times.astype('datetime64[s]')
809 µs ± 26.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit times.astype('datetime64[s]').tolist()
56.4 ms ± 57.7 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit func(times)
174 ms ± 2.06 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit [datetime.utcfromtimestamp(t) for t in times]
311 ms ± 2.15 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
</code>```

Body:
I have an array of Unix timestamps.  I can run datetime.utcfromtimestamp on each entry individually, but I cannot run them all from a numpy array.  Why does that happen?

MWE

import numpy as np
from datetime import datetime

times = np.array((1524967210, 1524967211, 1524967212))

# Works
for i in times:
    print(datetime.utcfromtimestamp(times[i]))

# Does not work
print(datetime.utcfromtimestamp(times[:]))

The second example issues: TypeError: only integer scalar arrays can be converted to a scalar index rather than an array of times.  A Unix timestamp conversion seems straightforward to implement as a vectorized operation (see source code here), so why does it not work here?  Is there something I can do to alter this which will enable vectorized operation?

Body:
You can use .astype('datetime64[s]'), then .tolist() to achieve the same result (a list of Python datetime objects, naive but representing UTC). A little %timeit comparison:

import numpy as np
from datetime import datetime
func = np.vectorize(datetime.utcfromtimestamp)

N = 1000000
times = np.linspace(1524967210, 1524967210+N, N)

%timeit times.astype('datetime64[s]')
809 µs ± 26.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit times.astype('datetime64[s]').tolist()
56.4 ms ± 57.7 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit func(times)
174 ms ± 2.06 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit [datetime.utcfromtimestamp(t) for t in times]
311 ms ± 2.15 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)


问:
Qt application dependent on windows service
My Qt application is dependent on windows bonjour service. If the application is launched at login, it sometimes is not able to register with bonjour probably as the service is not yet up completely. I need to restart the service manually to make it work. Is there a way to specify the dependent services of my application which can take care of this or may be I just check the status of the service and wait till it's up.

Any pointer is appreciated.

Soumya

答: You can check with QueryServiceStatus. If you need to start it, you can then wait with NotifyServiceStatusChange until the service has started.

ContentLicense: CC BY-SA 3.0


问:
Unable to use any windows drives in WSL
I was tiring to access files inside /mnt in WSL(Ubuntu). But when I typed ls ./d it gave the following error:

```<code>ls: cannot open directory '.': Input/output error
</code>```

This is happening while using any command in any file of the windows drives, I also typed cd ./d/<any-folder> and it gave the following:

```<code>cd: Input/output error: <folder-name>
</code>```

答: As pointed here, just go to the PowerShell and run the command wsl.exe --shutdown and restart the WSL.

Title: Unable to use any windows drives in WSL

Body:
I was tiring to access files inside /mnt in WSL(Ubuntu). But when I typed ls ./d it gave the following error:

ls: cannot open directory '.': Input/output error

This is happening while using any command in any file of the windows drives, I also typed cd ./d/<any-folder> and it gave the following:

cd: Input/output error: <folder-name>


问:
Default values of a prop of type object in vue are not being used
I'm not sure why the default values of a prop, in object format, in vue are not being accepted but when I pass in the props dynamically the values appear fine.

I have a component, component1, it has:

```<code><label :style="setTextStyles"></label>

props: {
    textStyles: {
      type: Object,
      default: () => ({
        'textColor': 'white',
        'uppercase': 'uppercase',
        'fontWeight': 'bold',
      })
    }
},
computed:{
    setTextStyles() {
      return {
        'font-weight': this.textStyles.fontWeight,
        'text-transform': this.textStyles.uppercase,
        '--color': this.textStyles.textColor
      }
}
</code>```

I have a second component that uses component 1:

```<code><component1 :textStyles="{'textColor':'red', 'uppercase':'None','fontWeight':'bold'}"/>
</code>```

Which ever prop I specify, ie textColor, or upprecase or fontWeight, I see the expected result. However the default values don't seem to show up if I don't specify it. For example, the fontWeight is not bold by default even though it's set as the default font weight. This is the same with textColor.

Below does not give me a bold font:

```<code><component1 :textStyles="{'textColor':'red', 'uppercase':'None'}"/>
</code>```

Below does not give me a white text color:

```<code><component1 :textStyles="{'uppercase':'None','fontWeight':'bold'}"/>
</code>```

I'm not sure why the default values are not appearing

答:
Do not expect vue props to act like function arguments in javascript. Instead you can have the default values in a separate variable inside the component and use Object.assign() to build the final desired object.

For example:

```<code>const defaultStyles = {
        'textColor': 'white',
        'uppercase': 'uppercase',
        'fontWeight': 'bold',
      }

export default {
  props : {
    textStyles : {
       default : {},
       type : Object
    }
  },

  data(){
    return {
       finalStyles : Object.assign({}, defaultStyles, textStyles)
    }
  }
}
</code>```

Body:
I'm not sure why the default values of a prop, in object format, in vue are not being accepted but when I pass in the props dynamically the values appear fine.

I have a component, component1, it has:

props: {
    textStyles: {
      type: Object,
      default: () => ({
        'textColor': 'white',
        'uppercase': 'uppercase',
        'fontWeight': 'bold',
      })
    }
},
computed:{
    setTextStyles() {
      return {
        'font-weight': this.textStyles.fontWeight,
        'text-transform': this.textStyles.uppercase,
        '--color': this.textStyles.textColor
      }
}

I have a second component that uses component 1:

<component1 :textStyles="{'textColor':'red', 'uppercase':'None','fontWeight':'bold'}"/>

Which ever prop I specify, ie textColor, or upprecase or fontWeight, I see the expected result. However the default values don't seem to show up if I don't specify it. For example, the fontWeight is not bold by default even though it's set as the default font weight. This is the same with textColor.

Below does not give me a bold font:

<component1 :textStyles="{'textColor':'red', 'uppercase':'None'}"/>

Below does not give me a white text color:

<component1 :textStyles="{'uppercase':'None','fontWeight':'bold'}"/>

I'm not sure why the default values are not appearing

Body:
Do not expect vue props to act like function arguments in javascript. Instead you can have the default values in a separate variable inside the component and use Object.assign() to build the final desired object.

For example:

const defaultStyles = {
        'textColor': 'white',
        'uppercase': 'uppercase',
        'fontWeight': 'bold',
      }

export default {
  props : {
    textStyles : {
       default : {},
       type : Object
    }
  },

  data(){
    return {
       finalStyles : Object.assign({}, defaultStyles, textStyles)
    }
  }
}


问:
Pass jq output to curl
I want to be use a number of values from jq piped to curl. I have json data with a structure that looks something like this

```<code>{
  "apps": {
    "code": "200",
    "name": "app1",
  },
  "result": "1"
}
{
  "apps": {
    "code": "200",
    "name": "app2",
  },
  "result": "5"
}
...
...
...

</code>```

What I want to do is to take the values of every apps.name and result and pass that to curl:

```<code>curl -XPOST http://localhost --data-raw 'app=$appsName result=$result'
</code>```

The curl command will then run X amount of times depending on how many objects there are.
In jq I came up with this but I don't know how or the best way of passing this to curl in a loop.

```<code>jq -r '.result as $result | .apps as $apps | $apps.name + " " + $result myfile.json
</code>```

答:
jq -r '"\( .apps.name ) \( .result )"' |
while read -r app result; do
   curl -XPOST http://localhost --data-raw "app=$app result=$result"
done
```
<p>or</p>
<pre class="lang-sh prettyprint-override"><code>jq -r '"app=\( .apps.name ) result=\( .result )"' |
while read -r data; do
   curl -XPOST http://localhost --data-raw "$data"
done
</code>```

The first one assumes the name can't contain whitespace.

Title: Pass jq output to curl

Body:
I want to be use a number of values from jq piped to curl. I have json data with a structure that looks something like this

{
  "apps": {
    "code": "200",
    "name": "app1",
  },
  "result": "1"
}
{
  "apps": {
    "code": "200",
    "name": "app2",
  },
  "result": "5"
}
...
...
...

What I want to do is to take the values of every apps.name and result and pass that to curl:

curl -XPOST http://localhost --data-raw 'app=$appsName result=$result'

The curl command will then run X amount of times depending on how many objects there are.
In jq I came up with this but I don't know how or the best way of passing this to curl in a loop.

jq -r '.result as $result | .apps as $apps | $apps.name + " " + $result myfile.json

Body:
jq -r '"\( .apps.name ) \( .result )"' |
while read -r app result; do
   curl -XPOST http://localhost --data-raw "app=$app result=$result"
done

or

jq -r '"app=\( .apps.name ) result=\( .result )"' |
while read -r data; do
   curl -XPOST http://localhost --data-raw "$data"
done

The first one assumes the name can't contain whitespace.


问:
Puppet: Could not find resource 'File[/etc/auditbeat/auditbeat.yml]' in parameter 'require'
I'm using Puppet to replace Spacewalk Configuration Channels.
I'm very new to puppet, and the class I'm writing should copy some files to the host system.
I have this in my class:

```<code>class main_configurations {
  file { '/etc/auditbeat':
    ensure  => directory,
    path    => '/etc/auditbeat',
    require => File['/etc/auditbeat/auditbeat.yml'],
    source  => 'puppet:///modules/main_configurations/auditbeat/auditbeat.yml',
    recurse => true,
  }
}
</code>```

But when I run puppet agent -t I get the following error:

```<code>Error: Could not retrieve catalog from remote server: Error 500 on SERVER: Server Error: Could not find resource 'File[/etc/auditbeat/auditbeat.yml]' in parameter 'require' (file: /etc/puppetlabs/code/environments/production/modules/main_configurations/manifests/init.pp, line: 8) on node <servername>
</code>```

For completeness, this is the folder structure on my puppet server:

```<code>/etc/puppetlabs/code/environments/production/modules/main_configurations/files/auditbeat
/etc/puppetlabs/code/environments/production/modules/main_configurations/files/auditbeat/auditbeat.yml
/etc/puppetlabs/code/environments/production/modules/main_configurations/files/auditbeat/audit.rules.d
/etc/puppetlabs/code/environments/production/modules/main_configurations/files/auditbeat/audit.rules.d/auditbeat-rules.conf
</code>```

答:
But when I run puppet agent -t I get the following error:

Error: Could not retrieve catalog from remote server: Error 500 on
SERVER: Server Error: Could not find resource
'File[/etc/auditbeat/auditbeat.yml]' in parameter 'require' (file:
/etc/puppetlabs/code/environments/production/modules/main_configurations/manifests/init.pp,
line: 8) on node

As @MattSchuchard explained in comments, that means exactly what it says: you have a require parameter that refers to resource File[/etc/auditbeat/auditbeat.yml], but that (Puppet) resource is not declared in any of the manifest files that were processed.  This constitutes an inconsistency in your manifest set. It has nothing to do with which files are available for installation from your module or which are already present on the target, nor about what Puppet might do when given a manifest set free of such inconsistencies.

Considering the declaration that is presented:

```<code>  file { '/etc/auditbeat':
    ensure  => directory,
    path    => '/etc/auditbeat',
    require => File['/etc/auditbeat/auditbeat.yml'],
    source  => 'puppet:///modules/main_configurations/auditbeat/auditbeat.yml',
    recurse => true,
  }
</code>```

I'm inclined to think that you misunderstand at least what the require metaparameter means.  It is one of several that speak to the relative order in which various resources are applied.  It says that application of the resource being declared requires the specified other resources to have successfully been applied before.  That's surely not what you intend here.

Moreover, a resource reference such as you are assigning to that parameter does not serve as a resource declaration. It does not contain enough information to do so.  As the name suggests, it is a reference to a resource declared elsewhere.

It looks like you are trying to manage a subdirectory tree rooted at /etc/auditbeat to match a tree in your module.  In that case, you probably want something more like this:

```<code>  file { '/etc/auditbeat':
    # no path required if it is already given by the resource title
    ensure  => 'directory',
    source  => 'puppet:///modules/main_configurations/auditbeat',
    recurse => true,
  }
</code>```

Mainly, that drops the require parameter.

Note that that combination will also enable purging for the destination subtree, so that unmanaged non-directories anywhere within are removed.  If you don't want that then use recurse => 'remote' instead.

There is a variety of other attributes that you might want to add, mostly to do with ownership and mode for the installed files.  If you just want to copy some or all of that from the files on the server then you will want to add source_permissions => 'use'.  Alternatively, there are attributes for explicitly specifying ownership and mode in your manifest.

Body:
I'm using Puppet to replace Spacewalk Configuration Channels.
I'm very new to puppet, and the class I'm writing should copy some files to the host system.
I have this in my class:

class main_configurations {
  file { '/etc/auditbeat':
    ensure  => directory,
    path    => '/etc/auditbeat',
    require => File['/etc/auditbeat/auditbeat.yml'],
    source  => 'puppet:///modules/main_configurations/auditbeat/auditbeat.yml',
    recurse => true,
  }
}

But when I run puppet agent -t I get the following error:

Error: Could not retrieve catalog from remote server: Error 500 on SERVER: Server Error: Could not find resource 'File[/etc/auditbeat/auditbeat.yml]' in parameter 'require' (file: /etc/puppetlabs/code/environments/production/modules/main_configurations/manifests/init.pp, line: 8) on node <servername>

For completeness, this is the folder structure on my puppet server:

/etc/puppetlabs/code/environments/production/modules/main_configurations/files/auditbeat
/etc/puppetlabs/code/environments/production/modules/main_configurations/files/auditbeat/auditbeat.yml
/etc/puppetlabs/code/environments/production/modules/main_configurations/files/auditbeat/audit.rules.d
/etc/puppetlabs/code/environments/production/modules/main_configurations/files/auditbeat/audit.rules.d/auditbeat-rules.conf

Body:
But when I run puppet agent -t I get the following error:

Error: Could not retrieve catalog from remote server: Error 500 on
SERVER: Server Error: Could not find resource
'File[/etc/auditbeat/auditbeat.yml]' in parameter 'require' (file:
/etc/puppetlabs/code/environments/production/modules/main_configurations/manifests/init.pp,
line: 8) on node

As @MattSchuchard explained in comments, that means exactly what it says: you have a require parameter that refers to resource File[/etc/auditbeat/auditbeat.yml], but that (Puppet) resource is not declared in any of the manifest files that were processed.  This constitutes an inconsistency in your manifest set. It has nothing to do with which files are available for installation from your module or which are already present on the target, nor about what Puppet might do when given a manifest set free of such inconsistencies.

Considering the declaration that is presented:

  file { '/etc/auditbeat':
    ensure  => directory,
    path    => '/etc/auditbeat',
    require => File['/etc/auditbeat/auditbeat.yml'],
    source  => 'puppet:///modules/main_configurations/auditbeat/auditbeat.yml',
    recurse => true,
  }

I'm inclined to think that you misunderstand at least what the require metaparameter means.  It is one of several that speak to the relative order in which various resources are applied.  It says that application of the resource being declared requires the specified other resources to have successfully been applied before.  That's surely not what you intend here.

Moreover, a resource reference such as you are assigning to that parameter does not serve as a resource declaration. It does not contain enough information to do so.  As the name suggests, it is a reference to a resource declared elsewhere.

It looks like you are trying to manage a subdirectory tree rooted at /etc/auditbeat to match a tree in your module.  In that case, you probably want something more like this:

  file { '/etc/auditbeat':
    # no path required if it is already given by the resource title
    ensure  => 'directory',
    source  => 'puppet:///modules/main_configurations/auditbeat',
    recurse => true,
  }

Mainly, that drops the require parameter.

Note that that combination will also enable purging for the destination subtree, so that unmanaged non-directories anywhere within are removed.  If you don't want that then use recurse => 'remote' instead.

There is a variety of other attributes that you might want to add, mostly to do with ownership and mode for the installed files.  If you just want to copy some or all of that from the files on the server then you will want to add source_permissions => 'use'.  Alternatively, there are attributes for explicitly specifying ownership and mode in your manifest.


问:
Selecting first non null value in a model
Let's say I have a model class that looks like this:

```<code>   public class ModelTest {
        public string val1 {get;set;}
        public string val2 {get;set;}
        public string val3 {get;set;}
   }
</code>```

Somewhere in my code this ModelTest gets its data. The caveat is that, only 1 of them will hold a value

```<code>   var model = new ModelTest() {val1=null, val2="value", val3=null} //Sudo code
</code>```

What I am trying to do somehow, is compare a value to whichever 1 of the 3 items can potentially have a values, so something like:

```<code>     var testCompare = "someValue"

     if (testCompare == model. ....//how can I get the NOT NULL value from ModelTest here for comparison
</code>```

答:
It's a very bizarre use case, but let's go with it. Here's another option for the bonfire..

```<code>public class ModelTest {
    private string _val;
    public string val1 {get => _val; set => _val ??= value;}
    public string val2 {get => _val; set => _val ??= value;}
    public string val3 {get => _val; set => _val ??= value;}
}
</code>```

Whichever one of these is set to non null ends up committing that value to _val - ??= writes the right hand into the left hand only if the left hand is null, essentially like left = left ?? right.

It doesn't matter which you use to access the value..

Note that there is only one data storage location so this approach is incapable of remembering two values, or which value was the non null. You wouldn't use this for disparate properties like name, address and social security number because it could lead to bizarre effects elsewhere. This is for a very narrow use case of "there are three properties that are essentially the same thing, they cannot be collapsed to one, and I don't know which one will be set but i can treat them equivalent for reading"

Body:
Let's say I have a model class that looks like this:

   public class ModelTest {
        public string val1 {get;set;}
        public string val2 {get;set;}
        public string val3 {get;set;}
   }

Somewhere in my code this ModelTest gets its data. The caveat is that, only 1 of them will hold a value

   var model = new ModelTest() {val1=null, val2="value", val3=null} //Sudo code

What I am trying to do somehow, is compare a value to whichever 1 of the 3 items can potentially have a values, so something like:

     var testCompare = "someValue"

     if (testCompare == model. ....//how can I get the NOT NULL value from ModelTest here for comparison

Body:
It's a very bizarre use case, but let's go with it. Here's another option for the bonfire..

public class ModelTest {
    private string _val;
    public string val1 {get => _val; set => _val ??= value;}
    public string val2 {get => _val; set => _val ??= value;}
    public string val3 {get => _val; set => _val ??= value;}
}

Whichever one of these is set to non null ends up committing that value to _val - ??= writes the right hand into the left hand only if the left hand is null, essentially like left = left ?? right.

It doesn't matter which you use to access the value..

Note that there is only one data storage location so this approach is incapable of remembering two values, or which value was the non null. You wouldn't use this for disparate properties like name, address and social security number because it could lead to bizarre effects elsewhere. This is for a very narrow use case of "there are three properties that are essentially the same thing, they cannot be collapsed to one, and I don't know which one will be set but i can treat them equivalent for reading"


问:
Optional MatDatePicker on MatInput
Since my text and date inputs on an Angular form (built with *ngFor) have all the same styling (except for the type of input, of course), I want to combine them to make them easier to maintain. So I have done the following:

```<code><div *ngFor="let form of source">
  <div [ngSwitch]="form.type">
    <mat-form-field *ngSwitchDefault>
      <mat-label>{{form.displayName}}</mat-label>
      <ng-container [ngSwitch]="form.format">
        <input *ngSwitchDefault matInput formControlName="{{form.displayName}}" otherAttributes
               [attr.matDatepicker]="form.type === 'date' ? 'picker' : null">
      </ng-container>
      <mat-datepicker-toggle *ngIf="form.type === 'date'" matSuffix [for]="picker"></mat-datepicker-toggle>
      <mat-datepicker #picker></mat-datepicker>
    </mat-form-field>
  </div>
</div>
</code>```

I originally tried this without the attr. on the matDatepicker in the input, but then the compiler complains that Type 'string | null' is not assignable to type 'MatDatepickerPanel<MatDatepickerControl<any>, any, any>'. Using attribute binding is supposed to drop the attribute altogether when it evaluates to null or undefined, but when I do it this way, it compiles fine but the browser fails with Attempted to open an [sic] MatDatepicker with no associated input when I click the datepicker toggle, so it would seem it fails to set the attribute in either case. I get this result whether I have quotes around picker in the expression or not, since the rules for attribute binding specify that it should evaluate to a string.

Does this mean that attribute binding won't work for this situation? What else might I be doing wrong here? Is there some other trick I can use to base the text and date inputs on the same definition, or am I going to have to write and maintain almost identical definitions for these two controls?

Edit: Oh, and if I don't make it optional, then it forces all my non-date inputs to only take date inputs.

答:
Does this mean that attribute binding won't work for this situation?

I am sorry to say that, but: Yes, this won´t work.

That is because you apply a value to an attribute but you don´t actually create the directive. (Compare: Apply a directive conditionally)

So unfortunatly you can´t use a single input for what you want to achieve. At least you only need a single mat-form-field. (Small hint: The closing tag is missing)

Title: Optional MatDatePicker on MatInput

Body:
Since my text and date inputs on an Angular form (built with *ngFor) have all the same styling (except for the type of input, of course), I want to combine them to make them easier to maintain. So I have done the following:

    <mat-form-field *ngSwitchDefault>
      <mat-label>{{form.displayName}}</mat-label>
      <ng-container [ngSwitch]="form.format">
        <input *ngSwitchDefault matInput formControlName="{{form.displayName}}" otherAttributes
               [attr.matDatepicker]="form.type === 'date' ? 'picker' : null">
      </ng-container>
      <mat-datepicker-toggle *ngIf="form.type === 'date'" matSuffix [for]="picker"></mat-datepicker-toggle>
      <mat-datepicker #picker></mat-datepicker>
    </mat-form-field>

I originally tried this without the attr. on the matDatepicker in the input, but then the compiler complains that Type 'string | null' is not assignable to type 'MatDatepickerPanel<MatDatepickerControl<any>, any, any>'. Using attribute binding is supposed to drop the attribute altogether when it evaluates to null or undefined, but when I do it this way, it compiles fine but the browser fails with Attempted to open an [sic] MatDatepicker with no associated input when I click the datepicker toggle, so it would seem it fails to set the attribute in either case. I get this result whether I have quotes around picker in the expression or not, since the rules for attribute binding specify that it should evaluate to a string.

Does this mean that attribute binding won't work for this situation? What else might I be doing wrong here? Is there some other trick I can use to base the text and date inputs on the same definition, or am I going to have to write and maintain almost identical definitions for these two controls?

Edit: Oh, and if I don't make it optional, then it forces all my non-date inputs to only take date inputs.


问:
Create an array of objects from another array grouping duplicates in Javascript
I need to re-organize an array of objects (from a database) into different groups according to one of the attributes of objects. To make it clearer, let's take the following example:

The ORM (Sequelize) returns the following array object:

```<code>[
  {
    id: 182,
    employeeId: 'a',
    skillId: 207,
    score: 3,
  },
  {
    id: 512,
    employeeId: 'a',
    skillId: 212,
    score: 4,
  },
  {
    id: 908,
    employeeId: 'b',
    skillId: 134,
    score: 2,
  },
  {
    id: 876,
    employeeId: 'c',
    skillId: 212,
    score: 3,
  },
]
</code>```

I need to re-categorize the object grouping the entries by employeeId. Like this:

```<code>[
  {
    employeeId: 'a',
    skills:
           [
             { skillId: 203, score: 3},
             { skillId: 212, score: 4}
           ]
  },
  {
    employeeId: 'b',
    skills:
           [
             { skillId: 134, score: 2}
           ]
   },
   {
    employeeId: 'c',
    skills:
           [
             { skillId: 212, score: 3}
           ]
   }
]
</code>```

It didn't look hard at first but I'm hitting a roadblock, I already tried using reduce, forEarch and map but I only got to make an array of employeeIds, can't really get to include the skills array in each object of the array.

Any help would be appreciated.

答:
const result = [
  {
    id: 182,
    employeeId: 'a',
    skillId: 207,
    score: 3,
  },
  {
    id: 512,
    employeeId: 'a',
    skillId: 212,
    score: 4,
  },
  {
    id: 908,
    employeeId: 'b',
    skillId: 134,
    score: 2,
  },
  {
    id: 876,
    employeeId: 'c',
    skillId: 212,
    score: 3,
  },
]

const tempObj = result.reduce((acc, curr) => {
    if (curr.employeeId in acc) {
        acc[curr.employeeId].push({
            skillId: curr.skillId,
            score: curr.score
        })
    } else {
        acc[curr.employeeId] = [{
            skillId: curr.skillId,
            score: curr.score
        }]
    }
    return acc
}, {})

const reorganized = Object.keys(tempObj).map(key => ({
    employeeId: key,
    skills: tempObj[key]
}))

console.log(JSON.stringify(reorganized, null, 2))```

Body:
I need to re-organize an array of objects (from a database) into different groups according to one of the attributes of objects. To make it clearer, let's take the following example:

The ORM (Sequelize) returns the following array object:

[
  {
    id: 182,
    employeeId: 'a',
    skillId: 207,
    score: 3,
  },
  {
    id: 512,
    employeeId: 'a',
    skillId: 212,
    score: 4,
  },
  {
    id: 908,
    employeeId: 'b',
    skillId: 134,
    score: 2,
  },
  {
    id: 876,
    employeeId: 'c',
    skillId: 212,
    score: 3,
  },
]

I need to re-categorize the object grouping the entries by employeeId. Like this:

[
  {
    employeeId: 'a',
    skills:
           [
             { skillId: 203, score: 3},
             { skillId: 212, score: 4}
           ]
  },
  {
    employeeId: 'b',
    skills:
           [
             { skillId: 134, score: 2}
           ]
   },
   {
    employeeId: 'c',
    skills:
           [
             { skillId: 212, score: 3}
           ]
   }
]

It didn't look hard at first but I'm hitting a roadblock, I already tried using reduce, forEarch and map but I only got to make an array of employeeIds, can't really get to include the skills array in each object of the array.

Any help would be appreciated.


问:
Wal-e: unable to to push backups - permission error
We get the following error when we try to push backup using wal-e:

```<code>2020-07-16T21:18:55Z <Greenlet at 0x7f2a59fadc48: <wal_e.worker.upload.PartitionUploader object at 0x7f2a59f96cc0>([ExtendedTarInfo(submitted_path='/var/lib/postgres)> failed with PermissionError

wal_e.operator.backup WARNING  MSG: blocking on sending WAL segments
  DETAIL: The backup was not completed successfully, but we have to wait anyway.  See README: TODO about pg_cancel_backup
  STRUCTURED: time=2020-07-16T21:18:55.651073-00 pid=19697
wal_e.main   CRITICAL MSG: An unprocessed exception has avoided all error handling
  DETAIL: Traceback (most recent call last):
    File "/var/lib/postgresql/virtualenvs/wal-e/lib/python3.5/site-packages/wal_e/operator/backup.py", line 197, in database_backup
      **kwargs)
    File "/var/lib/postgresql/virtualenvs/wal-e/lib/python3.5/site-packages/wal_e/operator/backup.py", line 500, in _upload_pg_cluster_dir
      pool.put(tpart)
    File "/var/lib/postgresql/virtualenvs/wal-e/lib/python3.5/site-packages/wal_e/worker/upload_pool.py", line 108, in put
      self._wait()
    File "/var/lib/postgresql/virtualenvs/wal-e/lib/python3.5/site-packages/wal_e/worker/upload_pool.py", line 65, in _wait
      raise val
    File "src/gevent/greenlet.py", line 766, in gevent._greenlet.Greenlet.run
    File "/var/lib/postgresql/virtualenvs/wal-e/lib/python3.5/site-packages/wal_e/worker/upload.py", line 96, in __call__
      gpg_key=self.gpg_key) as pl:
    File "/var/lib/postgresql/virtualenvs/wal-e/lib/python3.5/site-packages/wal_e/pipeline.py", line 92, in __enter__
      self.stdin = pipebuf.NonBlockBufferedWriter(stdin)
    File "/var/lib/postgresql/virtualenvs/wal-e/lib/python3.5/site-packages/wal_e/pipebuf.py", line 225, in __init__
      _setup_fd(self._fd)
    File "/var/lib/postgresql/virtualenvs/wal-e/lib/python3.5/site-packages/wal_e/pipebuf.py", line 62, in _setup_fd
      set_buf_size(fd)
    File "/var/lib/postgresql/virtualenvs/wal-e/lib/python3.5/site-packages/wal_e/pipebuf.py", line 53, in set_buf_size
      fcntl.fcntl(fd, fcntl.F_SETPIPE_SZ, OS_PIPE_SZ)
  PermissionError: [Errno 1] Operation not permitted
</code>```

It's not clear why fcntl call may lead to PermissionError.

PostgreSQL version: 9.6, Python: 3.5, Wal-e : 1.1.1 (tried also 1.0.3 and 1.1.0).

It was working previously and stopped working at some point (without any noticeable changes).

答:
Well, I'm late to the game.  See https://github.com/wal-e/wal-e/issues/270

I've worked around it by patching wal-e to not set this.

Body:
We get the following error when we try to push backup using wal-e:

2020-07-16T21:18:55Z <Greenlet at 0x7f2a59fadc48: <wal_e.worker.upload.PartitionUploader object at 0x7f2a59f96cc0>([ExtendedTarInfo(submitted_path='/var/lib/postgres)> failed with PermissionError

wal_e.operator.backup WARNING  MSG: blocking on sending WAL segments
  DETAIL: The backup was not completed successfully, but we have to wait anyway.  See README: TODO about pg_cancel_backup
  STRUCTURED: time=2020-07-16T21:18:55.651073-00 pid=19697
wal_e.main   CRITICAL MSG: An unprocessed exception has avoided all error handling
  DETAIL: Traceback (most recent call last):
    File "/var/lib/postgresql/virtualenvs/wal-e/lib/python3.5/site-packages/wal_e/operator/backup.py", line 197, in database_backup
      **kwargs)
    File "/var/lib/postgresql/virtualenvs/wal-e/lib/python3.5/site-packages/wal_e/operator/backup.py", line 500, in _upload_pg_cluster_dir
      pool.put(tpart)
    File "/var/lib/postgresql/virtualenvs/wal-e/lib/python3.5/site-packages/wal_e/worker/upload_pool.py", line 108, in put
      self._wait()
    File "/var/lib/postgresql/virtualenvs/wal-e/lib/python3.5/site-packages/wal_e/worker/upload_pool.py", line 65, in _wait
      raise val
    File "src/gevent/greenlet.py", line 766, in gevent._greenlet.Greenlet.run
    File "/var/lib/postgresql/virtualenvs/wal-e/lib/python3.5/site-packages/wal_e/worker/upload.py", line 96, in __call__
      gpg_key=self.gpg_key) as pl:
    File "/var/lib/postgresql/virtualenvs/wal-e/lib/python3.5/site-packages/wal_e/pipeline.py", line 92, in __enter__
      self.stdin = pipebuf.NonBlockBufferedWriter(stdin)
    File "/var/lib/postgresql/virtualenvs/wal-e/lib/python3.5/site-packages/wal_e/pipebuf.py", line 225, in __init__
      _setup_fd(self._fd)
    File "/var/lib/postgresql/virtualenvs/wal-e/lib/python3.5/site-packages/wal_e/pipebuf.py", line 62, in _setup_fd
      set_buf_size(fd)
    File "/var/lib/postgresql/virtualenvs/wal-e/lib/python3.5/site-packages/wal_e/pipebuf.py", line 53, in set_buf_size
      fcntl.fcntl(fd, fcntl.F_SETPIPE_SZ, OS_PIPE_SZ)
  PermissionError: [Errno 1] Operation not permitted

It's not clear why fcntl call may lead to PermissionError.

PostgreSQL version: 9.6, Python: 3.5, Wal-e : 1.1.1 (tried also 1.0.3 and 1.1.0).

It was working previously and stopped working at some point (without any noticeable changes).


问:
ffmpeg.probe not working when run from python on windows 10
I am relatively new to python, I am working on extracting some metadata from a video and I am trying to use ffmpeg.probe (or ffprobe) because it provides all the data I need.

After many errors I went to the basic and tried:

```<code>import ffmpeg
import json

movie_path="E:\Archive\Peliculas\Clasicos\Casablanca.avi"
probe = ffmpeg.probe(movie_path)
</code>```

The error that I get is:

```<code>Traceback (most recent call last):
  File "C:\Users\xxx\Desktop\test.py", line 5, in <module>
    probe = ffmpeg.probe(movie_path)
  File "C:\Users\xxx\AppData\Local\Programs\Python\Python310\lib\site-packages\ffmpeg\_probe.py", line 20, in probe
    p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  File "C:\Users\xxx\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 966, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "C:\Users\xxx\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 1435, in _execute_child
    hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified
</code>```

I have been searching around and tried installing and uninstalling ffmpeg, ffmpeg-python, installing it directly on windows (adding the files to the path so that I can run it in the console). Then tried to do it on my own using the _probe.py as example:

```<code>p = subprocess.Popen(['ffprobe', '-show_format', '-show_streams', '-of', 'json', 'E:\Archive\Peliculas\Clasicos\Casablanca.avi'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) #shell=True is not present in _probe.py  but it wont run otherwise
out, err = p.communicate()
</code>```

The error returned is: b'"ffprobe" is not recognized as an internal or external command, \r\n program, or executable batch file.\r\n' but runs, it is not the "FileNotFoundError"

When I run it in cmd there is no issue, ffprobe -show_format  -show_streams -of json E:\Archive\Peliculas\Clasicos\Casablanca.avi provides the information (with a couple of lines before the JSON but works).

I don't know if it is a windows thing (I have tried both \ and \\ already with no apparent difference) or I am doing wrong.

答:
You should have "ffprobe.exe" in the directory (just "ffmpeg.exe" isn't enough).
It solved the issue for me.</p>

Body:
I am relatively new to python, I am working on extracting some metadata from a video and I am trying to use ffmpeg.probe (or ffprobe) because it provides all the data I need.

After many errors I went to the basic and tried:

import ffmpeg
import json

movie_path="E:\Archive\Peliculas\Clasicos\Casablanca.avi"
probe = ffmpeg.probe(movie_path)

The error that I get is:

Traceback (most recent call last):
  File "C:\Users\xxx\Desktop\test.py", line 5, in <module>
    probe = ffmpeg.probe(movie_path)
  File "C:\Users\xxx\AppData\Local\Programs\Python\Python310\lib\site-packages\ffmpeg\_probe.py", line 20, in probe
    p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  File "C:\Users\xxx\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 966, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "C:\Users\xxx\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 1435, in _execute_child
    hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified

I have been searching around and tried installing and uninstalling ffmpeg, ffmpeg-python, installing it directly on windows (adding the files to the path so that I can run it in the console). Then tried to do it on my own using the _probe.py as example:

p = subprocess.Popen(['ffprobe', '-show_format', '-show_streams', '-of', 'json', 'E:\Archive\Peliculas\Clasicos\Casablanca.avi'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) #shell=True is not present in _probe.py  but it wont run otherwise
out, err = p.communicate()

The error returned is: b'"ffprobe" is not recognized as an internal or external command, \r\n program, or executable batch file.\r\n' but runs, it is not the "FileNotFoundError"

When I run it in cmd there is no issue, ffprobe -show_format  -show_streams -of json E:\Archive\Peliculas\Clasicos\Casablanca.avi provides the information (with a couple of lines before the JSON but works).

I don't know if it is a windows thing (I have tried both \ and \\ already with no apparent difference) or I am doing wrong.


问:
Strange issue with wordpress - critical error but nothing in debug.log
I have just put some changes to a wordpress theme live, it all works on the staging server but for some reason it's giving a critical error on the live site.

As normal i go and look at the debug.log file and there is no fatal error is showing in that file, and no error_log is showing it either.

Any ideas on why it's not recording the fatal error (usually that is what causes the wordpress critical error)

答:
Probably, the "fatal error" you're talking about occurred before WordPress was initialized. For example, if the code, that triggers the error is located in index.php of your active theme.

In this case, try to find error messages not in wp-content/debug.log, but in webserver logs folder /var/log/httpd/error_log/ or /var/log/apache2/error.log


问:
Count the existence number of a key in a list of dictionary
I used gspread and pandas to convert my google sheet into a list of dictionaries. The example list is shown as follows: (It's a very long list, so I only list a few lines)

```<code>mylist = [
{'StartDate': '2021-10-02', 'ID': 11773, 'Receiver': Mike, 'Days':66 },
{'StartDate': '2021-10-03', 'ID': 15673, 'Receiver': Jane, 'Days':65},
{'StartDate': '2021-10-03', 'ID': 15673, 'Receiver': Jane, 'Days':65},
{'StartDate': '2021-10-03', 'ID': 15673, 'Receiver': Mike, 'Days':65},
...
{'StartDate': '2021-10-5', 'ID': 34653, 'Receiver': Jack, 'Days':63}]
</code>```

I want to count the number of the existence of some keys, for example Mike and Jane in the Receiver field. I tried the following to count the total number of the rows, and I think I may use a similar code

```<code>counts = collections.Counter()
for d in package2019:
    counts.update(d.keys())
count_list = [{c: counts[c] for c in d} for d in mylist]
</code>```

I just don't know how should I count the number of existence for some keys. I'm new to python and I searched anywhere online with no luck

答:
You could use a list comprehension to build a list of receivers. Then pass that list to collections.Counter to get the counts of how many times each receiver appears in mylist:

```<code>from collections import Counter
receivers = [d['Receiver'] for d in mylist]
counts = Counter(receivers)
</code>```

Output:

```<code>Counter({'Mike': 2, 'Jane': 2, 'Jack': 1})
</code>```

Body:
I used gspread and pandas to convert my google sheet into a list of dictionaries. The example list is shown as follows: (It's a very long list, so I only list a few lines)

mylist = [
{'StartDate': '2021-10-02', 'ID': 11773, 'Receiver': Mike, 'Days':66 },
{'StartDate': '2021-10-03', 'ID': 15673, 'Receiver': Jane, 'Days':65},
{'StartDate': '2021-10-03', 'ID': 15673, 'Receiver': Jane, 'Days':65},
{'StartDate': '2021-10-03', 'ID': 15673, 'Receiver': Mike, 'Days':65},
...
{'StartDate': '2021-10-5', 'ID': 34653, 'Receiver': Jack, 'Days':63}]

I want to count the number of the existence of some keys, for example Mike and Jane in the Receiver field. I tried the following to count the total number of the rows, and I think I may use a similar code

counts = collections.Counter()
for d in package2019:
    counts.update(d.keys())
count_list = [{c: counts[c] for c in d} for d in mylist]

I just don't know how should I count the number of existence for some keys. I'm new to python and I searched anywhere online with no luck

Body:
You could use a list comprehension to build a list of receivers. Then pass that list to collections.Counter to get the counts of how many times each receiver appears in mylist:

from collections import Counter
receivers = [d['Receiver'] for d in mylist]
counts = Counter(receivers)

Output:

Counter({'Mike': 2, 'Jane': 2, 'Jack': 1})


问:
Make CloudBuild git push last commits to a branch in another repo
I have branch_a (development branch) in repo_A and branch_b in repo_B (production branch). Both repos are on Cloud Source.
Their history is the same, except for the last commit(s) in branch_a.

How to make CloudBuild push last commit(s) from repo_A/branch_a to repo_B/branch_b?

CloudBuild gets triggered with a push to repo_A/branch_a.  CloudBuild fetches repo_A/branch_a into the working directory

I managed to add repo_B/branch_b as remote. But when I try to push 'master' to repo_B/branch_b I get:

```<code>src refspec branch_b does not match any
failed to push some refs to repo_B
</code>```

git remote -v lists both remotes: repo_A and repo_B

CloudBuild service account has access to both repos

答:
For the future generations

The problem was that Cloud Build was pulling only the last commit from repo_A, thus comparing to repo_B/branch_B was showing inconsistent history.

git pull --unshallow did the trick.

Body:
I have branch_a (development branch) in repo_A and branch_b in repo_B (production branch). Both repos are on Cloud Source.
Their history is the same, except for the last commit(s) in branch_a.

How to make CloudBuild push last commit(s) from repo_A/branch_a to repo_B/branch_b?

CloudBuild gets triggered with a push to repo_A/branch_a.  CloudBuild fetches repo_A/branch_a into the working directory

I managed to add repo_B/branch_b as remote. But when I try to push 'master' to repo_B/branch_b I get:

src refspec branch_b does not match any
failed to push some refs to repo_B

git remote -v lists both remotes: repo_A and repo_B

CloudBuild service account has access to both repos