问:
How to build grouped tree array from flat array in php
i am trying to re format a array as tree, main array and child arrays should be grouped by "name" property.

my flat array is like

```<code>$flat = [
    ['id' => 1, 'parent_id' => 0, 'name' => 'root1'],
    ['id' => 2, 'parent_id' => 0, 'name' => 'root1'],
    ['id' => 3, 'parent_id' => 1, 'name' => 'ch-1'],
    ['id' => 4, 'parent_id' => 1, 'name' => 'ch-1'],
    ['id' => 5, 'parent_id' => 3, 'name' => 'ch-1-1'],
    ['id' => 6, 'parent_id' => 3, 'name' => 'ch-1-1'],
    ['id' => 7, 'parent_id' => 0, 'name' => 'root2'],
    ['id' => 8, 'parent_id' => 0, 'name' => 'root2'],
    ['id' => 9, 'parent_id' => 7, 'name' => 'ch3-1'],
    ['id' => 10, 'parent_id' => 7, 'name' => 'ch3-1']
];
</code>```

i could build tree structure by

```<code>$tree = buildTree($flat, 'parent_id', 'id');

function buildTree(array $flatList)
{
    $grouped = [];
    foreach ($flatList as $node) {
        $grouped[$node['parent_id']][] = $node;
    }

    $fnBuilder = function ($siblings) use (&$fnBuilder, $grouped) {
        foreach ($siblings as $k => $sibling) {
            $id = $sibling['id'];
            if (isset($grouped[$id])) {
                $sibling['children'] = $fnBuilder($grouped[$id]);
            }
            $siblings[$k] = $sibling;
        }
        return $siblings;
    };

    return $fnBuilder($grouped[0]);
}
</code>```

this works perfectly.

But what i want is build nested array should be grouped by it's "name" property.

so the final output should be like

```<code>[
  "root1": [{
      "id": 1,
      "parent_id": 0,
      "name": "root1",
      "children": [
        "ch-1": [{
            "id": 3,
            "parent_id": 1,
            "name": "ch-1",
            "children": [
              "ch-1-1": [{
                  "id": 5,
                  "parent_id": 3,
                  "name": "ch-1-1"
                },
                {
                  "id": 6,
                  "parent_id": 3,
                  "name": "ch-1-1"
                }
              ]
            ]
          },
          {
            "id": 4,
            "parent_id": 1,
            "name": "ch-1"
          }
        ]
      ]
    },
    {
      "id": 2,
      "parent_id": 0,
      "name": "root1"
    }
  ],
  "root2": [{
      "id": 7,
      "parent_id": 0,
      "name": "root2",
      "children": [
        "ch3-1": [{
            "id": 9,
            "parent_id": 7,
            "name": "ch3-1"
          },
          {
            "id": 10,
            "parent_id": 7,
            "name": "ch3-2"
          }
        ]
      ]
    },
    {
      "id": 8,
      "parent_id": 0,
      "name": "root2"
    }
  ]
]
</code>```

I have been stuck here almost for couple of days. Please help me to solve this problem.
Thank you.

答:
Use a function like these with unset()

```<code>function buildTree(array &$flat, $parentId = 0) {
    $branch = array();

    foreach ($flat as $element) {
        if ($element['parent_id'] == $parentId) {
            $children = buildTree($flat, $element['id']);
        if ($children) {
            $element['children'] = $children;
        }
        $branch[$element['id']] = $element;
        unset($flat[$element['id']]);
        }
    }
    return $branch;
}
</code>```

After buildTree we need to group by name here is my code:-

```<code>$result = array();
foreach ($buildTree as $element) {
    $result[$element['name']][] = $element;
}
</code>```

Hope it will help you. see details from here

Thanks

Body:
i am trying to re format a array as tree, main array and child arrays should be grouped by "name" property.

my flat array is like

$flat = [
    ['id' => 1, 'parent_id' => 0, 'name' => 'root1'],
    ['id' => 2, 'parent_id' => 0, 'name' => 'root1'],
    ['id' => 3, 'parent_id' => 1, 'name' => 'ch-1'],
    ['id' => 4, 'parent_id' => 1, 'name' => 'ch-1'],
    ['id' => 5, 'parent_id' => 3, 'name' => 'ch-1-1'],
    ['id' => 6, 'parent_id' => 3, 'name' => 'ch-1-1'],
    ['id' => 7, 'parent_id' => 0, 'name' => 'root2'],
    ['id' => 8, 'parent_id' => 0, 'name' => 'root2'],
    ['id' => 9, 'parent_id' => 7, 'name' => 'ch3-1'],
    ['id' => 10, 'parent_id' => 7, 'name' => 'ch3-1']
];

i could build tree structure by

$tree = buildTree($flat, 'parent_id', 'id');

function buildTree(array $flatList)
{
    $grouped = [];
    foreach ($flatList as $node) {
        $grouped[$node['parent_id']][] = $node;
    }

    $fnBuilder = function ($siblings) use (&$fnBuilder, $grouped) {
        foreach ($siblings as $k => $sibling) {
            $id = $sibling['id'];
            if (isset($grouped[$id])) {
                $sibling['children'] = $fnBuilder($grouped[$id]);
            }
            $siblings[$k] = $sibling;
        }
        return $siblings;
    };

    return $fnBuilder($grouped[0]);
}

this works perfectly.

But what i want is build nested array should be grouped by it's "name" property.

so the final output should be like

[
  "root1": [{
      "id": 1,
      "parent_id": 0,
      "name": "root1",
      "children": [
        "ch-1": [{
            "id": 3,
            "parent_id": 1,
            "name": "ch-1",
            "children": [
              "ch-1-1": [{
                  "id": 5,
                  "parent_id": 3,
                  "name": "ch-1-1"
                },
                {
                  "id": 6,
                  "parent_id": 3,
                  "name": "ch-1-1"
                }
              ]
            ]
          },
          {
            "id": 4,
            "parent_id": 1,
            "name": "ch-1"
          }
        ]
      ]
    },
    {
      "id": 2,
      "parent_id": 0,
      "name": "root1"
    }
  ],
  "root2": [{
      "id": 7,
      "parent_id": 0,
      "name": "root2",
      "children": [
        "ch3-1": [{
            "id": 9,
            "parent_id": 7,
            "name": "ch3-1"
          },
          {
            "id": 10,
            "parent_id": 7,
            "name": "ch3-2"
          }
        ]
      ]
    },
    {
      "id": 8,
      "parent_id": 0,
      "name": "root2"
    }
  ]
]

I have been stuck here almost for couple of days. Please help me to solve this problem.
Thank you.

Body:
Use a function like these with unset()

function buildTree(array &$flat, $parentId = 0) {
    $branch = array();

    foreach ($flat as $element) {
        if ($element['parent_id'] == $parentId) {
            $children = buildTree($flat, $element['id']);
        if ($children) {
            $element['children'] = $children;
        }
        $branch[$element['id']] = $element;
        unset($flat[$element['id']]);
        }
    }
    return $branch;
}

After buildTree we need to group by name here is my code:-

$result = array();
foreach ($buildTree as $element) {
    $result[$element['name']][] = $element;
}

Hope it will help you. see details from here

Thanks


来源: stackexchange

问:
Using the broom::tidy to add confidence intervals to linear models in nested data frame
I've been trying follow the approach set out by Hadley Wickham for running multiple models in a nested data frame as per https://r4ds.had.co.nz/many-models.html

I've managed to write this code below to create the multiple linear models:

```<code>#create nested data frame
by_clin_grp <- df_long %>%
  group_by(clin_risk) %>%
  nest()

#create a function to run the linear models
model <- function(df){
  lm(outcome ~ age + sex + clin_sub_grp, data =df)
}

#run the models
by_clin_grp <- by_clin_grp %>%
  mutate(model = map(data,model))

#unnest the models using the broom package
by_clin_grp_unnest <- by_clin_grp %>%
  mutate(tidy = map(model, broom::tidy))%>%
  unnest(tidy)
</code>```

However, I need to add confidence intervals around my regression estimates. It seems like I should be able to add them using broom::tidy as per the help page but I'm unable to work out how to specify this correctly in the code above?

答:
You have to specify the relevant arguments inside map. There are two possibilities:

```<code>by_clin_grp_unnest <- by_clin_grp %>%
  mutate(tidy = map(model, ~broom::tidy(.x, conf.int = TRUE, conf.level = 0.99)))%>%
  unnest(tidy)
</code>```

or

```<code>by_clin_grp_unnest <- by_clin_grp %>%
  mutate(tidy = map(model, broom::tidy, conf.int = TRUE, conf.level = 0.99)) %>%
  unnest(tidy)
</code>```

Both are equivalent just differ in syntax

ContentLicense: CC BY-SA 4.0

Body:
I've been trying follow the approach set out by Hadley Wickham for running multiple models in a nested data frame as per https://r4ds.had.co.nz/many-models.html

I've managed to write this code below to create the multiple linear models:

#create nested data frame
by_clin_grp <- df_long %>%
  group_by(clin_risk) %>%
  nest()

#create a function to run the linear models
model <- function(df){
  lm(outcome ~ age + sex + clin_sub_grp, data =df)
}

#run the models
by_clin_grp <- by_clin_grp %>%
  mutate(model = map(data,model))

#unnest the models using the broom package
by_clin_grp_unnest <- by_clin_grp %>%
  mutate(tidy = map(model, broom::tidy))%>%
  unnest(tidy)

However, I need to add confidence intervals around my regression estimates. It seems like I should be able to add them using broom::tidy as per the help page but I'm unable to work out how to specify this correctly in the code above?

Body:
You have to specify the relevant arguments inside map. There are two possibilities:

by_clin_grp_unnest <- by_clin_grp %>%
  mutate(tidy = map(model, ~broom::tidy(.x, conf.int = TRUE, conf.level = 0.99)))%>%
  unnest(tidy)

or

by_clin_grp_unnest <- by_clin_grp %>%
  mutate(tidy = map(model, broom::tidy, conf.int = TRUE, conf.level = 0.99)) %>%
  unnest(tidy)

Both are equivalent just differ in syntax


问:
Subset dataset with several levels of a categorical variable
I want to subset a dataset with several levels of a categorical variable in Rstudio.

With the function "subset" I am able to do it with just one level

new_df<-subset(df, df$cat.var=="level.1")

How do I subset with more than one levels?

答:
You can use %in%.

This is a membership operator that you can use with a vector of the factor levels of cat.var which you would like to retain rows for.

new_df <- subset(df, df$cat.var %in% c("level.1", "level.2"))
```
<p>For example</p>
<pre class="lang-r prettyprint-override"><code>df <- data.frame(fct = rep(letters[1:3], times = 2), nums = 1:6)

df

# This is our example data.frame
#   fct nums
# 1   a    1
# 2   b    2
# 3   c    3
# 4   a    4
# 5   b    5
# 6   c    6

subset(df, df$fct %in% c("a", "b"))

# Subsetting on a factor using %in% returns the following output:
#   fct nums
# 1   a    1
# 2   b    2
# 4   a    4
# 5   b    5
</code>```

Note: Another option is to use the filter function from dplyr as follows

library(dplyr)

filter(df, fct %in% c("a", "b"))
```

This returns the same filtered (subsetted) dataframe.

Body:
You can use %in%.

This is a membership operator that you can use with a vector of the factor levels of cat.var which you would like to retain rows for.

new_df <- subset(df, df$cat.var %in% c("level.1", "level.2"))

For example

df <- data.frame(fct = rep(letters[1:3], times = 2), nums = 1:6)

df

# This is our example data.frame
#   fct nums
# 1   a    1
# 2   b    2
# 3   c    3
# 4   a    4
# 5   b    5
# 6   c    6

subset(df, df$fct %in% c("a", "b"))

# Subsetting on a factor using %in% returns the following output:
#   fct nums
# 1   a    1
# 2   b    2
# 4   a    4
# 5   b    5

Note: Another option is to use the filter function from dplyr as follows

library(dplyr)

filter(df, fct %in% c("a", "b"))

This returns the same filtered (subsetted) dataframe.


问:
On public XMPP servers, how do you find which port supports websockets?
Opening a websocket without a port specified seems to fail on all xmpp servers. I assume this means there is no default websocket port.

I have been able to only open one xmpp server's websocket. It does not appear other xmpp servers use the same 5291 websocket port as tigase.im

How do you determine the websocket port for a public XMPP server? The lists of open xmpp servers seem to only give a url.

I at first tried DNS SRV lookup using DNSchecker.org which showed no SRV record.

As I learned more about DNS SRV lookup formats by reading RFC 6120, I found I can get the tcp port using mxtoolbox.com with the string: _xmpp-client._tcp.tigase.im

On a hunch, I tried _xmpp-client._websocket.tigase.im, but no port was returned. On further reading, the IETF specified to try the string _ws._tcp.tigase.im which also returned nothing using mxtoolbox.com  Is there a different string I should be using with mxtoolbox.com?

Is there another way to get the websocket port number of a public XMPP server?

答:
XEP-0156 in addition to specifying DNS SRV records to find websocket ports, says they may be specified in the DNS TXT records.
These can be found, as I was trying, using mxtoolbox.com with the string _xmppconnect.tigase.im or with the linux and windows console commands "dig +short txt _xmppconnect.tigase.im" or "nslookup q=txt _xmppconnect.tigase.im"

Thanks to AGodThatCanDance on Reddit


问:
How to track transaction status on elrond network
Can someone help with tracking the transaction status of a value transfer on the elrond network?

```<code>   const testTransaction = new Transaction({
      value: Balance.egld(1),
      data: new TransactionPayload('Test Transfer'),
      receiver: new Address(ownerWallet),
      nonce: sender.nonce,
      gasPrice: new GasPrice(10000000000,
      gasLimit: new GasLimit(1000000)
    });

    await refreshAccount();

    const { sessionId  } = await sendTransactions({
      transactions: testTransaction,
      transactionsDisplayInfo: {
        processingMessage: 'Processing transaction',
        errorMessage: 'An error has occured during Transaction',
        successMessage: 'Transaction successful'
      }
    });
</code>```

I am currently using sendTransactions to send my transaction.

答:
According to the documentation of the erdjs documentation, you can use the TransactionWatcher.

Here's below a reduced example from the documentation:

```<code>await tx1.send(provider);

let watcher = new TransactionWatcher(tx1.hash, provider);
await watcher.awaitStatus(status => status.isExecuted());
</code>```

The erdjs doc:  https://elrondnetwork.github.io/elrond-sdk-docs/erdjs/latest/

Body:
Can someone help with tracking the transaction status of a value transfer on the elrond network?

   const testTransaction = new Transaction({
      value: Balance.egld(1),
      data: new TransactionPayload('Test Transfer'),
      receiver: new Address(ownerWallet),
      nonce: sender.nonce,
      gasPrice: new GasPrice(10000000000,
      gasLimit: new GasLimit(1000000)
    });

    await refreshAccount();

    const { sessionId  } = await sendTransactions({
      transactions: testTransaction,
      transactionsDisplayInfo: {
        processingMessage: 'Processing transaction',
        errorMessage: 'An error has occured during Transaction',
        successMessage: 'Transaction successful'
      }
    });

I am currently using sendTransactions to send my transaction.

Body:
According to the documentation of the erdjs documentation, you can use the TransactionWatcher.

Here's below a reduced example from the documentation:

await tx1.send(provider);

let watcher = new TransactionWatcher(tx1.hash, provider);
await watcher.awaitStatus(status => status.isExecuted());

The erdjs doc:  https://elrondnetwork.github.io/elrond-sdk-docs/erdjs/latest/


问:
how can i have a struct have an unknown size array member?
im trying to make a sort of minesweeper clone in c, but i cant figure out how to create a variable length array member of a struct and initialize it.

my struct definitions

typedef struct Cell
{
    Rectangle area;         // The area the cell covers
    bool hasMine;           // If the cell covers a mine
    bool covered;           // If the cell is currently covered
    int touching;           // How many mines the cell is touching
} Cell;

typedef struct Minefield
{
    int columns;        // The amount of columns
    int rows;           // The amount of rows
    int mines;          // The amount of mines
    Cell field[];       // An array of columns*rows Cells

} Minefield;
```
<p>how im creating new instances of a Minefield</p>
<pre class="lang-c prettyprint-override"><code>Minefield NewGame(int columns, int rows, int mines)
{
    int i = 0;

    Cell cells[columns*rows];

    for (i=0; i < columns*rows; i++) {
        int x = 0;
        int y = 0;

        if (i == 0) {
            Rectangle area = (Rectangle){0, 0, cellsize, cellsize};
            cells[i] = (Cell){area, false, true, 0};
        }
        else {
            Cell previous = cells[i-1];

            x = previous.area.x + cellsize;
            y = previous.area.y + cellsize;

            Rectangle area = (Rectangle){x, y, cellsize, cellsize};
            cells[i] = (Cell){area, false, true, 0};
        }

    }

    Minefield field = (Minefield){columns, rows, mines, cells};
    return field;
}
</code>```

im new to c, ive done some googling and ive come across some very similar questions, but i cant really understand them or the examples they give. i think you can do what my errendous code is trying to do (or something very similar) with a gcc extension, but i want my code to be portable. how can i have a struct have an unknown size array member?

答: Unfortunately, C doesn't have any built-in dynamic array like python. However, if you want to use some dynamic array either you can implement your self or you can see the answer to that link C dynamically growing array which explains that you need to have starting array with a default size, and then you can increase the size of the array which depends on your algorithm. After you import that header file provided by @casablance, you can simply use it for your minesweeper game.</p>

Body:
im trying to make a sort of minesweeper clone in c, but i cant figure out how to create a variable length array member of a struct and initialize it.

my struct definitions

typedef struct Cell
{
    Rectangle area;         // The area the cell covers
    bool hasMine;           // If the cell covers a mine
    bool covered;           // If the cell is currently covered
    int touching;           // How many mines the cell is touching
} Cell;

typedef struct Minefield
{
    int columns;        // The amount of columns
    int rows;           // The amount of rows
    int mines;          // The amount of mines
    Cell field[];       // An array of columns*rows Cells

} Minefield;

how im creating new instances of a Minefield

Minefield NewGame(int columns, int rows, int mines)
{
    int i = 0;

    Cell cells[columns*rows];

    for (i=0; i < columns*rows; i++) {
        int x = 0;
        int y = 0;

        if (i == 0) {
            Rectangle area = (Rectangle){0, 0, cellsize, cellsize};
            cells[i] = (Cell){area, false, true, 0};
        }
        else {
            Cell previous = cells[i-1];

            x = previous.area.x + cellsize;
            y = previous.area.y + cellsize;

            Rectangle area = (Rectangle){x, y, cellsize, cellsize};
            cells[i] = (Cell){area, false, true, 0};
        }

    }

    Minefield field = (Minefield){columns, rows, mines, cells};
    return field;
}

im new to c, ive done some googling and ive come across some very similar questions, but i cant really understand them or the examples they give. i think you can do what my errendous code is trying to do (or something very similar) with a gcc extension, but i want my code to be portable. how can i have a struct have an unknown size array member?


答:
You have to use SELECT query with LIKE keyword

The percentage ( % ) wildcard matches any string of zero or more characters. For example, b% matches any string starts with the character b such as Benny and Ben.

```<code>SELECT * FROM students WHERE name LIKE 'b%';
</code>```

If you have same name in record which starts from uppercase as well as lowecase then put BINARY keyword after LIKE keyword (Case Sensitive):

```<code>SELECT * FROM students WHERE name LIKE BINARY 'b%';
</code>```

Title: How to find a specific row in an index

Body:
I am new to MySQL and am not very familiar with it. I am supposed to find a name that starts with b in index, which i do not have the slightest clue of doing.

| id | name         | DoB        | class | marks | dept_id |
+----+--------------+------------+-------+-------+---------+
|  1 | Data Science | 2006-07-15 |    11 |   100 |       3 |
|  2 | Garry        | 2006-08-20 |    11 |    92 |       4 |
|  3 | Jane         | 2006-03-22 |    10 |    95 |       2 |
|  4 | Benny        | 2005-10-10 |    12 |    74 |       4 |
|  5 | Karen        | 2005-01-15 |    12 |    88 |       3 |
|  6 | Camy         | 2006-04-18 |    12 |    91 |       2 |
|  7 | Farhan       | 2006-09-21 |    11 |    80 |    NULL |
|  8 | Shamil       | 2005-10-19 |    11 |    90 |       3 |
+----+--------------+------------+-------+-------+---------+

The Table above is (students)
And the one Below it is the Index of (students)

+----------+------------+------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
| Table    | Non_unique | Key_name   | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | Visible | Expression |
+----------+------------+------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
| students |          0 | PRIMARY    |            1 | id          | A         |           6 |     NULL |   NULL |      | BTREE      |         |               | YES     | NULL       |
| students |          1 | dept_id    |            1 | dept_id     | A         |           3 |     NULL |   NULL | YES  | BTREE      |         |               | YES     | NULL       |
| students |          1 | name_index |            1 | name        | A         |           6 |     NULL |   NULL |      | BTREE      |         |               | YES     | NULL       |
| students |          1 | index_name |            1 | name        | A         |           6 |     NULL |   NULL |      | BTREE      |         |               | YES     | NULL       |
+----------+------------+------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+

Body:
You have to use SELECT query with LIKE keyword

The percentage ( % ) wildcard matches any string of zero or more characters. For example, b% matches any string starts with the character b such as Benny and Ben.

SELECT * FROM students WHERE name LIKE 'b%';

If you have same name in record which starts from uppercase as well as lowecase then put BINARY keyword after LIKE keyword (Case Sensitive):

SELECT * FROM students WHERE name LIKE BINARY 'b%';


问:
Sms cannot be Sent via twilio getting 400 error
I am trying to send SMS via Twilio using HttpEntity from my Java code. I am getting 400 Bad Request with no details. The response is below.

```<code> [<html>
 <head><title>400 Bad Request</title></head>
 <body>
 <center><h1>400 Bad Request</h1></center>
 <hr><center>openresty</center>
 </body>
 </html>]
</code>```

Below is the code I have used to send a request. The request is successful from Postman. I cannot use Java SDK and has to use RestTemplate.

```<code> HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.add("route-to-back-end-endpoint", "https://api.twilio.com/2010-04-01/Accounts/xxx/Messages.json");
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("To", "+91*******");
        map.add("From", "+1******");
        map.add("Body", "Try try try");
        HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(map, headers);
        String response = null;
        try {
            restTemplateSsl.getInterceptors().add(new BasicAuthenticationInterceptor("xxx", "yyy"));
            response = restTemplateSsl.postForObject("Internal Xml Gateway Link", entity, String.class);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("Exception : {} ", e.getMessage());
        }
        log.info("Response Received :{}", response);
        return response;
</code>```

The authentication is successful with Twilio. So no authentication issue. I am not sure what is exactly wrong in request.

答: You might get this error if the path in your HTTP request doesn't start with '/'.</p>

Body:
I am trying to send SMS via Twilio using HttpEntity from my Java code. I am getting 400 Bad Request with no details. The response is below.

 [
 <title>400 Bad Request</title>

400 Bad Request

openresty

 ]

Below is the code I have used to send a request. The request is successful from Postman. I cannot use Java SDK and has to use RestTemplate.

 HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.add("route-to-back-end-endpoint", "https://api.twilio.com/2010-04-01/Accounts/xxx/Messages.json");
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("To", "+91*******");
        map.add("From", "+1******");
        map.add("Body", "Try try try");
        HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(map, headers);
        String response = null;
        try {
            restTemplateSsl.getInterceptors().add(new BasicAuthenticationInterceptor("xxx", "yyy"));
            response = restTemplateSsl.postForObject("Internal Xml Gateway Link", entity, String.class);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("Exception : {} ", e.getMessage());
        }
        log.info("Response Received :{}", response);
        return response;

The authentication is successful with Twilio. So no authentication issue. I am not sure what is exactly wrong in request.


问:
Default argument for a multiple argument function only when no argument supplied
Let's consider a function that accepts multiple arguments as under:

```<code>def my_function(*args):
    my_list = []
    for _ in args:
        my_list.append(_)
    another_function(my_list)
</code>```

Now, the issue that I face in my scenario is that: I need my_list to contain at least one value, any argument, but at least one.

A user can do my_function(arg1), my_fuynction(arg1,arg2), my_function(arg1,arg2,arg3) and so on. But if a user does my_function(), I need to provide a default argument (say arg1) to the function.

If I put an default argument, then the argument defaultarg will be compulsory and it has to be supplied with some value:

```<code>def my_function(defaultarg, *args):
    #function
</code>```

If I put it as optional argument, then I will have to provide a default value to the argument:

```<code>def my_function(optionalarg = defaultvalue, *args):
    #function
</code>```

Both these ways do not work for me as I can't make it compulsory and I can't give a default value for it.

How do I create this function so that if no arguments are passed, the function assumes one argument to have been passed?

As of now, I am handling this by putting a if...else in the function as under:

```<code>def my_function(*args):
    my_list = []
    if len(args) == 0:
        my_list.append('defaultarg')
    else:
        for _ in args:
            my_list.append(_)
    another_function(my_list)
</code>```

Is there any better way to do this?

答:
I can't give a default value for it

I don't understand this part of your question. You are providing the default value 'defaultarg' in your own solution?! My answer assumes that you can get the default value from somewhere.

Anyway, if you want to keep the f(*args) signature, you can check whether the args tuple is empty and supply a default value.

```<code>def my_function(*args):
     if not args:
         args = (default_value,)
     # more code
</code>```

or

```<code>def my_function(*args):
     if not args:
         return my_function(default_value)
     # more code
</code>```

You won't get around explicitly checking whether args is empty, but maybe you'll like one of these proposals better than your version.

edit:

You could also write a parameterized decorator.

```<code>def with_default_value(default_value):
    def with_default_value_decorator(f):
        def f_new(*args):
            if not args:
                return f(default_value)
            return f(*args)
        return f_new
    return with_default_value_decorator
</code>```

Example:

```<code>@with_default_value('hi')
def my_print(*args):
    print(' '.join(args))

</code>```

Demo:

```<code>>>> my_print('hello', 'world')
hello world
>>> my_print()
hi
</code>```

Body:
Let's consider a function that accepts multiple arguments as under:

def my_function(*args):
    my_list = []
    for _ in args:
        my_list.append(_)
    another_function(my_list)

Now, the issue that I face in my scenario is that: I need my_list to contain at least one value, any argument, but at least one.

A user can do my_function(arg1), my_fuynction(arg1,arg2), my_function(arg1,arg2,arg3) and so on. But if a user does my_function(), I need to provide a default argument (say arg1) to the function.

If I put an default argument, then the argument defaultarg will be compulsory and it has to be supplied with some value:

def my_function(defaultarg, *args):
    #function

If I put it as optional argument, then I will have to provide a default value to the argument:

def my_function(optionalarg = defaultvalue, *args):
    #function

Both these ways do not work for me as I can't make it compulsory and I can't give a default value for it.

How do I create this function so that if no arguments are passed, the function assumes one argument to have been passed?

As of now, I am handling this by putting a if...else in the function as under:

def my_function(*args):
    my_list = []
    if len(args) == 0:
        my_list.append('defaultarg')
    else:
        for _ in args:
            my_list.append(_)
    another_function(my_list)

Is there any better way to do this?

Body:
I can't give a default value for it

I don't understand this part of your question. You are providing the default value 'defaultarg' in your own solution?! My answer assumes that you can get the default value from somewhere.

Anyway, if you want to keep the f(*args) signature, you can check whether the args tuple is empty and supply a default value.

def my_function(*args):
     if not args:
         args = (default_value,)
     # more code

or

def my_function(*args):
     if not args:
         return my_function(default_value)
     # more code

You won't get around explicitly checking whether args is empty, but maybe you'll like one of these proposals better than your version.

edit:

You could also write a parameterized decorator.

def with_default_value(default_value):
    def with_default_value_decorator(f):
        def f_new(*args):
            if not args:
                return f(default_value)
            return f(*args)
        return f_new
    return with_default_value_decorator

Example:

@with_default_value('hi')
def my_print(*args):
    print(' '.join(args))

Demo:

>>> my_print('hello', 'world')
hello world
>>> my_print()
hi


问:
"auto" keyword affects math calculations?
Consider next code:

```<code>#include <cmath>
unsigned int nump=12u;
auto inner=2.5;
auto outer=6.0;
auto single=2*3.14159265359/nump;
auto avg=0.5*inner+0.5*outer;
for (auto i=0u;i<nump;++i){
    auto theta=i*single;
    auto px=avg*sin(theta);
    auto py=avg*cos(theta);
    auto tw=17.;
    int v1=std::round(1+px-tw/2.0);
    int v2=std::round(2+py-tw/2.0);
    std::cout<<"#"<<i<<":"<<v1<<";"<<v2<<std::endl;
}
</code>```

it produces output like this:

```<code>#0:-8;-2
#1:-5;-3
#2:-4;-4
#3:-3;-7
#4:-4;-9
#5:-5;-10
#6:-8;-11
#7:-10;-10
#8:-11;-9
#9:-12;-6
#10:-11;-4
#11:-10;-3
</code>```

Now let's modify this code by replacing most of "auto" with "float":

```<code>#include <cmath>
unsigned int nump=12u;
float inner=2.5;
float outer=6.0;
float single=2*3.14159265359/nump;
float avg=0.5*inner+0.5*outer;
for (unsigned int i=0u;i<nump;++i){
    float theta=i*single;
    float px=avg*sin(theta);
    float py=avg*cos(theta);
    float tw=17.;
    int v1=std::round(1+px-tw/2.0);
    int v2=std::round(2+py-tw/2.0);
    std::cout<<"#"<<i<<":"<<v1<<","<<v2<<std::endl;
}
</code>```

and here's the second output:

```<code>#0:-8,-2
#1:-5,-3
#2:-4,-4
#3:-3,-7
#4:-4,-9
#5:-5,-10
#6:-8,-11
#7:-10,-10
#8:-11,-9
#9:-12,-7
#10:-11,-4
#11:-10,-3
</code>```

As one can see in line 9 values are different.
Any explanation?

PS. OS X 10.12 c++11 and c++14, Apple LLVM 8.1; however was observed also on linux platform with C++17.

UPDATE

As people suggested I modified the code by adding "f" suffix to floating-point values.

```<code>unsigned int nump=12u;
auto inner=2.5f;
auto outer=6.0f;
auto single=2.f*3.14159265359f/nump;
auto avg=0.5f*inner+0.5f*outer;
for (auto i=0u;i<nump;++i){
    auto theta=i*single;
    auto px=avg*sin(theta);
    auto py=avg*cos(theta);
    auto tw=17.f;
    int v1=std::round(1.f+px-tw/2.0f);
    int v2=std::round(2.f+py-tw/2.0f);
    std::cout<<"#"<<i<<":"<<v1<<";"<<v2<<std::endl;
}
</code>```

versus

```<code>unsigned int nump=12u;
float inner=2.5f;
float outer=6.0f;
float single=2.f*3.14159265359f/nump;
float avg=0.5f*inner+0.5f*outer;
for (unsigned int i=0u;i<nump;++i){
    float theta=i*single;
    float px=avg*sin(theta);
    float py=avg*cos(theta);
    float tw=17.f;
    int v1=std::round(1.f+px-tw/2.0f);
    int v2=std::round(2.f+py-tw/2.0f);
    std::cout<<"#"<<i<<":"<<v1<<";"<<v2<<std::endl;
}
</code>```

The result is exactly the same.

答:
2.5 for example is a double type. So inner is a double in your first snippet, but a float in the second. (Note that the expression 2 * 3.14159265359 / nump is a double too.)

So the type conversions are bound to cost precision in places. That is the cause of the difference you observe.

On modern desktop systems you'll likely find that double is faster than a float as in using the latter can cause type conversions (unnoticed by the programmer) at the machine level.

Body:
Consider next code:

#include <cmath>
unsigned int nump=12u;
auto inner=2.5;
auto outer=6.0;
auto single=2*3.14159265359/nump;
auto avg=0.5*inner+0.5*outer;
for (auto i=0u;i<nump;++i){
    auto theta=i*single;
    auto px=avg*sin(theta);
    auto py=avg*cos(theta);
    auto tw=17.;
    int v1=std::round(1+px-tw/2.0);
    int v2=std::round(2+py-tw/2.0);
    std::cout<<"#"<<i<<":"<<v1<<";"<<v2<<std::endl;
}

it produces output like this:

#0:-8;-2
#1:-5;-3
#2:-4;-4
#3:-3;-7
#4:-4;-9
#5:-5;-10
#6:-8;-11
#7:-10;-10
#8:-11;-9
#9:-12;-6
#10:-11;-4
#11:-10;-3

Now let's modify this code by replacing most of "auto" with "float":

#include <cmath>
unsigned int nump=12u;
float inner=2.5;
float outer=6.0;
float single=2*3.14159265359/nump;
float avg=0.5*inner+0.5*outer;
for (unsigned int i=0u;i<nump;++i){
    float theta=i*single;
    float px=avg*sin(theta);
    float py=avg*cos(theta);
    float tw=17.;
    int v1=std::round(1+px-tw/2.0);
    int v2=std::round(2+py-tw/2.0);
    std::cout<<"#"<<i<<":"<<v1<<","<<v2<<std::endl;
}

and here's the second output:

#0:-8,-2
#1:-5,-3
#2:-4,-4
#3:-3,-7
#4:-4,-9
#5:-5,-10
#6:-8,-11
#7:-10,-10
#8:-11,-9
#9:-12,-7
#10:-11,-4
#11:-10,-3

As one can see in line 9 values are different.
Any explanation?

PS. OS X 10.12 c++11 and c++14, Apple LLVM 8.1; however was observed also on linux platform with C++17.

UPDATE

As people suggested I modified the code by adding "f" suffix to floating-point values.

unsigned int nump=12u;
auto inner=2.5f;
auto outer=6.0f;
auto single=2.f*3.14159265359f/nump;
auto avg=0.5f*inner+0.5f*outer;
for (auto i=0u;i<nump;++i){
    auto theta=i*single;
    auto px=avg*sin(theta);
    auto py=avg*cos(theta);
    auto tw=17.f;
    int v1=std::round(1.f+px-tw/2.0f);
    int v2=std::round(2.f+py-tw/2.0f);
    std::cout<<"#"<<i<<":"<<v1<<";"<<v2<<std::endl;
}

versus

unsigned int nump=12u;
float inner=2.5f;
float outer=6.0f;
float single=2.f*3.14159265359f/nump;
float avg=0.5f*inner+0.5f*outer;
for (unsigned int i=0u;i<nump;++i){
    float theta=i*single;
    float px=avg*sin(theta);
    float py=avg*cos(theta);
    float tw=17.f;
    int v1=std::round(1.f+px-tw/2.0f);
    int v2=std::round(2.f+py-tw/2.0f);
    std::cout<<"#"<<i<<":"<<v1<<";"<<v2<<std::endl;
}

The result is exactly the same.


问:
How come Netlify CMS on localhost is not working?
I’m from Taiwan and not good at English, but I’ll try my best to explain my question.

I use Netlify CMS to build my Hugo website.

Everything runs well, but when I want to change and check if the CMS’s configuration and style is okay, I always need to push my repository to Github, which is disturb me a lot.

So I tried to use local_backend: true in admin/config.yml, then used this command: npx netlify-cms-proxy-server.
then the window showed:

```<code>info: Netlify CMS File System Proxy Server configured with C:\Users\june.wu\Documents\GitHub\house-blog-hugo-cms
info: Netlify CMS Proxy Server listening on port 8081
</code>```

It looked it ran successfully on localhost:8081.
But when I type localhost:8081 in browser it showed: Cannot GET /

How can I solve this problem?

答:
I can confirm what said in the previous answer. Run npx netlify-cms-proxy-server and go to localhost:8080/admin or try also localhost:8080/admin/ (with ending slash). It should work if you are using default 8080 port.

Ignore that CMS is on port 8081 as said in the script log

Body:
I’m from Taiwan and not good at English, but I’ll try my best to explain my question.

I use Netlify CMS to build my Hugo website.

Everything runs well, but when I want to change and check if the CMS’s configuration and style is okay, I always need to push my repository to Github, which is disturb me a lot.

So I tried to use local_backend: true in admin/config.yml, then used this command: npx netlify-cms-proxy-server.
then the window showed:

info: Netlify CMS File System Proxy Server configured with C:\Users\june.wu\Documents\GitHub\house-blog-hugo-cms
info: Netlify CMS Proxy Server listening on port 8081

It looked it ran successfully on localhost:8081.
But when I type localhost:8081 in browser it showed: Cannot GET /

How can I solve this problem?


答:
No. auto does not directly affect maths. What does affect maths is the type of your variables involved in the calculation.

```<code>float inner=2.5;
</code>```

This is a float initialized by the floating point literal 2.5 which is of type double.

This on the other hand:

```<code>auto inner=2.5;
</code>```

Declares inner to be initialized with the floating point literal 2.5 which is of type double and the type of inner is deduced from the initializer: innter is a double.

Change your floating point literals to float to get the same results. For example 2.5 -> 2.5f.

auto does not change the meaning of code when you replace it with the exact type that it gets deduced to. If you replace it with a different type then the meaning of the code is changed.

Title: "auto" keyword affects math calculations?

Body:
No. auto does not directly affect maths. What does affect maths is the type of your variables involved in the calculation.

float inner=2.5;

This is a float initialized by the floating point literal 2.5 which is of type double.

This on the other hand:

auto inner=2.5;

Declares inner to be initialized with the floating point literal 2.5 which is of type double and the type of inner is deduced from the initializer: innter is a double.

Change your floating point literals to float to get the same results. For example 2.5 -> 2.5f.

auto does not change the meaning of code when you replace it with the exact type that it gets deduced to. If you replace it with a different type then the meaning of the code is changed.


问:
Hasura anonymus role permission, API not exposed
I am using Hasura for a project. When I give permission for the public (API exposed for everybody), then no API is exposed in the API section of Hasura. In this case I only X-Hasura-Role public in headers.

But all APIs for role public are exposed when I add x-hasura-admin-secret. For the role public, x-hasura-admin-secret should not be needed. I don't understand what's wrong is doing there?

答: Add HASURA_GRAPHQL_UNAUTHORIZED_ROLE as public in .env environment. If you use Hasura cloud then add it Hasura Env Vars section.


Title: reshape from wide to long, simple data.table issue

Body:
I know there must be a one-line data.table solution for this, probably with dcast, but I can't figure it out.

I have data like this:

library(data.table)
data1 <- data.table(
  id = seq(1:5),
  code = c("A","A","B","A","B"),
  date = as.Date( c("2021-08-11","2021-01-05","2021-02-18","2021-02-13","2021-12-13" ))
)
data2 <- data.table(
  id = seq(1:5),
  code = c("B","B","A","B","A"),
  date = as.Date( c("2021-08-13","2021-01-05","2021-02-19","2021-02-14","2021-12-13" ))
)
data3 <- rbind(data1, data2)

I simply wish to reshape to a wide format like this

data_want <- data.table(
  id = seq(1:5),
  code1 = c("A", "A","B","A","B"),
  data1 = c("2021-08-11", "2021-01-05","2021-02-18","2021-02-13","2021-12-13"),
  code2 = c("B", "B","A","B","A"),
  data2 = c("2021-08-13", "2021-01-05","2021-02-19","2021-02-14","2021-12-13")
)

How to do it with dcast?

Body:
# load package
library(data.table)

# create batch number
data3[, batch := 1:.N, id]

# long to wide
data4 <- dcast(data3
                , id ~ batch
                , value.var = c('code', 'date')
                ); data4

   id code_1 code_2     date_1     date_2
1:  1      A      B 2021-08-11 2021-08-13
2:  2      A      B 2021-01-05 2021-01-05
3:  3      B      A 2021-02-18 2021-02-19
4:  4      A      B 2021-02-13 2021-02-14
5:  5      B      A 2021-12-13 2021-12-13


问:
Adding It function to Cypress fixture
I think I'm missing the point here. The fixture can't be used outside a test but I want to use the 'it' function to test each fixture in a JSON file.

I'm not sure if I understand fixtures correctly or use them correctly at the moment. Here is my Cypress TypeScript code:

```<code>let row: string;
let stream: string;

cy.fixture('AllNotificationStates').then((notifications) => {
  for (let notification in notifications) {
    row = notifications[notification].rowId;
    stream = notifications[notification].streamId;

    it(`${row}`, () => {
      cy.intercept('GET', '**/api/', (req) => {
        req.reply((req) => {
          req.statusCode = 200;
          req.body = [notifications[notification]];
        });
      });
      cy.visit('/notification/dashboard');

      co.setTestId(row);
      co.assertRowIDandStreamID(row, stream);
    });
  }
});
</code>```

答:
You cannot use cy.fixture if you are using it before the it block. Instead you can directly import it and then use it like this.

import notifications from '../fixtures/AllNotificationStates.json'

for (let notification in notifications) {
  let row = notifications[notification].rowId
  let stream = notifications[notification].streamId

  it(`${row}`, () => {
    cy.intercept('GET', '**/api/', (req) => {
      req.reply((req) => {
        req.statusCode = 200
        req.body = [notifications[notification]]
      })
    })
    cy.visit('/notification/dashboard')

    co.setTestId(row)
    co.assertRowIDandStreamID(row, stream)
  })
}
```

Title: Adding It function to Cypress fixture

Body:
I think I'm missing the point here. The fixture can't be used outside a test but I want to use the 'it' function to test each fixture in a JSON file.

I'm not sure if I understand fixtures correctly or use them correctly at the moment. Here is my Cypress TypeScript code:

let row: string;
let stream: string;

cy.fixture('AllNotificationStates').then((notifications) => {
  for (let notification in notifications) {
    row = notifications[notification].rowId;
    stream = notifications[notification].streamId;

    it(`${row}`, () => {
      cy.intercept('GET', '**/api/', (req) => {
        req.reply((req) => {
          req.statusCode = 200;
          req.body = [notifications[notification]];
        });
      });
      cy.visit('/notification/dashboard');

      co.setTestId(row);
      co.assertRowIDandStreamID(row, stream);
    });
  }
});


问:
Qt kerning issue
In my application I'm using a QTextEdit to display some text, using HTML for formatting. The displayed document can be printed. And here's the issue: while on screen the kerning is correct, when printed the document has a very bad looking (mainly: too much space after some letters).

Trying to understand the problem I output the HTML in an external file, and tested it in real browsers. In Chrome there's exactly the same issue, while in Firefox the kerning is correct for printing too. The problem comes definitely from the HTML rendering engine, but I'm not using the QtWebkit module (I haven't even compiled it) which would have explained that the same problem occurs in Chrome.

How can I fix this ?

EDIT

Here's what it looks like:

First the text as it should be rendered (Firefox):

Then what is rendered with Qt/Chrome (particulary noticeable after the M and the p):

答:
Here is a simple workaround,

Use below function and draw your complete QTextEdit Widget on QImage, then print that QImage.

http://doc.qt.io/qt-5/qwidget.html#render

Qt uses different renderer for printing, I think this is an issue related to it.

http://doc.qt.io/qt-5/paintsystem-devices.html

ContentLicense: CC BY-SA 3.0

Title: Qt kerning issue


问:
How to get overlapped rectangular bars in ggplot?
I am trying to create 3 layers of rectangles each with different color on top of each other to get something like below image:

Data:

```<code>library(tidyverse)

df_vaccination <- data.frame(type = c('Population', 'First.Dose.Administered', 'Second.Dose.Administered'),
           count = c(1366400000, 952457943, 734608556))
</code>```

Code tried:

```<code>df_vaccination %>%

  ggplot()+
  geom_rect(aes(xmin = 0, ymin = 0, xmax = count, ymax = 0,
                   size = 10, lineend = 'round',
                   alpha = 0.5, fill = type)) +
  scale_fill_manual(values = c("#d8b365", "orange", "#5ab4ac")) +

  theme_clean() +
  scale_x_continuous(labels = unit_format(scale = 1e-7, unit = "Cr")) +
  guides(color = guide_legend(order = 1),
         size = FALSE,
         alpha = FALSE)
</code>```

Result I am getting is blank plot when I am using geom_rect() & scale_fill_manual(). I am not sure why am I getting blank rectangle:

答:
Convert type column to ordered factor so that largest number plots first, then use geom_col with x = 1. This will make the bars to plot on top of each other, lastly flip the coordinates:

```<code>df_vaccination$type <- factor(df_vaccination$type, levels = df_vaccination$type)

ggplot(df_vaccination, aes(x = 1, y = count, fill = type))+
  geom_col() +
  scale_fill_manual(values = c("#d8b365", "orange", "#5ab4ac")) +
  coord_flip() +
  theme_void()
</code>```

Body:
I am trying to create 3 layers of rectangles each with different color on top of each other to get something like below image:

Data:

library(tidyverse)

df_vaccination <- data.frame(type = c('Population', 'First.Dose.Administered', 'Second.Dose.Administered'),
           count = c(1366400000, 952457943, 734608556))

Code tried:

df_vaccination %>%

  ggplot()+
  geom_rect(aes(xmin = 0, ymin = 0, xmax = count, ymax = 0,
                   size = 10, lineend = 'round',
                   alpha = 0.5, fill = type)) +
  scale_fill_manual(values = c("#d8b365", "orange", "#5ab4ac")) +

  theme_clean() +
  scale_x_continuous(labels = unit_format(scale = 1e-7, unit = "Cr")) +
  guides(color = guide_legend(order = 1),
         size = FALSE,
         alpha = FALSE)

Result I am getting is blank plot when I am using geom_rect() & scale_fill_manual(). I am not sure why am I getting blank rectangle:

Body:
Convert type column to ordered factor so that largest number plots first, then use geom_col with x = 1. This will make the bars to plot on top of each other, lastly flip the coordinates:

df_vaccination$type <- factor(df_vaccination$type, levels = df_vaccination$type)

ggplot(df_vaccination, aes(x = 1, y = count, fill = type))+
  geom_col() +
  scale_fill_manual(values = c("#d8b365", "orange", "#5ab4ac")) +
  coord_flip() +
  theme_void()


问:
Program to find from where the program is called
The requirement is very simple, I want to write a simple hello world program or anything so the program knows about its execution parent. For eg.

Since I am from a Java background I will give a Java example. I want to write a jar that runs and outputs the following:

Running from command line:

```<code>$ java -jar myjar.jar
Hello world called from bash
</code>```

but when running from myscript.sh:

```<code>$ sh myscript.sh
Hello world called from myscript.sh
</code>```

myscript.sh

```<code>#!/bin/bash
#
# runs the jar
java -jar myjar.jar
</code>```

Now, I am language agnostic regarding this so any language/library that can help me achieve this is welcome, the only requirement is it should be able to be called from a bash script and should recognize the script that calls it.

Every idea is welcomed.

答:
You can achieve it in python like this:

Basically it should be same, be it any programming language. You need to get the parent process ID and name of the process associated with it. If you use Java program, I guess you can achieve the same there also.

I named the python script as test.py and shell script as test.sh

test.py

```<code>import os
import psutil

ppid = os.getppid()
process_name = psutil.Process(ppid).name()

print("Parent process ID of current process is:", ppid)
print("The parent process name is: ", process_name)
</code>```

test.sh

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

python test.py
</code>```

Output:

```<code>python test.py
('Parent process ID of current process is:', 14866)
('The parent process name is: ', 'bash')

./test.sh
('Parent process ID of current process is:', 15382)
('The parent process name is: ', 'test.sh')
</code>```

Body:
The requirement is very simple, I want to write a simple hello world program or anything so the program knows about its execution parent. For eg.

Since I am from a Java background I will give a Java example. I want to write a jar that runs and outputs the following:

Running from command line:

$ java -jar myjar.jar
Hello world called from bash

but when running from myscript.sh:

$ sh myscript.sh
Hello world called from myscript.sh

myscript.sh

#!/bin/bash
#
# runs the jar
java -jar myjar.jar

Now, I am language agnostic regarding this so any language/library that can help me achieve this is welcome, the only requirement is it should be able to be called from a bash script and should recognize the script that calls it.

Every idea is welcomed.

Body:
You can achieve it in python like this:

Basically it should be same, be it any programming language. You need to get the parent process ID and name of the process associated with it. If you use Java program, I guess you can achieve the same there also.

I named the python script as test.py and shell script as test.sh

test.py

import os
import psutil

ppid = os.getppid()
process_name = psutil.Process(ppid).name()

print("Parent process ID of current process is:", ppid)
print("The parent process name is: ", process_name)

test.sh

#!/bin/bash

python test.py

Output:

python test.py
('Parent process ID of current process is:', 14866)
('The parent process name is: ', 'bash')

./test.sh
('Parent process ID of current process is:', 15382)
('The parent process name is: ', 'test.sh')


问:
can i change the column names to the top in PHEATMAP
I am using PHEATMAP to generate a heatmap - currently the row names and column names defaults to left and bottom - can somebody point me to option where i can change it to RIGHT and TOP.</p>

答:
Unfortunately, you must use ComplexHeatmap - I'm aware OP cannot use CH but posterity for others:

```<code>library(pheatmap)
pheatmap(plot_mat, cluster_rows = T, cluster_cols = F,
         display_numbers = T, cutree_rows = 3,
         color = hcl.colors(50, "sunsetdark", rev=F),
         border_color = "black", number_color = "black",
         fontsize_number = 9, angle_col = 0)
</code>```

```<code>library(ComplexHeatmap)
ComplexHeatmap::pheatmap(plot_mat, cluster_rows = T, cluster_cols = F,
                         display_numbers = T, cutree_rows = 3,
                         color = hcl.colors(50, "sunsetdark", rev=F),
                         border_color = "black", number_color = "black",
                         fontsize_number = 9, column_names_side = c("top"),
                         angle_col = c("0"))
</code>```

Body:
Unfortunately, you must use ComplexHeatmap - I'm aware OP cannot use CH but posterity for others:

library(pheatmap)
pheatmap(plot_mat, cluster_rows = T, cluster_cols = F,
         display_numbers = T, cutree_rows = 3,
         color = hcl.colors(50, "sunsetdark", rev=F),
         border_color = "black", number_color = "black",
         fontsize_number = 9, angle_col = 0)

library(ComplexHeatmap)
ComplexHeatmap::pheatmap(plot_mat, cluster_rows = T, cluster_cols = F,
                         display_numbers = T, cutree_rows = 3,
                         color = hcl.colors(50, "sunsetdark", rev=F),
                         border_color = "black", number_color = "black",
                         fontsize_number = 9, column_names_side = c("top"),
                         angle_col = c("0"))


问:
getting binary format for displaying image in datagridview
i am currently facing some problem retrieving image for display on a datagridview control.
The Image data type in the database  is blob.
 I am using mysql as a database for retrieving the image . may i ask if it is possible to just retrieve a image data of this format and display in the gridview? or do i need to store the image in a image folder for retrieval?

I am using winforms application

答: Don't really think it's possible to figure out EXACT  format of the image from its binary stream. The only solution I met, is storing the format in DB too, or have architectual convension to store in DB only one format type images.</p>


问:
Could not find artifact org.apache.flink:flink-table:jar:1.14.3 in MavenCentral (https://repo1.maven.org/maven2)
I am trying to add Flink Table dependency in my POM.xml file and the following is the dependency.

```<code><dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-table</artifactId>
        <version>${flink.version}</version>
        <scope>provided</scope>
    </dependency>
</code>```

This throws the error Could not find artifact org.apache.flink:flink-table:jar:1.14.3 in MavenCentral (https://repo1.maven.org/maven2)

My flink version is 1.14.3

Below is my full pom

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.amazonaws</groupId>
<artifactId>SlidingWindowDeviceStatusJob3</artifactId>
<version>1.2</version>
<packaging>jar</packaging>
<properties>
    <java.version>1.8</java.version>
    <scala.binary.version>2.12</scala.binary.version>
    <flink.version>1.14.3</flink.version>
    <kda.version>2.0.0</kda.version>
    <kda.runtime.version>1.2.0</kda.runtime.version>
    <avcms.tlvcodec.version>2.2.1</avcms.tlvcodec.version>

</properties>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.7</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-bom</artifactId>
            <!-- Get the latest SDK version from https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-bom -->
            <version>1.11.903</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-kinesisanalytics-runtime</artifactId>
        <version>${kda.runtime.version}</version>
    </dependency>

    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-connector-kinesis_${scala.binary.version}</artifactId>
        <version>${flink.version}</version>
    </dependency>

    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-streaming-java_${scala.binary.version}</artifactId>
        <version>${flink.version}</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-kinesisanalytics-flink</artifactId>
        <version>${kda.version}</version>
    </dependency>

    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-java-sdk-logs</artifactId>
        <!-- scope>compile</scope -->
    </dependency>

    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-table</artifactId>
        <version>${flink.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-streaming-scala_${scala.binary.version}</artifactId>
        <version>${flink.version}</version>
    </dependency>

</dependencies>

<build>

<plugins>

<!-- Java Compiler -->
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.1</version>
    <configuration>
        <source>${java.version}</source>
        <target>${java.version}</target>
    </configuration>
</plugin>
<!-- We use the maven-shade plugin to create a fat jar that contains all necessary dependencies. -->
<!-- Change the value of <mainClass>...</mainClass> if your program entry point changes. -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.1</version>
<executions>
<!-- Run shade goal on package phase -->
<execution>
<phase>package</phase>
<goals>
    <goal>shade</goal>
</goals>
<configuration>
<artifactSet>
    <excludes>
        <exclude>org.apache.flink:force-shading</exclude>
        <exclude>com.google.code.findbugs:jsr305</exclude>
        <exclude>org.slf4j:*</exclude>
        <exclude>log4j:*</exclude>
    </excludes>
</artifactSet>
<filters>
<filter>
<!-- Do not copy the signatures in the META-INF folder.
Otherwise, this might cause SecurityExceptions when using the JAR. -->
<artifact>*:*</artifact>
<excludes>
    <exclude>META-INF/*.SF</exclude>
    <exclude>META-INF/*.DSA</exclude>
    <exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
    <transformers>
        <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
            <mainClass>com.amazonaws.services.kinesisanalytics.devicestatus.SlidingWindowDeviceStatusJob3</mainClass>
        </transformer>
    </transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</code>```

Please help me resolve this issue.

答: To use the Table API you need flink-table-api-java, plus flink-table-api-scala_2.12 if you are using scala. If you are also using the DataStream API then you'll also need flink-table-api-java-bridge and perhaps flink-table-api-scala-bridge_2.12.

Body:
I am trying to add Flink Table dependency in my POM.xml file and the following is the dependency.

<dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-table</artifactId>
        <version>${flink.version}</version>
        <scope>provided</scope>
    </dependency>

This throws the error Could not find artifact org.apache.flink:flink-table:jar:1.14.3 in MavenCentral (https://repo1.maven.org/maven2)

My flink version is 1.14.3

Below is my full pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.amazonaws</groupId>
<artifactId>SlidingWindowDeviceStatusJob3</artifactId>
<version>1.2</version>
<packaging>jar</packaging>
<properties>
    <java.version>1.8</java.version>
    <scala.binary.version>2.12</scala.binary.version>
    <flink.version>1.14.3</flink.version>
    <kda.version>2.0.0</kda.version>
    <kda.runtime.version>1.2.0</kda.runtime.version>
    <avcms.tlvcodec.version>2.2.1</avcms.tlvcodec.version>

</properties>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.7</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-bom</artifactId>

            <version>1.11.903</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-kinesisanalytics-runtime</artifactId>
        <version>${kda.runtime.version}</version>
    </dependency>

    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-connector-kinesis_${scala.binary.version}</artifactId>
        <version>${flink.version}</version>
    </dependency>

    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-streaming-java_${scala.binary.version}</artifactId>
        <version>${flink.version}</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-kinesisanalytics-flink</artifactId>
        <version>${kda.version}</version>
    </dependency>

    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-java-sdk-logs</artifactId>

    </dependency>

    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-table</artifactId>
        <version>${flink.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-streaming-scala_${scala.binary.version}</artifactId>
        <version>${flink.version}</version>
    </dependency>

</dependencies>

<build>

<plugins>

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.1</version>
    <configuration>
        <source>${java.version}</source>
        <target>${java.version}</target>
    </configuration>
</plugin>

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.1</version>
<executions>

<execution>
<phase>package</phase>
<goals>
    <goal>shade</goal>
</goals>
<configuration>
<artifactSet>
    <excludes>
        <exclude>org.apache.flink:force-shading</exclude>
        <exclude>com.google.code.findbugs:jsr305</exclude>
        <exclude>org.slf4j:*</exclude>
        <exclude>log4j:*</exclude>
    </excludes>
</artifactSet>
<filters>
<filter>

<artifact>*:*</artifact>
<excludes>
    <exclude>META-INF/*.SF</exclude>
    <exclude>META-INF/*.DSA</exclude>
    <exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
    <transformers>
        <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
            <mainClass>com.amazonaws.services.kinesisanalytics.devicestatus.SlidingWindowDeviceStatusJob3</mainClass>
        </transformer>
    </transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>

Please help me resolve this issue.


问:
Communication between two networks over file share
My problem is that I have two computers in different networks which can "communicate" only over a common file share mounted on both systems (typically Windows SMB server on third-party host). All other ports are blocked! I would like to use this file share for a direct communication between these two machines. I'm root on both machines, it's possible to use Windows or Linux on them. There is also no need to use SSH for the communication, 'netcat' or other command-line oriented tools are available.

What has been done so far to solve it: I started a (long ;-) discussion about tunneling SSH, which is on hold now, SSH: TCP-over-File?, but includes many valuable information (especially from Ch. Duffy et al.). I have understood that SSH is not suitable for that, but the question, if this Windows tunneling tool could by useful, is still open: https://labs.mwrinfosecurity.com/tools/tcp-over-file-tunnel/

How to establish a communication using common tools coming with the operating systems (Ubuntu or Windows 7) in this case?

答: If You have ssh connection from your workstation to both servers - just use putty for tunneling or something like that.</p>


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

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

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

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

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

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

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

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

void BM_predict(benchmark::State& state)
{

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

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

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

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

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

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

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

答:
Adding to the list:

Given the case that A and B are totally unpredictable, but usually A||B is true (i.e. when A is wrong, then usually B is true and vice versa).
In this case A||B may lead to a lot of mispredictions, but A|B is predictable and most likely faster.

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

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

void BM_misspredict(benchmark::State& state)
{

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

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

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

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

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

void BM_predict(benchmark::State& state)
{

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

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

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

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

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

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

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


问:
Using javascript navigate to a page and also send querystring?
I want to navigate from page1.html to page2.html and at the same time adding querystring in URL using javascript.

I tried:

```<code>window.location.href = 'page2.html?uname=mustafa';
</code>```

It does navigate to page2.html but "?uname=mustafa" is not added in URL.
So am unable to parse querystring on page2. How can I achieve it?

答:
try this

```<code>window.location = `addUser.html?userId=${userId}`;
</code>```

here userId is a parameter and ${userId} is variable value

Body:
I want to navigate from page1.html to page2.html and at the same time adding querystring in URL using javascript.

I tried:

window.location.href = 'page2.html?uname=mustafa';

It does navigate to page2.html but "?uname=mustafa" is not added in URL.
So am unable to parse querystring on page2. How can I achieve it?

Body:
try this

window.location = `addUser.html?userId=${userId}`;

here userId is a parameter and ${userId} is variable value


问:
Function can't be displayed in second canvas within p5.js
I created two separate canvases with p5.js by creating a new instance (see line 58 in my javascript file). Then I inserted a function called "firstAnimation" that will be displayed in one of the canvases.

Run the code here --> https://editor.p5js.org/MaximilianFreitag/sketches/fP46XAHnP

In line 45 of my javascript file p5.js is telling me that my function "secondAnimation" does not exist. So I can not output another animation in this canvas

In line 49 I can still draw a circle inside the second canvas with sketch.circle(100,100,100).

How can I display my second function in the second canvas so that I have two animations?

I can only add a simple circle

答: You nead to specify where to draw a line. in second function just add  myp5.line and just run function secondAnimation() without sketch.


问:
Serializing WITHOUT xmlns
I have a couple extension methods that handle serialization of my classes, and since it can be a time consuming process, they are created once per class, and handed out by this method.

```<code>public static XmlSerializer GetSerializerFor(Type typeOfT)
{
    if (!serializers.ContainsKey(typeOfT))
    {
        var xmlAttributes = new XmlAttributes();
        var xmlAttributeOverrides = new XmlAttributeOverrides();

        System.Diagnostics.Debug.WriteLine(string.Format("XmlSerializerFactory.GetSerializerFor(typeof({0}));", typeOfT));

        xmlAttributes.Xmlns = false;
        xmlAttributeOverrides.Add(typeOfT, xmlAttributes);

        var newSerializer = new XmlSerializer(typeOfT, xmlAttributeOverrides);
        serializers.Add(typeOfT, newSerializer);
    }

    return serializers[typeOfT];
}
</code>```

This is called by the extension method .Serialize()

```<code>public static XElement Serialize(this object source)
{
    try
    {
        var serializer = XmlSerializerFactory.GetSerializerFor(source.GetType());
        var xdoc = new XDocument();
        using (var writer = xdoc.CreateWriter())
        {
            serializer.Serialize(writer, source, new XmlSerializerNamespaces(new[] { new XmlQualifiedName("", "") }));
        }

        return (xdoc.Document != null) ? xdoc.Document.Root : new XElement("Error", "Document Missing");
    }
    catch (Exception x)
    {
        return new XElement("Error", x.ToString());
    }
}
</code>```

Unfortunately, when Serializing classes that are auto-generated, they have the attribute XmlTypeAttribute(Namespace="http://tempuri.org/") applied to them.

This causes the deserialization by the the non-auto-generated counterparts to fail.

I need the serializer to completely ignore and not apply the namespace, but what I have written in the first block of code doesn't seem to remove it, I still end up with xml like this

```<code><Note>
  <ID xmlns="http://tempuri.org/">12</ID>
  <Author xmlns="http://tempuri.org/">
    <ID>1234</ID>
    <Type>Associate</Type>
    <IsAvailable>false</IsAvailable>
  </Author>
  <Created xmlns="http://tempuri.org/">2010-06-22T09:38:01.5024351-05:00</Created>
  <Text xmlns="http://tempuri.org/">This is an update</Text>
</Note>
</code>```

Instead of the same, minus the xmlns="http://tempuri.org/" attribute.

Please help, thanks, this is driving me crazy!

EDIT:

I know the problem, just not how to fix it.

My class, isn't just full of simple types.

It contains properties with types of other classes.  Which are also auto-generated with the XmlTypeAttribute(Namespace = "http://tempuri.org/") attribute.  So what is happening, is that when serialization occurs, and it serializes the properties of my class, they aren't going through my custom serialization, and thus, are having the attribute applied and not overridden.

Now I just need to figure out how to jump that hoop.  Any thoughts as to how?

EDIT 2:

The following works to serialize WITHOUT xmlns... but I'm having a problem on the deserialization end, just not yet sure if it's related or not

```<code>public static XmlSerializer GetSerializerFor(Type typeOfT)
{
    if (!serializers.ContainsKey(typeOfT))
    {
        var xmlAttributes = new XmlAttributes();
        var xmlAttributeOverrides = new XmlAttributeOverrides();

        System.Diagnostics.Debug.WriteLine(string.Format("XmlSerializerFactory.GetSerializerFor(typeof({0}));", typeOfT));

        xmlAttributes.XmlType = new XmlTypeAttribute
        {
            Namespace = ""
        };

        xmlAttributes.Xmlns = false;

        var types = new List<Type> {typeOfT, typeOfT.BaseType};

        foreach (var property in typeOfT.GetProperties())
        {
            types.Add(property.PropertyType);
        }

        types.RemoveAll(t => t.ToString().StartsWith("System."));

        foreach (var type in types)
        {
            xmlAttributeOverrides.Add(type, xmlAttributes);
        }

        var newSerializer = new XmlSerializer(typeOfT, xmlAttributeOverrides);
        //var newSerializer = new XmlSerializer(typeOfT, xmlAttributeOverrides, extraTypes.ToArray(), new XmlRootAttribute(), string.Empty);
        //var newSerializer = new XmlSerializer(typeOfT, string.Empty);

        serializers.Add(typeOfT, newSerializer);
    }

    return serializers[typeOfT];
}
</code>```

EDIT3:
Ended up using solution from
How to remove all namespaces from XML with C#?

```<code>public static XElement RemoveAllNamespaces(this XElement source)
{
    return !source.HasElements
               ? new XElement(source.Name.LocalName)
                     {
                         Value = source.Value
                     }
               : new XElement(source.Name.LocalName, source.Elements().Select(el => RemoveAllNamespaces(el)));
}
</code>```

答:
Working solution (without empty xmlns attribute):</p>
```<code>var ns = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
XmlSerializer serializer = new XmlSerializer(typeof(XmlInfo));
XmlDocument doc = new XmlDocument();
using (var ms = new MemoryStream()) {
    serializer.Serialize(ms, this, ns);
    ms.Position = 0;
    doc.Load(ms);
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Serializing WITHOUT xmlns

Body:
I have a couple extension methods that handle serialization of my classes, and since it can be a time consuming process, they are created once per class, and handed out by this method.

public static XmlSerializer GetSerializerFor(Type typeOfT)
{
    if (!serializers.ContainsKey(typeOfT))
    {
        var xmlAttributes = new XmlAttributes();
        var xmlAttributeOverrides = new XmlAttributeOverrides();

        System.Diagnostics.Debug.WriteLine(string.Format("XmlSerializerFactory.GetSerializerFor(typeof({0}));", typeOfT));

        xmlAttributes.Xmlns = false;
        xmlAttributeOverrides.Add(typeOfT, xmlAttributes);

        var newSerializer = new XmlSerializer(typeOfT, xmlAttributeOverrides);
        serializers.Add(typeOfT, newSerializer);
    }

    return serializers[typeOfT];
}

This is called by the extension method .Serialize()

public static XElement Serialize(this object source)
{
    try
    {
        var serializer = XmlSerializerFactory.GetSerializerFor(source.GetType());
        var xdoc = new XDocument();
        using (var writer = xdoc.CreateWriter())
        {
            serializer.Serialize(writer, source, new XmlSerializerNamespaces(new[] { new XmlQualifiedName("", "") }));
        }

        return (xdoc.Document != null) ? xdoc.Document.Root : new XElement("Error", "Document Missing");
    }
    catch (Exception x)
    {
        return new XElement("Error", x.ToString());
    }
}

Unfortunately, when Serializing classes that are auto-generated, they have the attribute XmlTypeAttribute(Namespace="http://tempuri.org/") applied to them.

This causes the deserialization by the the non-auto-generated counterparts to fail.

I need the serializer to completely ignore and not apply the namespace, but what I have written in the first block of code doesn't seem to remove it, I still end up with xml like this

<Note>
  <ID xmlns="http://tempuri.org/">12</ID>
  <Author xmlns="http://tempuri.org/">
    <ID>1234</ID>
    <Type>Associate</Type>
    <IsAvailable>false</IsAvailable>
  </Author>
  <Created xmlns="http://tempuri.org/">2010-06-22T09:38:01.5024351-05:00</Created>
  <Text xmlns="http://tempuri.org/">This is an update</Text>
</Note>

Instead of the same, minus the xmlns="http://tempuri.org/" attribute.

Please help, thanks, this is driving me crazy!

EDIT:

I know the problem, just not how to fix it.

My class, isn't just full of simple types.

It contains properties with types of other classes.  Which are also auto-generated with the XmlTypeAttribute(Namespace = "http://tempuri.org/") attribute.  So what is happening, is that when serialization occurs, and it serializes the properties of my class, they aren't going through my custom serialization, and thus, are having the attribute applied and not overridden.

Now I just need to figure out how to jump that hoop.  Any thoughts as to how?

EDIT 2:

The following works to serialize WITHOUT xmlns... but I'm having a problem on the deserialization end, just not yet sure if it's related or not

public static XmlSerializer GetSerializerFor(Type typeOfT)
{
    if (!serializers.ContainsKey(typeOfT))
    {
        var xmlAttributes = new XmlAttributes();
        var xmlAttributeOverrides = new XmlAttributeOverrides();

        System.Diagnostics.Debug.WriteLine(string.Format("XmlSerializerFactory.GetSerializerFor(typeof({0}));", typeOfT));

        xmlAttributes.XmlType = new XmlTypeAttribute
        {
            Namespace = ""
        };

        xmlAttributes.Xmlns = false;

        var types = new List<Type> {typeOfT, typeOfT.BaseType};

        foreach (var property in typeOfT.GetProperties())
        {
            types.Add(property.PropertyType);
        }

        types.RemoveAll(t => t.ToString().StartsWith("System."));

        foreach (var type in types)
        {
            xmlAttributeOverrides.Add(type, xmlAttributes);
        }

        var newSerializer = new XmlSerializer(typeOfT, xmlAttributeOverrides);
        //var newSerializer = new XmlSerializer(typeOfT, xmlAttributeOverrides, extraTypes.ToArray(), new XmlRootAttribute(), string.Empty);
        //var newSerializer = new XmlSerializer(typeOfT, string.Empty);

        serializers.Add(typeOfT, newSerializer);
    }

    return serializers[typeOfT];
}

EDIT3:
Ended up using solution from
How to remove all namespaces from XML with C#?

public static XElement RemoveAllNamespaces(this XElement source)
{
    return !source.HasElements
               ? new XElement(source.Name.LocalName)
                     {
                         Value = source.Value
                     }
               : new XElement(source.Name.LocalName, source.Elements().Select(el => RemoveAllNamespaces(el)));
}

Body:
Working solution (without empty xmlns attribute):

var ns = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
XmlSerializer serializer = new XmlSerializer(typeof(XmlInfo));
XmlDocument doc = new XmlDocument();
using (var ms = new MemoryStream()) {
    serializer.Serialize(ms, this, ns);
    ms.Position = 0;
    doc.Load(ms);
}


问:
Office 365 SMTP starts firing net_io_connectionclosed
A while ago I've configured my ASP.NET C# project to send e-mail via Office 365, but last week it's starting to throw a lot of exceptions.

```<code>System.IO.IOException: Unable to read data from the transport connection: net_io_connectionclosed.
at System.Net.Mail.SmtpReplyReaderFactory.ProcessRead(Byte[] buffer, Int32 offset, Int32 read, Boolean readLine)
at System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader caller, Boolean oneLine)
at System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader caller)
at System.Net.Mail.CheckCommand.Send(SmtpConnection conn, String& response)
at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& exception)
at System.Net.Mail.SmtpClient.Send(MailMessage message)
</code>```

How can I prevent this from happening?

```<code>  MailMessage message = new MailMessage(System.Configuration.ConfigurationManager.AppSettings["smtpfrom"], email, strOnderwerp, strBody);
            message.Priority = MailPriority.Normal;
            message.IsBodyHtml = true;
            SmtpClient client = new SmtpClient(System.Configuration.ConfigurationManager.AppSettings["smtpserver"], Convert.ToInt32((System.Configuration.ConfigurationManager.AppSettings["smtpport"])));

            client.EnableSsl = Boolean.Parse(System.Configuration.ConfigurationManager.AppSettings["smtpssl"]); ;
            client.Credentials = new System.Net.NetworkCredential(System.Configuration.ConfigurationManager.AppSettings["smtpuser"], System.Configuration.ConfigurationManager.AppSettings["smtppass"]);

            client.Send(message);
            client.Dispose();
</code>```

The exceptions seems to be thrown on the Dispose.

答:
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

this worked for me

Body:
A while ago I've configured my ASP.NET C# project to send e-mail via Office 365, but last week it's starting to throw a lot of exceptions.

System.IO.IOException: Unable to read data from the transport connection: net_io_connectionclosed.
at System.Net.Mail.SmtpReplyReaderFactory.ProcessRead(Byte[] buffer, Int32 offset, Int32 read, Boolean readLine)
at System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader caller, Boolean oneLine)
at System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader caller)
at System.Net.Mail.CheckCommand.Send(SmtpConnection conn, String& response)
at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& exception)
at System.Net.Mail.SmtpClient.Send(MailMessage message)

How can I prevent this from happening?

  MailMessage message = new MailMessage(System.Configuration.ConfigurationManager.AppSettings["smtpfrom"], email, strOnderwerp, strBody);
            message.Priority = MailPriority.Normal;
            message.IsBodyHtml = true;
            SmtpClient client = new SmtpClient(System.Configuration.ConfigurationManager.AppSettings["smtpserver"], Convert.ToInt32((System.Configuration.ConfigurationManager.AppSettings["smtpport"])));

            client.EnableSsl = Boolean.Parse(System.Configuration.ConfigurationManager.AppSettings["smtpssl"]); ;
            client.Credentials = new System.Net.NetworkCredential(System.Configuration.ConfigurationManager.AppSettings["smtpuser"], System.Configuration.ConfigurationManager.AppSettings["smtppass"]);

            client.Send(message);
            client.Dispose();

The exceptions seems to be thrown on the Dispose.


问:
How can I get COUNT to work in this query
so my goal here is to either return a 1 or a 0. I want it to return a 1 if these 2 processes have ran at the same time and a 0 if they haven't. So far, my query is able to identify if the processes had ran together, but I get an error when I try to use COUNT.

```<code>SELECT T1.*, T2.*
FROM(
SELECT STRT_TM, END_TM
FROM TIME_TBL
WHERE PROC_NAME = 'PROC_1'
) T1
JOIN (
SELECT STRT_TM, END_TM
FROM TIME_TBL
WHERE PROC_NAME = 'PROC_2'
) T2
ON T1.STRT_TM BETWEEN T2.STRT_TM AND T2.END_TM OR T2.STRT_TM BETWEEN T1.STRT_TM AND T1.END_TM
LIMIT 1
</code>```

Any help is much appreciated.

答:
For whatever subselect:</p>
```<code>SELECT CASE WHEN COUNT (1) = 0 THEN 0 ELSE 1 END
FROM
(
  <YOUR_SUBSELECT_AS_IS_GOES_HERE>
) T
</code>```

Body:
so my goal here is to either return a 1 or a 0. I want it to return a 1 if these 2 processes have ran at the same time and a 0 if they haven't. So far, my query is able to identify if the processes had ran together, but I get an error when I try to use COUNT.

SELECT T1.*, T2.*
FROM(
SELECT STRT_TM, END_TM
FROM TIME_TBL
WHERE PROC_NAME = 'PROC_1'
) T1
JOIN (
SELECT STRT_TM, END_TM
FROM TIME_TBL
WHERE PROC_NAME = 'PROC_2'
) T2
ON T1.STRT_TM BETWEEN T2.STRT_TM AND T2.END_TM OR T2.STRT_TM BETWEEN T1.STRT_TM AND T1.END_TM
LIMIT 1

Any help is much appreciated.

Body:
For whatever subselect:

SELECT CASE WHEN COUNT (1) = 0 THEN 0 ELSE 1 END
FROM
(
  <YOUR_SUBSELECT_AS_IS_GOES_HERE>
) T


问:
to get a list of bools, .contain()
how do i do a list for bools in javascript. im doing a validation so i can have a list of bools and at the end i want to check that list if it contains any errors. im not sure how to add to the varable validations_errors (like a list). Plus i dont know how i can check if that list contains any true values.

what i got so far is this

```<code>var validation_errors;

            if (!validateForm($(this))) {
                validation_errors = false; //here i want to add the it to a list
                var $input_container = $(this).parents('.input');
                $input_container.removeClass('success').addClass('error');
            }

    //this is something what i want to do like (this code is c# based)
    if (validation_errors.contains(true)){
    // do some actions
    }
</code>```

EDIT

list of bools = list of true & false

答:
validation_errors = []; // DECLARATION

validation_errors.push( newBool ); // adding a new val to the array.

And then you can regularly iterate through the array at the end.

If I were you though, I would try something like this...

validation_errors = false; // declaration

Within the loop

If ( !newBool ) validation_errors = true;

And at the end

If( validation_errors ) //we failed

So you won't need a whole array and a second loop.

Edit : cellphone typing

Title: to get a list of bools, .contain()

Body:
how do i do a list for bools in javascript. im doing a validation so i can have a list of bools and at the end i want to check that list if it contains any errors. im not sure how to add to the varable validations_errors (like a list). Plus i dont know how i can check if that list contains any true values.

what i got so far is this

var validation_errors;

            if (!validateForm($(this))) {
                validation_errors = false; //here i want to add the it to a list
                var $input_container = $(this).parents('.input');
                $input_container.removeClass('success').addClass('error');
            }

    //this is something what i want to do like (this code is c# based)
    if (validation_errors.contains(true)){
    // do some actions
    }

EDIT

list of bools = list of true & false


问:
Illegal byte sequence zipro W 10-02 23:01:47 10808 9104 Error opening archive T:\my_app\build\app\outputs\flutter-apk\app.apk: I/O error ERROR: dump
I have created this project before and I'm trying to run it again but I am getting the following error(s) :

Error Log:

```<code>Launching lib\main.dart on AOSP on IA Emulator in debug mode...
lib\main.dart:1
√  Built build\app\outputs\flutter-apk\app-debug.apk.
ziparchive W 10-02 23:01:47 10808  9104 Unable to open 'T:my_ap\build\app\outputs\flutter-apk\app.apk': Illegal byte sequence
zipro W 10-02 23:01:47 10808  9104 Error opening archive T:\my_app\build\app\outputs\flutter-apk\app.apk: I/O error
ERROR: dump failed because resource AndroidManifest.xml not found
Failed to extract manifest from APK: ProcessException: The command failed
  Command: C:\Users\cordt\AppData\Local\Android\sdk\build-tools\30.0.3\aapt dump xmltree T:\batí\Mail\projects\shop_app_3\build\app\outputs\flutter-apk\app.apk AndroidManifest.xml.
Exception: Problem building Android application: see above error(s).
Exited (sigterm)
</code>```

I have tried flutter clean but it didn't help me.

答:
I came across a similar problem on an app I've been working on, the key takeaway is that this happened immediately after I update to the latest version of My flutter SDK. These are the steps I followed to solve this problem.

flutter create .

flutter clean

flutter pub get

flutter run

Body:
I have created this project before and I'm trying to run it again but I am getting the following error(s) :

Error Log:

Launching lib\main.dart on AOSP on IA Emulator in debug mode...
lib\main.dart:1
√  Built build\app\outputs\flutter-apk\app-debug.apk.
ziparchive W 10-02 23:01:47 10808  9104 Unable to open 'T:my_ap\build\app\outputs\flutter-apk\app.apk': Illegal byte sequence
zipro W 10-02 23:01:47 10808  9104 Error opening archive T:\my_app\build\app\outputs\flutter-apk\app.apk: I/O error
ERROR: dump failed because resource AndroidManifest.xml not found
Failed to extract manifest from APK: ProcessException: The command failed
  Command: C:\Users\cordt\AppData\Local\Android\sdk\build-tools\30.0.3\aapt dump xmltree T:\batí\Mail\projects\shop_app_3\build\app\outputs\flutter-apk\app.apk AndroidManifest.xml.
Exception: Problem building Android application: see above error(s).
Exited (sigterm)

I have tried flutter clean but it didn't help me.


问:
attaching binary file to an event in cumulocity
I have a scenario where in my code creates a file and an event in cumulocity as well. I need to attach the binary file to the event, however none of the API's provide me the functionality, any guidance as to how to go ahead please?

Update:

On having a look at the documentation https://cumulocity.com/api/10.11.0/#tag/Attachments , the binaryElement has a following structure

I have modified my JAVA code in the following manner:

```<code>String pathEvent = platform.getUrl().get()+"/event/events/{{eventId}}/binaries";
    String pathEventAttachment = pathEvent.replace("{{eventId}}", event.getId().getValue());

    HttpHeaders headers = RequestAuthenticationEncoder.encode(getCredentials());
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
    MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
    map.add("file",new ByteArrayResource(FileUtils.readFileToByteArray(file)));//anychanges here fails the code
    map.add("filename", file.getName().getBytes());

    HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(map,headers);
    restTemplate.postForObject(pathEventAttachment, request, String.class);
    log.info("Binary file added to the event {}", event.getId().getValue());
</code>```

Binary is created for the event, however the filename is incorrect:

Please let me know some insights as to why the name is not changing?

答:
You need to create a POST on /event/events/{{eventId}}/binaries with the appropriate Content-Type and body.

Here is a code snippet in python where a binary (log file) is attached to an event. It just POSTs the file content (bytes) as application/octet-stream

```<code># Create event
logfileEvent = {
    'type': 'c8y_Logfile',
    'text': 'See attached logfile',
    'time': datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z',
    'source': {
        'id': DEVICE_ID
    }
}
res = client.post(C8Y_BASE + '/event/events/', data=json.dumps(logfileEvent))
eventId = res.json()['id']

# Attach Binary
res = client.post(C8Y_BASE + '/event/events/' + eventId + '/binaries', data=bytes(FILE_CONTENT, 'utf-8'), headers={'Content-Type': 'application/octet-stream'})
binaryRef = res.json()['self']

# Update operation
logfileFragment = logfileOperation['c8y_LogfileRequest']
logfileFragment['file'] = binaryRef
updatedOperation = {
    'status': 'SUCCESSFUL',
    'c8y_LogfileRequest': logfileFragment
}
client.put(C8Y_BASE + '/devicecontrol/operations/' + logfileOperation['id'], data=json.dumps(updatedOperation))
</code>```

Body:
I have a scenario where in my code creates a file and an event in cumulocity as well. I need to attach the binary file to the event, however none of the API's provide me the functionality, any guidance as to how to go ahead please?

Update:

On having a look at the documentation https://cumulocity.com/api/10.11.0/#tag/Attachments , the binaryElement has a following structure

I have modified my JAVA code in the following manner:

String pathEvent = platform.getUrl().get()+"/event/events/{{eventId}}/binaries";
    String pathEventAttachment = pathEvent.replace("{{eventId}}", event.getId().getValue());

    HttpHeaders headers = RequestAuthenticationEncoder.encode(getCredentials());
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
    MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
    map.add("file",new ByteArrayResource(FileUtils.readFileToByteArray(file)));//anychanges here fails the code
    map.add("filename", file.getName().getBytes());

    HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(map,headers);
    restTemplate.postForObject(pathEventAttachment, request, String.class);
    log.info("Binary file added to the event {}", event.getId().getValue());

Binary is created for the event, however the filename is incorrect:

Please let me know some insights as to why the name is not changing?

Body:
You need to create a POST on /event/events/{{eventId}}/binaries with the appropriate Content-Type and body.

Here is a code snippet in python where a binary (log file) is attached to an event. It just POSTs the file content (bytes) as application/octet-stream

# Create event
logfileEvent = {
    'type': 'c8y_Logfile',
    'text': 'See attached logfile',
    'time': datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z',
    'source': {
        'id': DEVICE_ID
    }
}
res = client.post(C8Y_BASE + '/event/events/', data=json.dumps(logfileEvent))
eventId = res.json()['id']

# Attach Binary
res = client.post(C8Y_BASE + '/event/events/' + eventId + '/binaries', data=bytes(FILE_CONTENT, 'utf-8'), headers={'Content-Type': 'application/octet-stream'})
binaryRef = res.json()['self']

# Update operation
logfileFragment = logfileOperation['c8y_LogfileRequest']
logfileFragment['file'] = binaryRef
updatedOperation = {
    'status': 'SUCCESSFUL',
    'c8y_LogfileRequest': logfileFragment
}
client.put(C8Y_BASE + '/devicecontrol/operations/' + logfileOperation['id'], data=json.dumps(updatedOperation))


问:
How to skip a line every two lines starting by skipping the first line?
Here's my code : ls -lt | sed -n 'p;n'

That code makes me skip from a line to another when listing file names but doesn't start by skipping the first one, how to make that happen?

Here's an exemple without my code to skip to make it clear:

And here's an exemple of when I use the skip code:

答:
You have to invert your sed command: it should be n;p instead of p;n:

Your code:

for x in {1..20}; do echo $x ; done | sed -n 'p;n'
```
```1
3
5
7
9
11
13
15
17
19
```
<p>The version with <code>sed</code> inverted:</p>
<pre class="lang-sh prettyprint-override"><code>for x in {1..20}; do echo $x ; done | sed -n 'n;p'
</code>```

Output:

```<code>2
4
6
8
10
12
14
16
18
20
</code>```

Body:
You have to invert your sed command: it should be n;p instead of p;n:

Your code:

for x in {1..20}; do echo $x ; done | sed -n 'p;n'

1
3
5
7
9
11
13
15
17
19

The version with sed inverted:

for x in {1..20}; do echo $x ; done | sed -n 'n;p'

Output:

2
4
6
8
10
12
14
16
18
20