答:
You can take a recursive approach and count each value that is not an object (but count arrays as a single leaf), otherwise get all values of the object and try to count them:

const state = { driver: { user: { number: '1234', firstName: 'xyz', lastName: 'abc' }, kyc: { name: 'kyc1', idNumber: 'kyc2' }, license: { idNumber: '1234', issuedOn: '1991-05-12', validTill: '1991-12-12' } }, vehicle: { vin: '4567', registrationNumber: '4567', dateBought: '1954-09-12', contractValidity: '1954-12-12', departments: [1, 2], vehicleType: 2 }, owner: { user: { number: '1234', firstName: 'lml', lastName: 'pqr', dateOfBirth: '2068-11-26' }, kyc: { name: 'kyc2', idNumber: 'kyc123' }, bank: { ifscCode: '1234', bankName: 'bank1', branchName: 'branch1', accountNumber: '1234', accountHolderName: 'holder1' }, license: { idNumber: '12345', issuedOn: '1997-12-12', validTill: '1997-12-12' }, insurance: { idNumber: '1234', issuedOn: '2909-12-12', validTill: '2909-12-12' } }, errors: {}, isSubmitable: false}

function countLeaves(val) {
  if (typeof val !== "object" || Array.isArray(val)) {
    return 1;
  }

  return Object.values(val).map(countLeaves).reduce(sum, 0)
}

const sum = (a, b) => a + b;

console.log(countLeaves(state));```

Title: Counting the number of leaves in a JavaScript Object

Body:
I have an errors object in the following way and I want to count the total number of leaves, my object is as follows

I have tried using the object.keys() property but it only counts the direct children of the object and not the nested values

state = {
    driver: {
        user: {
            number: '1234',
            firstName: 'xyz',
            lastName: 'abc'
        },
        kyc: {
            name: 'kyc1',
            idNumber: 'kyc2'
        },
        license: {
            idNumber: '1234',
            issuedOn: '1991-05-12',
            validTill: '1991-12-12'
        }
    },
    vehicle: {
        vin: '4567',
        registrationNumber: '4567',
        dateBought: '1954-09-12',
        contractValidity: '1954-12-12',
        departments: [1, 2],
        vehicleType: 2
    },
    owner: {
        user: {
            number: '1234',
            firstName: 'lml',
            lastName: 'pqr',
            dateOfBirth: '2068-11-26'
        },
        kyc: {
            name: 'kyc2',
            idNumber: 'kyc123'
        },
        bank: {
            ifscCode: '1234',
            bankName: 'bank1',
            branchName: 'branch1',
            accountNumber: '1234',
            accountHolderName: 'holder1'
        },
        license: {
            idNumber: '12345',
            issuedOn: '1997-12-12',
            validTill: '1997-12-12'
        },
        insurance: {
            idNumber: '1234',
            issuedOn: '2909-12-12',
            validTill: '2909-12-12'
        }
    },
    errors: {},
    isSubmitable: false
}


来源: stackexchange

问:
EJS/Node/Express - Having a header partial, how to change title for each page?
I recently took a course on back-end web developing.

As the title says, I don't get how can I use a header partial for the whole website but have different titles for each page. (because  is included in the  tag)

Is there any trick?

答:
1st) In your Express route:

```<code>app.get("/", function(req, res){
  res.locals.title = "Abel's Home Page";                    // THIS LINE IS KEY
  res.render("home.ejs");
});
</code>```

2nd) In your views/home.ejs file:

```<code><% include partials/header.ejs %>
</code>```

3rd) In your views/partials/header.ejs file:

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title><%= title %></title>                               <!-- THIS LINE IS KEY -->
  <link rel="stylesheet" href="../style.css">
  <link rel="shortcut icon" href="../logo_sm.png" type="image/x-icon">
</head>
<body>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
1st) In your Express route:

app.get("/", function(req, res){
  res.locals.title = "Abel's Home Page";                    // THIS LINE IS KEY
  res.render("home.ejs");
});

2nd) In your views/home.ejs file:

<% include partials/header.ejs %>

3rd) In your views/partials/header.ejs file:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title><%= title %></title>                               <!-- THIS LINE IS KEY -->
  <link rel="stylesheet" href="../style.css">
  <link rel="shortcut icon" href="../logo_sm.png" type="image/x-icon">
</head>
<body>


问:
How to show each of the selected value from single select option in input tag
I am new to javascript and I want to use the select option to list each selected value in the input tag.

I have tried to use javascript to show the selected value but when I select for the second time the first value dismiss and show the second selected. I was expected to show each selected value in the input tag separately without dismissing other previous selected.

function getSelectedValue() {
  var selectedValue = document.getElementById("list").value;
  document.getElementById("myValues").innerHTML = selectedValue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select name="" onchange="getSelectedValue();" class="form-control" id="list">
  <option value="Option1">Option1</option>
  <option value="Option2">Option2</option>
  <option value="Option3">Option3</option>
  <option value="Option4">Option4</option>
</select>
<input type="text" name="value[]" id="myValue" value=""></code>```

I expected the output of

<input type="text" name="value[]" id="myValue" value="Option1">

<input type="text" name="value[]" id="myValue" value="Option3">

thus in the input should show

Option1
  Option3

答:
I dont know what you really expect, but I think this solution can be helpful to you. checkout the snippet.

First get the value and then append to the existing value

function getSelectedValue() {
  var selectedValue = document.getElementById("list").value;
  var _optionSelected = document.getElementById("myValue").value;
  _optionSelected.length ? document.getElementById("myValue").value += ', '+selectedValue : document.getElementById("myValue").value += selectedValue;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select name="" onchange="getSelectedValue();" class="form-control" id="list">
  <option value="Option1">Option1</option>
  <option value="Option2">Option2</option>
  <option value="Option3">Option3</option>
  <option value="Option4">Option4</option>
</select>
<input type="text" name="value[]" id="myValue" value=""></code>```

Body:
I am new to javascript and I want to use the select option to list each selected value in the input tag.

I have tried to use javascript to show the selected value but when I select for the second time the first value dismiss and show the second selected. I was expected to show each selected value in the input tag separately without dismissing other previous selected.

function getSelectedValue() {
  var selectedValue = document.getElementById("list").value;
  document.getElementById("myValues").innerHTML = selectedValue;
}

<select name="" onchange="getSelectedValue();" class="form-control" id="list">
  <option value="Option1">Option1</option>
  <option value="Option2">Option2</option>
  <option value="Option3">Option3</option>
  <option value="Option4">Option4</option>
</select>
<input type="text" name="value[]" id="myValue" value="">

I expected the output of

<input type="text" name="value[]" id="myValue" value="Option1">

<input type="text" name="value[]" id="myValue" value="Option3">

thus in the input should show

Option1
  Option3

Body:
I dont know what you really expect, but I think this solution can be helpful to you. checkout the snippet.

First get the value and then append to the existing value

function getSelectedValue() {
  var selectedValue = document.getElementById("list").value;
  var _optionSelected = document.getElementById("myValue").value;
  _optionSelected.length ? document.getElementById("myValue").value += ', '+selectedValue : document.getElementById("myValue").value += selectedValue;

}

<select name="" onchange="getSelectedValue();" class="form-control" id="list">
  <option value="Option1">Option1</option>
  <option value="Option2">Option2</option>
  <option value="Option3">Option3</option>
  <option value="Option4">Option4</option>
</select>
<input type="text" name="value[]" id="myValue" value="">


问:
Is there a way to split a column of addresses if there is a sub address such as a unit number?
I have addresses listed in a column in one of my tables that are formatted as follows (address number in already in a separate column).

```<code>addressStreet
-----------------
S 1ST ST UNIT A
S 1ST ST UNIT 101
Main AVE H2
Brooklyn BLVD
Brooklyn BLVD 104
</code>```

I am trying to figure out the best way of separating out the sub-address(UNIT#, ETC..) into a second column.

I am expecting to see

```<code>addressStreet       subStreet
--------------      ------------
S 1ST ST            UNIT A
S 1ST ST            UNIT 101
Main AVE            H2
Brooklyn BLVD
Brooklyn BLVD       104
</code>```

Thanks in advance for any help you can give on the issue.

答:
OK, since the address data in your table do not have a specific delimiter, if your tags like AVE,RD,ST,BLVD are few,you can use substring_index in mysql to implement this, like below:

```<code> select
     case when address like '% AVE%' then concat(substring_index(address,' AVE', 1), ' AVE')
          when address like '% ST%' then concat(substring_index(address,' ST', 1), ' ST')
          when address like '% RD%' then concat(substring_index(address,' RD', 1), ' RD')
          when address like '% BLVD%' then concat(substring_index(address,' BLVD', 1),' BLVD')
     end as addressStreet,
     coalesce(case when address like '%AVE %' then substring_index(address,' AVE', -1)
          when address like '%ST %' then substring_index(address,' ST', -1)
          when address like '%RD %' then substring_index(address,' RD', -1)
          when address like '%BLVD %' then substring_index(address,' BLVD', -1)
     end,'') as subStreet
 from
     street;
+---------------+-----------+
| addressStreet | subStreet |
+---------------+-----------+
| S 1ST ST      |  UNIT A   |
| S 1ST ST      |  UNIT 101 |
| Main AVE      |  H2       |
| Brooklyn BLVD |           |
| Brooklyn BLVD |  104      |
+---------------+-----------+
5 rows in set (0.00 sec)
</code>```

And if you use PostgreSQL, things would be easier:

```<code>select
    (regexp_split_to_array(address,' ST| AVE| BLVD| RD'))[1] as address_street,
    (regexp_split_to_array(address,' ST| AVE| BLVD| RD'))[2] as sub_street
from
    street;;
 address_street | sub_street
----------------+------------
 S 1ST          |  UNIT A
 S 1ST          |  UNIT 101
 Main           |  H2
 Brooklyn       |
 Brooklyn       |  104
(5 rows)
</code>```

Body:
I have addresses listed in a column in one of my tables that are formatted as follows (address number in already in a separate column).

addressStreet
-----------------
S 1ST ST UNIT A
S 1ST ST UNIT 101
Main AVE H2
Brooklyn BLVD
Brooklyn BLVD 104

I am trying to figure out the best way of separating out the sub-address(UNIT#, ETC..) into a second column.

I am expecting to see

addressStreet       subStreet
--------------      ------------
S 1ST ST            UNIT A
S 1ST ST            UNIT 101
Main AVE            H2
Brooklyn BLVD
Brooklyn BLVD       104

Thanks in advance for any help you can give on the issue.

Body:
OK, since the address data in your table do not have a specific delimiter, if your tags like AVE,RD,ST,BLVD are few,you can use substring_index in mysql to implement this, like below:

 select
     case when address like '% AVE%' then concat(substring_index(address,' AVE', 1), ' AVE')
          when address like '% ST%' then concat(substring_index(address,' ST', 1), ' ST')
          when address like '% RD%' then concat(substring_index(address,' RD', 1), ' RD')
          when address like '% BLVD%' then concat(substring_index(address,' BLVD', 1),' BLVD')
     end as addressStreet,
     coalesce(case when address like '%AVE %' then substring_index(address,' AVE', -1)
          when address like '%ST %' then substring_index(address,' ST', -1)
          when address like '%RD %' then substring_index(address,' RD', -1)
          when address like '%BLVD %' then substring_index(address,' BLVD', -1)
     end,'') as subStreet
 from
     street;
+---------------+-----------+
| addressStreet | subStreet |
+---------------+-----------+
| S 1ST ST      |  UNIT A   |
| S 1ST ST      |  UNIT 101 |
| Main AVE      |  H2       |
| Brooklyn BLVD |           |
| Brooklyn BLVD |  104      |
+---------------+-----------+
5 rows in set (0.00 sec)

And if you use PostgreSQL, things would be easier:

select
    (regexp_split_to_array(address,' ST| AVE| BLVD| RD'))[1] as address_street,
    (regexp_split_to_array(address,' ST| AVE| BLVD| RD'))[2] as sub_street
from
    street;;
 address_street | sub_street
----------------+------------
 S 1ST          |  UNIT A
 S 1ST          |  UNIT 101
 Main           |  H2
 Brooklyn       |
 Brooklyn       |  104
(5 rows)


问:
PHP getting full server name including port number and protocol
In PHP, is there a reliable and good way of getting these things:

Protocol: i.e. http or https
Servername: e.g. localhost
Portnumber: e.g. 8080

I can get the server name using $_SERVER['SERVER_NAME'].

I can kind of get the protocol but I don't think it's perfect:

```<code>    if(strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https') {
        return "https";
    }
    else {
        return "http";
    }
</code>```

I don't know how to get the port number though.  The port numbers I am using are not 80.. they are 8080 and 8888.

Thank you.

答:
The function that returns the full protocol-server-port info:</p>
```<code>function getMyUrl()
{
  $protocol = (!empty($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) == 'on' || $_SERVER['HTTPS'] == '1')) ? 'https://' : 'http://';
  $server = $_SERVER['SERVER_NAME'];
  $port = $_SERVER['SERVER_PORT'] ? ':'.$_SERVER['SERVER_PORT'] : '';
  return $protocol.$server.$port;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In PHP, is there a reliable and good way of getting these things:

Protocol: i.e. http or https
Servername: e.g. localhost
Portnumber: e.g. 8080

I can get the server name using $_SERVER['SERVER_NAME'].

I can kind of get the protocol but I don't think it's perfect:

    if(strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https') {
        return "https";
    }
    else {
        return "http";
    }

I don't know how to get the port number though.  The port numbers I am using are not 80.. they are 8080 and 8888.

Thank you.

Body:
The function that returns the full protocol-server-port info:

function getMyUrl()
{
  $protocol = (!empty($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) == 'on' || $_SERVER['HTTPS'] == '1')) ? 'https://' : 'http://';
  $server = $_SERVER['SERVER_NAME'];
  $port = $_SERVER['SERVER_PORT'] ? ':'.$_SERVER['SERVER_PORT'] : '';
  return $protocol.$server.$port;
}


问:
How to assign same value to multiple variables in Kotlin
I have two variables and want to assign same value to both the variables at the same time something like below:

```<code>var allGood: Boolean = false
val deviceId: String = "3550200583"
var isValidId: Boolean = false
allGood = isValidId = deviceId.length > 0 && deviceId.length <= 16
</code>```

is there any way to achieve this?

答:
Because assignment is not an expression in Kotlin, you can't do multiple assignments that way.  But there are other ways.  The most obvious is simply:

```<code>isValidId = deviceId.length > 0 && deviceId.length <= 16
allGood = isValidId
</code>```

A more idiomatic (if longer) way is:

```<code>(deviceId.length > 0 && deviceId.length <= 16).let {
    allGood = it
    isValidId = it
}
</code>```

(By the way, you can simplify the condition to deviceId.length in 1..16.)

There are a couple of reasons why Kotlin doesn't allow this.  The main one is that it's incompatible with the syntax for calling a function with named parameters: fn(paramName = value).  But it also avoids any confusion between = and == (which could otherwise cause hard-to-spot bugs).  See also here.

Body:
I have two variables and want to assign same value to both the variables at the same time something like below:

var allGood: Boolean = false
val deviceId: String = "3550200583"
var isValidId: Boolean = false
allGood = isValidId = deviceId.length > 0 && deviceId.length <= 16

is there any way to achieve this?

Body:
Because assignment is not an expression in Kotlin, you can't do multiple assignments that way.  But there are other ways.  The most obvious is simply:

isValidId = deviceId.length > 0 && deviceId.length <= 16
allGood = isValidId

A more idiomatic (if longer) way is:

(deviceId.length > 0 && deviceId.length <= 16).let {
    allGood = it
    isValidId = it
}

(By the way, you can simplify the condition to deviceId.length in 1..16.)

There are a couple of reasons why Kotlin doesn't allow this.  The main one is that it's incompatible with the syntax for calling a function with named parameters: fn(paramName = value).  But it also avoids any confusion between = and == (which could otherwise cause hard-to-spot bugs).  See also here.


问:
Authentication in .net Core with ReactJS SPA
I trying add authentication to .net Core 2.1 application.
Starting from scratch: We can create new web application with react using VS template.

In this tempate we can see:

```<code>app.UseSpa(spa =>
{
    spa.Options.SourcePath = "ClientApp";
    spa.ApplicationBuilder.UseAuthentication();

    if (env.IsDevelopment())
    {
        spa.UseReactDevelopmentServer(npmScript: "start");
    }
});
</code>```

I also added Auth controller and views with login/register endpoints.

How can I add logic which will reject access to SPA untill we will login to application?

I know how to use asp.net identity regullary but with this SPA I need advice.

答:
For authentication with SPA you can use some server side tech like JWT to authenticate user. So if user login success you can give them the token and when user request your API you can submit the token within the header of the request so that the server know who you are and allow you access the API resource or not.

You can take a look at openiddict. They have full example with Angular app

Body:
I trying add authentication to .net Core 2.1 application.
Starting from scratch: We can create new web application with react using VS template.

In this tempate we can see:

app.UseSpa(spa =>
{
    spa.Options.SourcePath = "ClientApp";
    spa.ApplicationBuilder.UseAuthentication();

    if (env.IsDevelopment())
    {
        spa.UseReactDevelopmentServer(npmScript: "start");
    }
});

I also added Auth controller and views with login/register endpoints.

How can I add logic which will reject access to SPA untill we will login to application?

I know how to use asp.net identity regullary but with this SPA I need advice.


问:
Fastest Dictionary lookup in c# .net Compact Framework 3.5
I'm looking for the fastest way to lookup if List, Set, Dictionary contains a specific Keyword (string). I don't need to store any data inside I just want to know if my Keyword is in the List.

I thought about some possibilities like:

```<code>Dictionary<string, bool> myDictionary = new Dictionary<string, bool>();
if (myDictionary.ContainsKey(valueToSearch))
{
    // do something
}
</code>```

but I don't need a value.

```<code>string[] myArray = {"key1", "key2", "key3"}
if (Array.IndexOf(myArray, valueToSearch) != -1)
{
    // do something
}
</code>```

Then I found:

```<code>List<string> list = new List<string>();
if (list.Contains(valueToSearch))
{
    // do something
}
</code>```

The lookup will happen very often and has to be very fast.
Any idea what's the fastest way to check if a value equals one of a given list of keys?

答: I agree with Andy. You could also look at SortedList It's essentially a Dictionary that's sorted by its keys. Should make searching quicker if it's already sorted...</p>

Body:
I'm looking for the fastest way to lookup if List, Set, Dictionary contains a specific Keyword (string). I don't need to store any data inside I just want to know if my Keyword is in the List.

I thought about some possibilities like:

Dictionary<string, bool> myDictionary = new Dictionary<string, bool>();
if (myDictionary.ContainsKey(valueToSearch))
{
    // do something
}

but I don't need a value.

string[] myArray = {"key1", "key2", "key3"}
if (Array.IndexOf(myArray, valueToSearch) != -1)
{
    // do something
}

Then I found:

List<string> list = new List<string>();
if (list.Contains(valueToSearch))
{
    // do something
}

The lookup will happen very often and has to be very fast.
Any idea what's the fastest way to check if a value equals one of a given list of keys?


问:
Is there a single line statement to return from a function only if a conditional is true?
In C#, is there any syntactic sugar to do the following in a single statement (basically, a conditional return):

public SomeBaseType MyFunction()
{
    // Can the two statements below be combined into one?
    SomeBaseType something = SomeFunction();
    if ( something != null ) { return something; }
    // End of statements regarding this question.

    // Do lots of other statements...
    return somethingElseThatIsADerivedTypeThatDoesntMatter;
}
```

答:
No, there's no "conditional return statement" that either returns (based on a condition) or continues in the method, although I've occasionally wished for one too. You could write:

```<code>public SomeBaseType MyFunction()
{
    return SomeFunction() ?? LocalMethod();

    SomeBaseType LocalMethod()
    {
        // Do lots of other statements...
        return somethingElseThatIsADerivedTypeThatDoesntMatter;
    }
}
</code>```

... but that's really no clearer.

Body:
No, there's no "conditional return statement" that either returns (based on a condition) or continues in the method, although I've occasionally wished for one too. You could write:

public SomeBaseType MyFunction()
{
    return SomeFunction() ?? LocalMethod();

    SomeBaseType LocalMethod()
    {
        // Do lots of other statements...
        return somethingElseThatIsADerivedTypeThatDoesntMatter;
    }
}

... but that's really no clearer.


问:
Odoo change name occurence in pages and menus
I am trying to change the displayed name Vendors in the Purchase application. I was successful in changing the submenu name from Settings--> Technical--> User interface(menu items). Now when i select this submenu the page that gets displayed has 'Vendors' displayed on the left top and in the filters. How do i change Vendors to some other name wherever it occurs.

I am using odoo 12

答:
there are two methods,
the simplest is to change the name for each action view (form, tree). See the photos

the second, the same thing but by editing the xml of action code by inheriting the targeted view in order to modify it.

i hope that's can help you


问:
How to Install a local .rpm file by automatically downloading/installing other dependencies
Now there are multiple variations of this question, but none apply to me.

I want to install a locally downloaded .rpm file and any other dependencies that would be required while running this install, automatically.

The question is very specific to locally downloaded, so please do not suggest running yum-downloader for a known package name. Nothing is known. I discovered a nice .rpm, downloaded it, and now want to install it.

Detailed example:

My system already has polycoreutils-python-2.5-11. If I install using yum, this is the highest version I get. However, I got a locally downloaded upgrade file which is even higher version polycoreutils-python-2.5-24 ... .rpm

When I try to install this, of course, it complains about new missing deps, namely, polycore-utils and setools-lib. I have them installed too, but older versions. So I can go download the needed new .rpm files.

But I can't repeat this process for as many dependencies discovered step by step. What's the best way to install a locally downloaded package, and its required dependencies.

答:
You yust need to use yum to install that package you downloaded. yum will then manage the dependencies for you:

```<code>Yum install /path/to/downloaded.rpm
</code>```

If yum cannot find the dependencies you need, you should tell yum where he can find them: add the repository where he can find them.

EDIT
Multiple remarks concerning the installation of externally downloaded packages.

If you can; stick with the versions that are available in the official repositories; or in related repositories (like epel for centos or packman for opensuse).

Once you start downloading yourself rpms from the internet; try to stay as close as possible to your os and version of your os. The further you go from your os-version; the more probable that you will get dependency errors. It is very well possible that you will have to start upgrading so many packages that you are close to doing a manual distribution upgrade; which obviously is quite risky.

If you find a package that was repackaged by someone for your os and os-version; you can simply add his repository to your yum; even if it is just for the time to install your rpm (you can disable or remove that repository afterwards). Be careful when adding this repository that you don't start upgrading too many of your packages without need; because then you might again run into issues if this is not an officially maintained repository.

If you don't find a repository that you can temporarily add to yum, the only solution that remains is manually downloading all dependencies into a local directory and then running yum install directory/*rpm. Note that - if you are lucky - you might find the rpms you depend on next to where you downloaded the rpm you want to install. Otherwise http://rpm.pbone.net/index.php3 is a very nice place to start searching.

Body:
You yust need to use yum to install that package you downloaded. yum will then manage the dependencies for you:

Yum install /path/to/downloaded.rpm

If yum cannot find the dependencies you need, you should tell yum where he can find them: add the repository where he can find them.

EDIT
Multiple remarks concerning the installation of externally downloaded packages.

If you can; stick with the versions that are available in the official repositories; or in related repositories (like epel for centos or packman for opensuse).

Once you start downloading yourself rpms from the internet; try to stay as close as possible to your os and version of your os. The further you go from your os-version; the more probable that you will get dependency errors. It is very well possible that you will have to start upgrading so many packages that you are close to doing a manual distribution upgrade; which obviously is quite risky.

If you find a package that was repackaged by someone for your os and os-version; you can simply add his repository to your yum; even if it is just for the time to install your rpm (you can disable or remove that repository afterwards). Be careful when adding this repository that you don't start upgrading too many of your packages without need; because then you might again run into issues if this is not an officially maintained repository.

If you don't find a repository that you can temporarily add to yum, the only solution that remains is manually downloading all dependencies into a local directory and then running yum install directory/*rpm. Note that - if you are lucky - you might find the rpms you depend on next to where you downloaded the rpm you want to install. Otherwise http://rpm.pbone.net/index.php3 is a very nice place to start searching.


问:
How to assign array value to another input type using jquery
I am new to jQuery can you help me. How to assign array input to assign another input value using jquery?

```<code><tr>
    <td><label>Date</label><input type="date" name="PostingDate[]" id="date" style="text-align: center;"class="form-control " required /></td>
    <input type="date" style="display: none;" name="AddedOn" class="KR" />
</tr>
<script type="text/javascript">
    var date=$("#date").val();
    $(".KR").val(date);
</script>

</code>```

want to assign the date to this input field.

答:
You can try in this way:</p>

```<code>    $('#date').on("change",function(){
         $(".KR").val($(this).val());
         $(".KR").show()
    })
</code>```

Body:
I am new to jQuery can you help me. How to assign array input to assign another input value using jquery?

    Date<input type="date" name="PostingDate[]" id="date" style="text-align: center;"class="form-control " required />
    <input type="date" style="display: none;" name="AddedOn" class="KR" />

want to assign the date to this input field.

Body:
You can try in this way:

    $('#date').on("change",function(){
         $(".KR").val($(this).val());
         $(".KR").show()
    })


问:
Passing Arraylist between activities? Using Parcelable
EDIT: I've updated my question considerably and am now going with Parcelable as my method.

I'm attempting to a pass an ArrayList from one activity to another. I've been reading around and can't seem to find any answers to my problem.

I've got an ArrayList<SearchList> which implements Parcelable SearchList has the following code...

```<code>  public class SearchList implements Parcelable {
private String title;
  private String description;
  private String link;
  public SearchList(String name, String phone, String mail) {
          super();
          this.title = name;
          this.description = phone;
          this.link = mail;
  }
  public SearchList(Parcel source){
      /*
       * Reconstruct from the Parcel
       */
      title = source.readString();
      description = source.readString();
      link = source.readString();
}
  public String gettitle() {
          return title;
  }
  public void setTitle(String title) {
          this.title = title;
  }
  public String getDescription() {
          return description;
  }
  public void setDescription(String description) {
          this.description = description;
  }
  public String getLink() {
          return link;
  }
  public void setLink(String link) {
          this.link = link;
  }

public int describeContents() {
    // TODO Auto-generated method stub
    return 0;
}

public void writeToParcel(Parcel dest, int flags) {
      dest.writeString(title);
      dest.writeString(description);
      dest.writeString(link);

}

 public static final Creator<SearchList> CREATOR = new Creator<SearchList>() {
        public SearchList createFromParcel(Parcel source) {
            return new SearchList(source);
        }
        public SearchList[] newArray(int size) {
            return new SearchList[size];
        }
    };
  }
</code>```

However, when I try and do...

```<code> List<SearchList> listOfResults = new ArrayList<SearchList>();
 intent.putParcelableArrayListExtra("results", listOfResults);
</code>```

I get not applicable for type (String, List<SearchList> why?

答: Could you use all String values, and change from bundle.putSerializable() to bundle.putStringArrayList("key", ArrayList<String>_object)

Body:
EDIT: I've updated my question considerably and am now going with Parcelable as my method.

I'm attempting to a pass an ArrayList from one activity to another. I've been reading around and can't seem to find any answers to my problem.

I've got an ArrayList<SearchList> which implements Parcelable SearchList has the following code...

  public class SearchList implements Parcelable {
private String title;
  private String description;
  private String link;
  public SearchList(String name, String phone, String mail) {
          super();
          this.title = name;
          this.description = phone;
          this.link = mail;
  }
  public SearchList(Parcel source){
      /*
       * Reconstruct from the Parcel
       */
      title = source.readString();
      description = source.readString();
      link = source.readString();
}
  public String gettitle() {
          return title;
  }
  public void setTitle(String title) {
          this.title = title;
  }
  public String getDescription() {
          return description;
  }
  public void setDescription(String description) {
          this.description = description;
  }
  public String getLink() {
          return link;
  }
  public void setLink(String link) {
          this.link = link;
  }

public int describeContents() {
    // TODO Auto-generated method stub
    return 0;
}

public void writeToParcel(Parcel dest, int flags) {
      dest.writeString(title);
      dest.writeString(description);
      dest.writeString(link);

}

 public static final Creator<SearchList> CREATOR = new Creator<SearchList>() {
        public SearchList createFromParcel(Parcel source) {
            return new SearchList(source);
        }
        public SearchList[] newArray(int size) {
            return new SearchList[size];
        }
    };
  }

However, when I try and do...

 List<SearchList> listOfResults = new ArrayList<SearchList>();
 intent.putParcelableArrayListExtra("results", listOfResults);

I get not applicable for type (String, List<SearchList> why?


答:
Another way is to do it like this:</p>

```<code>val deviceId: String = "3550200583";
val condition = deviceId.length > 0 && deviceId.length <= 16
var (allGood, isValidId) = arrayOf(condition, condition);
</code>```

Title: How to assign same value to multiple variables in Kotlin

Body:
Another way is to do it like this:

val deviceId: String = "3550200583";
val condition = deviceId.length > 0 && deviceId.length <= 16
var (allGood, isValidId) = arrayOf(condition, condition);


问:
Kafka Stream Exception: GroupAuthorizationException
I'm developing a Kafka-Stream application, which will read the message from input Kafka topic and filter unwanted data and push to output Kafka topic.

Kafka Stream Configuration:

```<code>@Bean(name = KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME)
public KafkaStreamsConfiguration kStreamsConfigs() {

    Map<String, Object> streamsConfiguration = new HashMap<>();
    streamsConfiguration.put(ConsumerConfig.GROUP_ID_CONFIG, "abcd");
    streamsConfiguration.put(StreamsConfig.APPLICATION_ID_CONFIG, "QC-NormalizedEventProcessor-v1.0.0");
    streamsConfiguration.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "test:9072");
    streamsConfiguration.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
    streamsConfiguration.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());
    streamsConfiguration.put(StreamsConfig.PROCESSING_GUARANTEE_CONFIG, StreamsConfig.EXACTLY_ONCE);
    streamsConfiguration.put(StreamsConfig.producerPrefix(ProducerConfig.ACKS_CONFIG), -1);
    streamsConfiguration.put(StreamsConfig.REPLICATION_FACTOR_CONFIG, 3);
    streamsConfiguration.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");
    streamsConfiguration.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, kafkaConsumerProperties.getConsumerJKSFileLocation());
    streamsConfiguration.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, kafkaConsumerProperties.getConsumerJKSPwd());
    streamsConfiguration.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SASL_SSL");
    streamsConfiguration.put(SASL_MECHANISM, "PLAIN");

    return new KafkaStreamsConfiguration(streamsConfiguration);
}
</code>```

KStream Filter Logic:

```<code>@Bean
public KStream<String, String> kStreamJson(StreamsBuilder builder) {

    KStream<String, String> stream = builder.stream(kafkaConsumerProperties.getConsumerTopic(), Consumed.with(Serdes.String(), Serdes.String()));
    /** Printing the source message */
    stream.foreach((key, value) -> LOGGER.info(THREAD_NO + Thread.currentThread().getId() + " *****Message From Input Topic: " + key + ": " + value));
    KStream<String, String> filteredDocument = stream.filter((k, v) -> filterCondition.test(k, v));

    filteredDocument.to(kafkaConsumerProperties.getProducerTopic(), Produced.with(Serdes.String(), Serdes.String()));
    /** After filtering printing the same message */
    filteredDocument.foreach((key, value) -> LOGGER.info(THREAD_NO + Thread.currentThread().getId() + " #####Filtered Document: " + key + ": " + value));
    return stream;
}
</code>```

While starting above spring based Kafka Stream application, i was getting below exception.

```<code>2019-05-27T07:58:36.018-0500 ERROR stream-thread [QC-NormalizedEventProcessor-v1.0.0-e9cb1bed-3d90-41f1-957a-4fc7efc12a02-StreamThread-1] Encountered the following unexpected Kafka exception during processing, this usually indicate Streams internal errors:
org.apache.kafka.common.errors.GroupAuthorizationException: Not authorized to access group: QC-NormalizedEventProcessor-v1.0.0
</code>```

Our Kafka Infra team given necessary permission to "group.id", using this same "group id" i can consume the message using other Kafka Consumer applications and I was using name as per my wish in "application.id". We are not adding/updating "application.id" in Kafka Access Control List.

Am really not sure we need to give any permission for "application.id" or am missing something in the Kafka Stream Configuration. Please advice.

Please Note: I have tried with using with "group.id" and without "group.id" in Kafka Stream Configuration, all the time i am getting same exception.

Thanks!
Bharathiraja Shanmugam

答:
We need to set access for application.id as well.
                         For more information please refer -> https://docs.confluent.io/current/streams/developer-guide/security.html

Required ACL setting for secure Kafka clusters

  Kafka clusters can use ACLs to control access to resources (like the ability to
  create topics), and for such clusters each client, including Kafka
  Streams, is required to authenticate as a particular user in order to
  be authorized with appropriate access. In particular, when Streams
  applications are run against a secured Kafka cluster, the principal
  running the application must have the ACL set so that the application
  has the permissions to create internal topics.

Since all internal topics as well as the embedded consumer group name are prefixed with the application ID, it is recommended to use ACLs on prefixed resource pattern to configure control lists to allow client to manage all topics and consumer groups started with this prefix as --resource-pattern-type prefixed --topic  --operation All (see KIP-277 and KIP-290 for details).

For example, given the following setup of your Streams application:

• Config application.id value is team1-streams-app1.
  • Authenticating with the Kafka cluster as a team1 user. •  The
  application's coded topology reads from input topics input-topic1
  and input-topic2. • The application's topology write to output
  topics output-topic1 and output-topic2.

Then the following commands would create the necessary ACLs in the
  Kafka cluster to allow your application to operate:

```<code># Allow Streams to read the input topics:
bin/kafka-acls ... --add --allow-principal User:team1 --operation Read --topic input-topic1 --topic input-topic2

# Allow Streams to write to the output topics:
bin/kafka-acls ... --add --allow-principal User:team1 --operation Write --topic output-topic1 --topic output-topic2

# Allow Streams to manage its own internal topics and consumer groups:
bin/kafka-acls ... --add --allow-principal User:team1 --operation All --resource-pattern-type prefixed --topic team1-streams-app1 --group team1-streams-app1
</code>```

Body:
I'm developing a Kafka-Stream application, which will read the message from input Kafka topic and filter unwanted data and push to output Kafka topic.

Kafka Stream Configuration:

@Bean(name = KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME)
public KafkaStreamsConfiguration kStreamsConfigs() {

    Map<String, Object> streamsConfiguration = new HashMap<>();
    streamsConfiguration.put(ConsumerConfig.GROUP_ID_CONFIG, "abcd");
    streamsConfiguration.put(StreamsConfig.APPLICATION_ID_CONFIG, "QC-NormalizedEventProcessor-v1.0.0");
    streamsConfiguration.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "test:9072");
    streamsConfiguration.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
    streamsConfiguration.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());
    streamsConfiguration.put(StreamsConfig.PROCESSING_GUARANTEE_CONFIG, StreamsConfig.EXACTLY_ONCE);
    streamsConfiguration.put(StreamsConfig.producerPrefix(ProducerConfig.ACKS_CONFIG), -1);
    streamsConfiguration.put(StreamsConfig.REPLICATION_FACTOR_CONFIG, 3);
    streamsConfiguration.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");
    streamsConfiguration.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, kafkaConsumerProperties.getConsumerJKSFileLocation());
    streamsConfiguration.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, kafkaConsumerProperties.getConsumerJKSPwd());
    streamsConfiguration.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SASL_SSL");
    streamsConfiguration.put(SASL_MECHANISM, "PLAIN");

    return new KafkaStreamsConfiguration(streamsConfiguration);
}

KStream Filter Logic:

@Bean
public KStream<String, String> kStreamJson(StreamsBuilder builder) {

    KStream<String, String> stream = builder.stream(kafkaConsumerProperties.getConsumerTopic(), Consumed.with(Serdes.String(), Serdes.String()));
    /** Printing the source message */
    stream.foreach((key, value) -> LOGGER.info(THREAD_NO + Thread.currentThread().getId() + " *****Message From Input Topic: " + key + ": " + value));
    KStream<String, String> filteredDocument = stream.filter((k, v) -> filterCondition.test(k, v));

    filteredDocument.to(kafkaConsumerProperties.getProducerTopic(), Produced.with(Serdes.String(), Serdes.String()));
    /** After filtering printing the same message */
    filteredDocument.foreach((key, value) -> LOGGER.info(THREAD_NO + Thread.currentThread().getId() + " #####Filtered Document: " + key + ": " + value));
    return stream;
}

While starting above spring based Kafka Stream application, i was getting below exception.

2019-05-27T07:58:36.018-0500 ERROR stream-thread [QC-NormalizedEventProcessor-v1.0.0-e9cb1bed-3d90-41f1-957a-4fc7efc12a02-StreamThread-1] Encountered the following unexpected Kafka exception during processing, this usually indicate Streams internal errors:
org.apache.kafka.common.errors.GroupAuthorizationException: Not authorized to access group: QC-NormalizedEventProcessor-v1.0.0

Our Kafka Infra team given necessary permission to "group.id", using this same "group id" i can consume the message using other Kafka Consumer applications and I was using name as per my wish in "application.id". We are not adding/updating "application.id" in Kafka Access Control List.

Am really not sure we need to give any permission for "application.id" or am missing something in the Kafka Stream Configuration. Please advice.

Please Note: I have tried with using with "group.id" and without "group.id" in Kafka Stream Configuration, all the time i am getting same exception.

Thanks!
Bharathiraja Shanmugam

Body:
We need to set access for application.id as well.
                         For more information please refer -> https://docs.confluent.io/current/streams/developer-guide/security.html

Required ACL setting for secure Kafka clusters

  Kafka clusters can use ACLs to control access to resources (like the ability to
  create topics), and for such clusters each client, including Kafka
  Streams, is required to authenticate as a particular user in order to
  be authorized with appropriate access. In particular, when Streams
  applications are run against a secured Kafka cluster, the principal
  running the application must have the ACL set so that the application
  has the permissions to create internal topics.

Since all internal topics as well as the embedded consumer group name are prefixed with the application ID, it is recommended to use ACLs on prefixed resource pattern to configure control lists to allow client to manage all topics and consumer groups started with this prefix as --resource-pattern-type prefixed --topic  --operation All (see KIP-277 and KIP-290 for details).

For example, given the following setup of your Streams application:

• Config application.id value is team1-streams-app1.
  • Authenticating with the Kafka cluster as a team1 user. •  The
  application's coded topology reads from input topics input-topic1
  and input-topic2. • The application's topology write to output
  topics output-topic1 and output-topic2.

Then the following commands would create the necessary ACLs in the
  Kafka cluster to allow your application to operate:

# Allow Streams to read the input topics:
bin/kafka-acls ... --add --allow-principal User:team1 --operation Read --topic input-topic1 --topic input-topic2

# Allow Streams to write to the output topics:
bin/kafka-acls ... --add --allow-principal User:team1 --operation Write --topic output-topic1 --topic output-topic2

# Allow Streams to manage its own internal topics and consumer groups:
bin/kafka-acls ... --add --allow-principal User:team1 --operation All --resource-pattern-type prefixed --topic team1-streams-app1 --group team1-streams-app1


问:
Parse record (PCF) from Kafka using Kafka Kusto Sink
I've set-up my environment using docker based on this guide.

On kafka-console-producer I will send this line:

```<code>Hazriq|27|Undegrad|UNITEN
</code>```

I want this data to be ingested to Kusto like this:

```<code>+--------+-----+----------------+------------+
| Name   | Age | EducationLevel | University |
+--------+-----+----------------+------------+
| Hazriq | 27  | Undegrad       | UNITEN     |
+--------+-----+----------------+------------+

</code>```

Can this be handled by Kusto using the mapping (which I'm still trying to understand) or this should be catered by Kafka?

Tried @daniel suggestion:

```<code>.create table ParsedTable (name: string, age: int, educationLevel: string, univ:string)

.create table ParsedTable ingestion csv mapping 'ParsedTableMapping' '[{ "Name" : "name", "Ordinal" : 0},{ "Name" : "age", "Ordinal" : 1 },{ "Name" : "educationLevel", "Ordinal" : 2},{ "Name" : "univ", "Ordinal" : 3}]'

</code>```

```<code>kusto.tables.topics_mapping=[{'topic': 'kafkatopiclugiaparser','db': 'kusto-test', 'table': 'ParsedTable','format': 'psv', 'mapping':'ParsedTableMapping'}]
value.converter=org.apache.kafka.connect.storage.StringConverter
key.converter=org.apache.kafka.connect.storage.StringConverter
</code>```

but getting this instead:

```<code>+----------------------------+-----+----------------+------+
| Name                       | Age | EducationLevel | Univ |
+----------------------------+-----+----------------+------+
| Hazriq|27|Undergrad|UNITEN |     |                |      |
+----------------------------+-----+----------------+------+
</code>```

答:
Currently, the connector passes the data as it comes (no manipulation on it on the client side), and any parsing is left to Kusto.

As such, psv format is supported by kusto, and it should be possible by setting the format to psv and providing a mapping reference.

When adding the plugin as described, you should be able to set it up like:

```<code>kusto.tables.topics_mapping=[{'topic': 'testing1','db': 'testDB', 'table': 'KafkaTest','format': 'psv', 'mapping':'KafkaMapping'}]
</code>```

The mapping can be defined in Kusto as described in the Kusto docs defined like so

Body:
I've set-up my environment using docker based on this guide.

On kafka-console-producer I will send this line:

Hazriq|27|Undegrad|UNITEN

I want this data to be ingested to Kusto like this:

+--------+-----+----------------+------------+
| Name   | Age | EducationLevel | University |
+--------+-----+----------------+------------+
| Hazriq | 27  | Undegrad       | UNITEN     |
+--------+-----+----------------+------------+

Can this be handled by Kusto using the mapping (which I'm still trying to understand) or this should be catered by Kafka?

Tried @daniel suggestion:

.create table ParsedTable (name: string, age: int, educationLevel: string, univ:string)

.create table ParsedTable ingestion csv mapping 'ParsedTableMapping' '[{ "Name" : "name", "Ordinal" : 0},{ "Name" : "age", "Ordinal" : 1 },{ "Name" : "educationLevel", "Ordinal" : 2},{ "Name" : "univ", "Ordinal" : 3}]'

kusto.tables.topics_mapping=[{'topic': 'kafkatopiclugiaparser','db': 'kusto-test', 'table': 'ParsedTable','format': 'psv', 'mapping':'ParsedTableMapping'}]
value.converter=org.apache.kafka.connect.storage.StringConverter
key.converter=org.apache.kafka.connect.storage.StringConverter

but getting this instead:

+----------------------------+-----+----------------+------+
| Name                       | Age | EducationLevel | Univ |
+----------------------------+-----+----------------+------+
| Hazriq|27|Undergrad|UNITEN |     |                |      |
+----------------------------+-----+----------------+------+

Body:
Currently, the connector passes the data as it comes (no manipulation on it on the client side), and any parsing is left to Kusto.

As such, psv format is supported by kusto, and it should be possible by setting the format to psv and providing a mapping reference.

When adding the plugin as described, you should be able to set it up like:

kusto.tables.topics_mapping=[{'topic': 'testing1','db': 'testDB', 'table': 'KafkaTest','format': 'psv', 'mapping':'KafkaMapping'}]

The mapping can be defined in Kusto as described in the Kusto docs defined like so


问:
How to save/export all the settings of IntelliJ IDEA?
I would like to reinstall my operating system and keep the IntelliJ IDEA settings (like colors, indents, inspections, etc.). Is there a way to save my settings to keep them during operating system reinstalling?

答:
Personally, I have found the Export Settings method to be most effective for transporting my settings between multi-platform dev environments (using an external service such as Google Drive to store them). Sure it's not as simple as using the 'Settings Sync' plugin, but it allows you to experiment with a wider variety of individual configurations (assuming you name your various configurations descriptively).

File --> Export Settings

With this method there is also the additional burden of transferring your runConfigurations data, as described in a previous answer. However, at the cost of increased complexity is increased freedom for experimentation.

However, if you only plan on using one configuration, I'd recommend the Sync Settings plugin. You can read more about its usage here:

https://www.jetbrains.com/help/idea/sharing-your-ide-settings.html


问:
asyncio: running task only if all other tasks are awaiting
I am currently running some endless tasks using asyncio.wait

I need a special function to run when all the others are on await

```<code>import asyncio

async def special_function():
    while True:
        # does some work,
        # Passes control back to controller to run main_tasks
        # if they are no longer waiting.
        await asyncio.sleep(0)

async def handler():
    tasks = [task() for task in main_tasks]

    # Adding the task that I want to run when all main_tasks are awaiting:
    tasks.append(special_function())

    await asyncio.wait(tasks)

asyncio.get_event_loop().run_until_complete(handler())
</code>```

How can I get  the special_function to only be run when all main_tasks are on await?

Edit:

What I mean by "all main_tasks are on await": all main_tasks are not ready to continue, e.g. are in asyncio.sleep(100) or I/O bound and still waiting for data.

Therefore the main_tasks cannot continue and the event loop runs the special_function while the tasks are in this state, NOT every iteration of the event loop.

Edit 2:

My use case:

The main_tasks are updating a data structure with new data from web-sockets.

The special_function transfers that data to another process upon an update signal from that process. (multiprocessing with shared variables and data structures)

It needs to be the most up to date data it can be when it transfers, there cannot be pending updates from main_tasks.

This is why I only want to run special_function when there are no main_tasks with new data available to be processed. (i.e. all waiting on await)

答:
I tried to write a test for the 'task not ready to run' condition. I think asyncio does not expose details from the scheduler. The developers have clearly stated they want to keep freedom for changing asyncio internals without breaking backward compatibility.

In asyncio.Task there is this comment (note: _step() runs the task coroutine till the next await):

```<code># An important invariant maintained while a Task not done:
#
# - Either _fut_waiter is None, and _step() is scheduled;
# - or _fut_waiter is some Future, and _step() is *not* scheduled.
</code>```

But that internal variable is not in the API, of course.

You can get some limited access to _fut_waiter by reading the output of repr(task), but the format seems to be not reliable either, so I would not depend on somehing like this:

```<code>PENDINGMSG = 'wait_for=<Future pending '

if all(PENDINGMSG in repr(t) for t in monitored_tasks):
    do_something()
</code>```

Anyway, I think you are trying to be too perfect. You want to know if there is new data in other tasks. What if the data is in asyncio buffers? Kernel buffer? Network card receive buffer? ... You could never know if new data arrives the next millisecond.

My suggestion: write all updates to a single queue. Check that queue as the only source of updates. If the queue is empty, publish the last state.

Body:
I am currently running some endless tasks using asyncio.wait

I need a special function to run when all the others are on await

import asyncio

async def special_function():
    while True:
        # does some work,
        # Passes control back to controller to run main_tasks
        # if they are no longer waiting.
        await asyncio.sleep(0)

async def handler():
    tasks = [task() for task in main_tasks]

    # Adding the task that I want to run when all main_tasks are awaiting:
    tasks.append(special_function())

    await asyncio.wait(tasks)

asyncio.get_event_loop().run_until_complete(handler())

How can I get  the special_function to only be run when all main_tasks are on await?

Edit:

What I mean by "all main_tasks are on await": all main_tasks are not ready to continue, e.g. are in asyncio.sleep(100) or I/O bound and still waiting for data.

Therefore the main_tasks cannot continue and the event loop runs the special_function while the tasks are in this state, NOT every iteration of the event loop.

Edit 2:

My use case:

The main_tasks are updating a data structure with new data from web-sockets.

The special_function transfers that data to another process upon an update signal from that process. (multiprocessing with shared variables and data structures)

It needs to be the most up to date data it can be when it transfers, there cannot be pending updates from main_tasks.

This is why I only want to run special_function when there are no main_tasks with new data available to be processed. (i.e. all waiting on await)

Body:
I tried to write a test for the 'task not ready to run' condition. I think asyncio does not expose details from the scheduler. The developers have clearly stated they want to keep freedom for changing asyncio internals without breaking backward compatibility.

In asyncio.Task there is this comment (note: _step() runs the task coroutine till the next await):

# An important invariant maintained while a Task not done:
#
# - Either _fut_waiter is None, and _step() is scheduled;
# - or _fut_waiter is some Future, and _step() is *not* scheduled.

But that internal variable is not in the API, of course.

You can get some limited access to _fut_waiter by reading the output of repr(task), but the format seems to be not reliable either, so I would not depend on somehing like this:

PENDINGMSG = 'wait_for=<Future pending '

if all(PENDINGMSG in repr(t) for t in monitored_tasks):
    do_something()

Anyway, I think you are trying to be too perfect. You want to know if there is new data in other tasks. What if the data is in asyncio buffers? Kernel buffer? Network card receive buffer? ... You could never know if new data arrives the next millisecond.

My suggestion: write all updates to a single queue. Check that queue as the only source of updates. If the queue is empty, publish the last state.


问:
Difference between back tracking and dynamic programming
I heard the only difference between dynamic programming and back tracking is DP allows overlapping of sub problems, e.g.

```<code>fib(n) = fib(n-1) + fib (n-2)
</code>```

Is it right? Are there any other differences?

Also, I would like know some common problems solved using these techniques.

答: In a very simple sentence I can say: Dynamic programming is a strategy to solve optimization problem. optimization problem is about minimum or maximum result (a single result). but in, Backtracking we use brute force approach, not for optimization problem. it is for when you have multiple results and you want all or some of them.

Body:
I heard the only difference between dynamic programming and back tracking is DP allows overlapping of sub problems, e.g.

fib(n) = fib(n-1) + fib (n-2)

Is it right? Are there any other differences?

Also, I would like know some common problems solved using these techniques.


问:
Scrolling wpf datagrid to particular row and focus that row
My requirement is to scroll through wpf data grid and reach to particular row and focus that row

I am using the below code to achieve it . Scrolling to particular row is working smoothly but few times focus not work

```<code>  private void FocusNextRow()
  {
             int index = indexOfRowsToHighlight[indexOfRowToFocus];
             MessagesDataGrid.SelectedItem = MessagesDataGrid.Items[index];
             MessagesDataGrid.ScrollIntoView(MessagesDataGrid.SelectedItem);
             Thread.Sleep(200);
             MessagesDataGrid.SelectionUnit = DataGridSelectionUnit.FullRow;
             DataGridRow row = MessagesDataGrid.ItemContainerGenerator.ContainerFromIndex(index)  as DataGridRow;
             DataGridCell cell = GetCell(MessagesDataGrid, row, 0);
             cell.Focus();
   }
   private static DataGridCell GetCell(DataGrid dataGrid, DataGridRow rowContainer, int column)
   {
        if (rowContainer != null)
        {
              DataGridCellsPresenter presenter = FindVisualChild<DataGridCellsPresenter>(rowContainer);
              // try to get the cell but it may possibly be virtualized
              DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
              if (cell == null)
              {
                  cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
              }
               return cell;
            }

             return null;
        }

        private static T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
        {
           for(int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
           {
               DependencyObject child = VisualTreeHelper.GetChild(obj, i);
               if (child != null && child is T)
                      return (T)child;
               else
               {
                     T childOfChild = FindVisualChild<T>(child);
                      if (childOfChild != null)
                           return childOfChild;
               }
            }
                    return null;
        }
</code>```

Out of 100 times 90 times focus is working but few times randomly it does not work

答:
it's maybe virtualizing!!
when call FocusNextRow function, check status of ItemContainerGenerator

```<code>MessagesDataGrid.ItemContainerGenerator.ContainerFromIndex(index)  as DataGridRow;
</code>```

https://learn.microsoft.com/ko-kr/dotnet/api/system.windows.controls.itemcontainergenerator?view=netframework-4.8

Body:
My requirement is to scroll through wpf data grid and reach to particular row and focus that row

I am using the below code to achieve it . Scrolling to particular row is working smoothly but few times focus not work

  private void FocusNextRow()
  {
             int index = indexOfRowsToHighlight[indexOfRowToFocus];
             MessagesDataGrid.SelectedItem = MessagesDataGrid.Items[index];
             MessagesDataGrid.ScrollIntoView(MessagesDataGrid.SelectedItem);
             Thread.Sleep(200);
             MessagesDataGrid.SelectionUnit = DataGridSelectionUnit.FullRow;
             DataGridRow row = MessagesDataGrid.ItemContainerGenerator.ContainerFromIndex(index)  as DataGridRow;
             DataGridCell cell = GetCell(MessagesDataGrid, row, 0);
             cell.Focus();
   }
   private static DataGridCell GetCell(DataGrid dataGrid, DataGridRow rowContainer, int column)
   {
        if (rowContainer != null)
        {
              DataGridCellsPresenter presenter = FindVisualChild<DataGridCellsPresenter>(rowContainer);
              // try to get the cell but it may possibly be virtualized
              DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
              if (cell == null)
              {
                  cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
              }
               return cell;
            }

             return null;
        }

        private static T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
        {
           for(int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
           {
               DependencyObject child = VisualTreeHelper.GetChild(obj, i);
               if (child != null && child is T)
                      return (T)child;
               else
               {
                     T childOfChild = FindVisualChild<T>(child);
                      if (childOfChild != null)
                           return childOfChild;
               }
            }
                    return null;
        }

Out of 100 times 90 times focus is working but few times randomly it does not work

Body:
it's maybe virtualizing!!
when call FocusNextRow function, check status of ItemContainerGenerator

MessagesDataGrid.ItemContainerGenerator.ContainerFromIndex(index)  as DataGridRow;

https://learn.microsoft.com/ko-kr/dotnet/api/system.windows.controls.itemcontainergenerator?view=netframework-4.8


问:
Background Image need to give innner div space
I would like to give a space of repeating background.

Tried Code :

#bg_img {
  background-image: url("https://image.freepik.com/free-vector/diagonal-lines-vector-background-design_1017-12303.jpg");
  background-repeat: repeat;
  background-position: left center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="bg_img">
  <div id="tbles">
    <table width="100%" cellspacing="0" cellpadding="0" border="1">
      <tbody>
        <tr>
          <td width="4%" align="center"><strong>No</strong></td>
          <td style="min-width:25%" align="center"><strong>Name</strong></td>
          <td style="min-width:11%" align="center"><strong>Unit</strong></td>
          <td style="width:11%" align="center"><strong>Unit Price</strong></td>
        </tr>
        <tr>
          <td class="materialRow" align="center">1.</td>
          <td class="materialRow" align="left"><strong>Banana 1</strong><br>
            <font style="font-size:11px;">FIRE BARRIER CAULK</font>
          </td>
          <td class="materialRow" align="center">Test</td>
          <td class="materialRow" align="center">780.00</td>
        </tr>
        <tr>
          <td class="materialRow" align="center">2.</td>
          <td class="materialRow" align="left"><strong>Banana 2</strong><br>
            <font style="font-size:11px;">INTUMESCENT STRIP</font>
          </td>
          <td class="materialRow" align="center">Test</td>
          <td class="materialRow" align="center">73,600.00</td>
        </tr>
        <tr>
          <td class="materialRow" align="center">3.</td>
          <td class="materialRow" align="left"><strong>Banana 3</strong><br>
            <font style="font-size:11px;">STAINLESS STEEL HOOP</font>
          </td>
          <td class="materialRow" align="center">25.00</td>
          <td class="materialRow" align="center">Test</td>

        </tr>
        <tr>
          <td class="materialRow" align="center">4.</td>
          <td class="materialRow" align="left"><strong>Banana 4</strong><br>
            <font style="font-size:11px;">COATED FIRESTOP BOARD</font>
          </td>
          <td class="materialRow" align="center">Test</td>
          <td class="materialRow" align="center">125.00</td>
        </tr>
        <tr>
          <td class="materialRow" align="center">5.</td>
          <td class="materialRow" align="left"><strong>Banana 5</strong><br>
            <font style="font-size:11px;">MORTAR</font>
          </td>
          <td class="materialRow" align="center">Test</td>
          <td class="materialRow" align="center">185.00</td>
        </tr>
      </tbody>
    </table>
  </div>
</div></code>```

Is it possible to display Background Images on specific Area only with using backgroud space, margin or padding?

Actual Result :

Expected Result :

答:
You have to update your table structure with thead and apply background-image to tbody. You also have blank column to achieve the requirement. Mentioned changes done in the below code snippet. Try this I hope it'll help you out. Thanks

#bg_img tbody {
    background-image: url("https://image.freepik.com/free-vector/diagonal-lines-vector-background-design_1017-12303.jpg");
            background-repeat: repeat;
    background-position: left center;
    }

.blank-row {
  padding: 1%;
}

tbody tr td:first-child,
tbody tr td:last-child{
  background-color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="bg_img">
  <div id="tbles">
       <table width="100%" cellspacing="0" cellpadding="0" border="1">
          <thead>
            <tr>
              <th width="2%"></th>
              <th width="4%" align="center"><strong>No</strong></th>
              <th style="min-width:25%" align="center"><strong>Name</strong></th>
              <th style="min-width:11%" align="center"><strong>Unit</strong></th>
              <th style="width:11%" align="center"><strong>Unit Price</strong></th>
              <th width="2%"></th>
            </tr>
            <tr>
              <th class="blank-row" colspan="6"></td>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td></td>
              <td class="materialRow" align="center">1.</td>
              <td class="materialRow" align="left"><strong>Banana 1</strong><br><font style="font-size:11px;">FIRE BARRIER CAULK</font></td>
              <td class="materialRow" align="center">Test</td>
              <td class="materialRow" align="center">780.00</td>
              <td></td>
              </tr><tr>
              <td></td>
              <td class="materialRow" align="center">2.</td>
              <td class="materialRow" align="left"><strong>Banana 2</strong><br><font style="font-size:11px;">INTUMESCENT STRIP</font></td>
              <td class="materialRow" align="center">Test</td>
              <td class="materialRow" align="center">73,600.00</td>
              <td></td>
              </tr><tr>
              <td></td>
              <td class="materialRow" align="center">3.</td>
              <td class="materialRow" align="left"><strong>Banana 3</strong><br><font style="font-size:11px;">STAINLESS STEEL HOOP</font></td>
              <td class="materialRow" align="center">25.00</td>
              <td class="materialRow" align="center">Test</td>
              <td></td>
              </tr><tr>
              <td></td>
              <td class="materialRow" align="center">4.</td>
              <td class="materialRow" align="left"><strong>Banana 4</strong><br><font style="font-size:11px;">COATED FIRESTOP BOARD</font></td>
              <td class="materialRow" align="center">Test</td>
              <td class="materialRow" align="center">125.00</td>
              <td></td>
              </tr><tr>
              <td></td>
              <td class="materialRow" align="center">5.</td>
              <td class="materialRow" align="left"><strong>Banana 5</strong><br><font style="font-size:11px;">MORTAR</font></td>
              <td class="materialRow" align="center">Test</td>
              <td class="materialRow" align="center">185.00</td>
              <td></td>
            </tr>
            <tr>
              <td class="blank-row" colspan="6"></td>
            </tr>
      </tbody>
    </table>
  </div>
</div></code>```

Body:
I would like to give a space of repeating background.

Tried Code :

#bg_img {
  background-image: url("https://image.freepik.com/free-vector/diagonal-lines-vector-background-design_1017-12303.jpg");
  background-repeat: repeat;
  background-position: left center;
}

          No
          Name
          Unit
          Unit Price

          1.
          Banana 1

            FIRE BARRIER CAULK

          Test
          780.00

          2.
          Banana 2

            INTUMESCENT STRIP

          Test
          73,600.00

          3.
          Banana 3

            STAINLESS STEEL HOOP

          25.00
          Test

          4.
          Banana 4

            COATED FIRESTOP BOARD

          Test
          125.00

          5.
          Banana 5

            MORTAR

          Test
          185.00

Is it possible to display Background Images on specific Area only with using backgroud space, margin or padding?

Actual Result :

Expected Result :

Body:
You have to update your table structure with thead and apply background-image to tbody. You also have blank column to achieve the requirement. Mentioned changes done in the below code snippet. Try this I hope it'll help you out. Thanks

#bg_img tbody {
    background-image: url("https://image.freepik.com/free-vector/diagonal-lines-vector-background-design_1017-12303.jpg");
            background-repeat: repeat;
    background-position: left center;
    }

.blank-row {
  padding: 1%;
}

tbody tr td:first-child,
tbody tr td:last-child{
  background-color: white;
}

<div id="bg_img">
  <div id="tbles">
       <table width="100%" cellspacing="0" cellpadding="0" border="1">
          <thead>
            <tr>
              <th width="2%"></th>
              <th width="4%" align="center"><strong>No</strong></th>
              <th style="min-width:25%" align="center"><strong>Name</strong></th>
              <th style="min-width:11%" align="center"><strong>Unit</strong></th>
              <th style="width:11%" align="center"><strong>Unit Price</strong></th>
              <th width="2%"></th>
            </tr>
            <tr>
              <th class="blank-row" colspan="6"></td>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td></td>
              <td class="materialRow" align="center">1.</td>
              <td class="materialRow" align="left"><strong>Banana 1</strong><br><font style="font-size:11px;">FIRE BARRIER CAULK</font></td>
              <td class="materialRow" align="center">Test</td>
              <td class="materialRow" align="center">780.00</td>
              <td></td>
              </tr><tr>
              <td></td>
              <td class="materialRow" align="center">2.</td>
              <td class="materialRow" align="left"><strong>Banana 2</strong><br><font style="font-size:11px;">INTUMESCENT STRIP</font></td>
              <td class="materialRow" align="center">Test</td>
              <td class="materialRow" align="center">73,600.00</td>
              <td></td>
              </tr><tr>
              <td></td>
              <td class="materialRow" align="center">3.</td>
              <td class="materialRow" align="left"><strong>Banana 3</strong><br><font style="font-size:11px;">STAINLESS STEEL HOOP</font></td>
              <td class="materialRow" align="center">25.00</td>
              <td class="materialRow" align="center">Test</td>
              <td></td>
              </tr><tr>
              <td></td>
              <td class="materialRow" align="center">4.</td>
              <td class="materialRow" align="left"><strong>Banana 4</strong><br><font style="font-size:11px;">COATED FIRESTOP BOARD</font></td>
              <td class="materialRow" align="center">Test</td>
              <td class="materialRow" align="center">125.00</td>
              <td></td>
              </tr><tr>
              <td></td>
              <td class="materialRow" align="center">5.</td>
              <td class="materialRow" align="left"><strong>Banana 5</strong><br><font style="font-size:11px;">MORTAR</font></td>
              <td class="materialRow" align="center">Test</td>
              <td class="materialRow" align="center">185.00</td>
              <td></td>
            </tr>
            <tr>
              <td class="blank-row" colspan="6"></td>
            </tr>
      </tbody>
    </table>
  </div>
</div>


问:
String cells data is not visible in excel editor when excel is created using SXSSFWorkbook and modified using XSSFWorkbook
Scenario:

1) A csv file is converted into excel file using SXSSFWorkbook.
2) If the data is again read from CSV file and written to the above generated excel file using XSSFWorkbook then the string data is not visible in libre office but data is visible if the excel file is opened in online excel viewer(some of the excel viewers are mentioning that the file is corrupt and data can be recoverable).

Cell creation Using SXSSFWorkbook:

Cell cell = row.createCell(1);

cell.setCellValue("Some Value");

Cell updation using XSSFWorkbook:

Cell cell = row.getCell(1);

cell.setCellValue("Some Value");

Observations:

1) When cell value is updated using XSSFCell, then the raw value of cell and string value of the cell are different.

2) If excel file is generated with SXSSFWorkbook and opened using XSSFWorkbook then internally maintained STCellType is STCellType.INLINE_STR and if excel file is generated using XSSFWorkbook then internally maintained STCellType is STCellType.S (STCellType is used in CTCell of XSSFCell).

Apache POI Version: 4.1.0

Please suggest solution.

答:
The SXSSFWorkbook uses inline strings per default while XSSFWorkbook uses shared strings table per default. And XSSFCell.setCellValueImpl is incomplete for inline strings. It does:

```<code>...
if(_cell.getT() == STCellType.INLINE_STR) {
 //set the 'pre-evaluated result
 _cell.setV(str.getString());
}
...
</code>```

So for inline strings it always sets v element containing the text. But inline strings also may have is element having t element containing the text, or even is element having different rich text runs. This is not considered using XSSFCell.

But SXSSFWorkbook can be constructed so it also uses shared strings table. See constructor SXSSFWorkbook(XSSFWorkbook workbook, int rowAccessWindowSize, boolean compressTmpFiles, boolean useSharedStringsTable). So if following constructor used:

```<code>SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook(new XSSFWorkbook(), 2, true, true);
</code>```

then no inline strings are used and later updating using XSSF will not be problematic.

If SXSSFWorkbook is not using shared strings table but inline strings, there is a problem when later updating cells using XSSF because of the incompleteness of XSSFCell in using inline strings. Possible workaround will be managing the inline strings updating with own code.

Example:

```<code>import java.io.FileOutputStream;
import java.io.FileInputStream;

import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.xssf.streaming.*;

import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellType;

public class SXSSFTest {

 public static void main(String[] args) throws Exception {

  // first create SXSSFTest.xlsx using SXSSF ============================================

  String[][] data1 = new String[][]{
   new String[]{"A1", "B1", "C1"},
   new String[]{"A2", "B2", "C2"},
   new String[]{"A3", "B3", "C3"},
   new String[]{"A4", "B4", "C4"}
  };

  SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook();
  //SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook(new XSSFWorkbook(), 2, true, true);

  SXSSFSheet sxssfSheet = sxssfWorkbook.createSheet();

  int r = 0;
  for (String[] rowValues : data1) {
   SXSSFRow row = sxssfSheet.createRow(r++);
   int c = 0;
   for (String value : rowValues) {
    SXSSFCell cell = row.createCell(c++);
    cell.setCellValue(value);
   }
  }

  FileOutputStream outputStream = new FileOutputStream("SXSSFTest.xlsx");
  sxssfWorkbook.write(outputStream);
  outputStream.close();
  sxssfWorkbook.dispose();
  sxssfWorkbook.close();

  // now reread the SXSSFTest.xlsx and update it using XSSF =============================

  String[][] data2 = new String[][]{
   new String[]{"A2 New", "B2 New", "C2 New"},
   new String[]{"A3 New", "B3 New", "C3 New"}
  };

  XSSFWorkbook xssfWorkbook = (XSSFWorkbook)WorkbookFactory.create(
                               new FileInputStream("SXSSFTest.xlsx"));

  XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0);

  r = 1;
  for (String[] rowValues : data2) {
   XSSFRow row = xssfSheet.getRow(r++); if (row == null) row = xssfSheet.createRow(r++);
   int c = 0;
   for (String value : rowValues) {
    XSSFCell cell = row.getCell(c++);
    if (cell != null) { // cell was already there
     if (cell.getCTCell().getT() == STCellType.INLINE_STR) { // cell has inline string in it
      if (cell.getCTCell().isSetIs()) { // inline string has is element
       cell.getCTCell().getIs().setT(value); // set t element in is element
      } else {
       cell.getCTCell().setV(value); // set v element of inline string
      }
     } else {
      cell.setCellValue(value); // set shared string cell value
     }
    } else {
     cell = row.createCell(c++);
     cell.setCellValue(value);
    }
   }
  }

  outputStream = new FileOutputStream("XSSFTest.xlsx");
  xssfWorkbook.write(outputStream);
  outputStream.close();
  xssfWorkbook.close();

 }
}
</code>```

After that the SXSSFTest.xlsx looks like so in my LibreOffice Calc:

All cells have inline strings in it.

And the XSSFTest.xlsx looks like so:

There all inline strings are updated correctly now.

```<code>LibreOffice
Version: 6.0.7.3
Build ID: 1:6.0.7-0ubuntu0.18.04.5
</code>```

Body:
The SXSSFWorkbook uses inline strings per default while XSSFWorkbook uses shared strings table per default. And XSSFCell.setCellValueImpl is incomplete for inline strings. It does:

...
if(_cell.getT() == STCellType.INLINE_STR) {
 //set the 'pre-evaluated result
 _cell.setV(str.getString());
}
...

So for inline strings it always sets v element containing the text. But inline strings also may have is element having t element containing the text, or even is element having different rich text runs. This is not considered using XSSFCell.

But SXSSFWorkbook can be constructed so it also uses shared strings table. See constructor SXSSFWorkbook(XSSFWorkbook workbook, int rowAccessWindowSize, boolean compressTmpFiles, boolean useSharedStringsTable). So if following constructor used:

SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook(new XSSFWorkbook(), 2, true, true);

then no inline strings are used and later updating using XSSF will not be problematic.

If SXSSFWorkbook is not using shared strings table but inline strings, there is a problem when later updating cells using XSSF because of the incompleteness of XSSFCell in using inline strings. Possible workaround will be managing the inline strings updating with own code.

Example:

import java.io.FileOutputStream;
import java.io.FileInputStream;

import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.xssf.streaming.*;

import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellType;

public class SXSSFTest {

 public static void main(String[] args) throws Exception {

  // first create SXSSFTest.xlsx using SXSSF ============================================

  String[][] data1 = new String[][]{
   new String[]{"A1", "B1", "C1"},
   new String[]{"A2", "B2", "C2"},
   new String[]{"A3", "B3", "C3"},
   new String[]{"A4", "B4", "C4"}
  };

  SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook();
  //SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook(new XSSFWorkbook(), 2, true, true);

  SXSSFSheet sxssfSheet = sxssfWorkbook.createSheet();

  int r = 0;
  for (String[] rowValues : data1) {
   SXSSFRow row = sxssfSheet.createRow(r++);
   int c = 0;
   for (String value : rowValues) {
    SXSSFCell cell = row.createCell(c++);
    cell.setCellValue(value);
   }
  }

  FileOutputStream outputStream = new FileOutputStream("SXSSFTest.xlsx");
  sxssfWorkbook.write(outputStream);
  outputStream.close();
  sxssfWorkbook.dispose();
  sxssfWorkbook.close();

  // now reread the SXSSFTest.xlsx and update it using XSSF =============================

  String[][] data2 = new String[][]{
   new String[]{"A2 New", "B2 New", "C2 New"},
   new String[]{"A3 New", "B3 New", "C3 New"}
  };

  XSSFWorkbook xssfWorkbook = (XSSFWorkbook)WorkbookFactory.create(
                               new FileInputStream("SXSSFTest.xlsx"));

  XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0);

  r = 1;
  for (String[] rowValues : data2) {
   XSSFRow row = xssfSheet.getRow(r++); if (row == null) row = xssfSheet.createRow(r++);
   int c = 0;
   for (String value : rowValues) {
    XSSFCell cell = row.getCell(c++);
    if (cell != null) { // cell was already there
     if (cell.getCTCell().getT() == STCellType.INLINE_STR) { // cell has inline string in it
      if (cell.getCTCell().isSetIs()) { // inline string has is element
       cell.getCTCell().getIs().setT(value); // set t element in is element
      } else {
       cell.getCTCell().setV(value); // set v element of inline string
      }
     } else {
      cell.setCellValue(value); // set shared string cell value
     }
    } else {
     cell = row.createCell(c++);
     cell.setCellValue(value);
    }
   }
  }

  outputStream = new FileOutputStream("XSSFTest.xlsx");
  xssfWorkbook.write(outputStream);
  outputStream.close();
  xssfWorkbook.close();

 }
}

After that the SXSSFTest.xlsx looks like so in my LibreOffice Calc:

All cells have inline strings in it.

And the XSSFTest.xlsx looks like so:

There all inline strings are updated correctly now.

LibreOffice
Version: 6.0.7.3
Build ID: 1:6.0.7-0ubuntu0.18.04.5


问:
"How to convert String Builder to Array ?"
What kind of mistake did I make in my code?

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.update_activity);

etEname = findViewById(R.id.etEname);
etSalary = findViewById(R.id.etSalary);
rbMale = findViewById(R.id.rbMale);
rbFemale = findViewById(R.id.rbFemale);
cbWork = findViewById(R.id.cbWork);
spEno = findViewById(R.id.spEno);
//creation
helper = new DBHelper(this);
Cursor cursor = helper.readAll();
String arr [] = new String[0];

StringBuilder builder=new StringBuilder();

    while(cursor.moveToNext()){
        builder.append(cursor.getString(0)+"   "+cursor.getString(1));
    }
    try {
    for (int i = 0 ; i < cursor.getCount(); i++)
        arr[i] = builder.toString();
ArrayAdapter<String> adapter = new ArrayAdapter<String>
        (this, R.layout.custom, R.id.textView2,arr );
// Add adapter to spinner
spEno.setAdapter(adapter);
}
</code>```

Simply put, I want to add specific data from the database name and id to spinner, what way?

答:
You don't need a StringBuilder:

```<code>int i = 0;
while(cursor.moveToNext()){
    arr[i++] = String.format("%s %s", cursor.getString(0), cursor.getString(1));
}

ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, R.layout.custom, R.id.textView2,arr);
spEno.setAdapter(adapter);
</code>```

Body:
What kind of mistake did I make in my code?

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.update_activity);

etEname = findViewById(R.id.etEname);
etSalary = findViewById(R.id.etSalary);
rbMale = findViewById(R.id.rbMale);
rbFemale = findViewById(R.id.rbFemale);
cbWork = findViewById(R.id.cbWork);
spEno = findViewById(R.id.spEno);
//creation
helper = new DBHelper(this);
Cursor cursor = helper.readAll();
String arr [] = new String[0];

StringBuilder builder=new StringBuilder();

    while(cursor.moveToNext()){
        builder.append(cursor.getString(0)+"   "+cursor.getString(1));
    }
    try {
    for (int i = 0 ; i < cursor.getCount(); i++)
        arr[i] = builder.toString();
ArrayAdapter<String> adapter = new ArrayAdapter<String>
        (this, R.layout.custom, R.id.textView2,arr );
// Add adapter to spinner
spEno.setAdapter(adapter);
}

Simply put, I want to add specific data from the database name and id to spinner, what way?

Body:
You don't need a StringBuilder:

int i = 0;
while(cursor.moveToNext()){
    arr[i++] = String.format("%s %s", cursor.getString(0), cursor.getString(1));
}

ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, R.layout.custom, R.id.textView2,arr);
spEno.setAdapter(adapter);


问:
Adding custom attribute to SQL DB using dynamic parameter in Azure Data factory
I have a CSV file that I need to ingest in MS SQL DB using ADF V2. Now thats a simple thing to achieve and i am able to do it. But I each file also has a Asset ID  associated with it which is dynamically generated you can think of it as a GUID.

Hence essentially, it is there so that in future I have a way to associate which record belong to which CSV as there can be multiple CSVs ingested.

I am able to retrieve the asset ID in form of dynamic parameter till Pipeline but I am not able to add it to the database. Essentially there will be one additional column called assetID against each record in DB. But how to populate it with the dynamic parameter, I am not able to find a way. Can any body help? or if there is any other way to associate a Unique ID to those records of file in DB.

答:
There are a couple of ways to go about this :

For each iteration(single csv file), use a Custom activity, read the csv file, use the pipeline parameter for the attribute you want to add and add it to the DB and then write the record to the table.

You can use a Stored Procedure activity and pass the parameter as shown in the below screenshot to add the column that you want to.

Hope this helps.


问:
How to make python command line argument continue in a new line
I have a python program which take a dozen input parameters, so normally I invoke it with
python my_script.py --inputA a --inputB b --inputC c --inputD d --inputE e --inputF f --inputG g --inputH h --inputI i --inputJ j --inputK k

This is a long line, and it is not easy to read

I tried add \ charactor after --inputA a in command line, but after return the return key, it will run, not wait for me to input another input parameter

答:
you can use  input parameter  command

param = input("Please input parameter \n")

here example :

http://en.verejava.com/?id=2022295574921


问:
Subscribe error: Property 'subscribe' does not exist on type 'void'.ts(2339)
I am learning to use Services in angular and I have problems to subscribe to my component. What am I doing wrong?

I poll with some amounts but none of them worked

Component

```<code>import { Component, OnInit } from '@angular/core';
import { Tweet } from '../Models/tweet';
import { TweetService } from '../Services/tweet.service';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-twitter',
  templateUrl: './twitter.component.html',
  styleUrls: ['./twitter.component.css']
})
export class TwitterComponent implements OnInit {

  tweet: Array<Tweet>;

  constructor( private tweetService : TweetService) {
    this.tweetService = tweetService;
   }

  ngOnInit() {
    this.tweetService.getListTweet()
      .subscribe((data : Array<Tweet>) => {
        this.tweet = data;
      },
      err => {
        console.log(err);
      });
  }

}

</code>```

This is my service, I do not know, if here is the problem or in the component

```<code>import { Injectable } from '@angular/core';
import { HttpClient } from 'selenium-webdriver/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/throw';

@Injectable({
  providedIn: 'root'
})
export class TweetService {

  baseUrl: string = "http://jsonplaceholder.typicode.com";

  constructor(private httpClient: HttpClient) {
    this.httpClient = httpClient;
   }

   getListTweet(){
    return this.httpClient.get(`${this.baseUrl}/posts`);
  }
}

</code>```

答: Inject them only in your constructor if u want more information you can check https://angular.io/guide/dependency-injection. Basically once when i provide it as argument to your constructor you have reference to you service and you are able to call all props/methods from this reference. No need attach reference in your components to them.</p>

Body:
I am learning to use Services in angular and I have problems to subscribe to my component. What am I doing wrong?

I poll with some amounts but none of them worked

Component

import { Component, OnInit } from '@angular/core';
import { Tweet } from '../Models/tweet';
import { TweetService } from '../Services/tweet.service';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-twitter',
  templateUrl: './twitter.component.html',
  styleUrls: ['./twitter.component.css']
})
export class TwitterComponent implements OnInit {

  tweet: Array<Tweet>;

  constructor( private tweetService : TweetService) {
    this.tweetService = tweetService;
   }

  ngOnInit() {
    this.tweetService.getListTweet()
      .subscribe((data : Array<Tweet>) => {
        this.tweet = data;
      },
      err => {
        console.log(err);
      });
  }

}

This is my service, I do not know, if here is the problem or in the component

import { Injectable } from '@angular/core';
import { HttpClient } from 'selenium-webdriver/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/throw';

@Injectable({
  providedIn: 'root'
})
export class TweetService {

  baseUrl: string = "http://jsonplaceholder.typicode.com";

  constructor(private httpClient: HttpClient) {
    this.httpClient = httpClient;
   }

   getListTweet(){
    return this.httpClient.get(`${this.baseUrl}/posts`);
  }
}