答:
Do not use seaborn's scatterplot() if you are not using dataframes and if you don't need the functionality that it provides. Use matplotlib's scatter() directly instead.

PS: np.matrix seems to be deprecated, use np.array instead.

```<code>scat=np.array([[0,1,2],[10,11,12],[20,21,22]])
fig, ax = plt.subplots()
ax.scatter(np.squeeze(scat[:,0]), np.squeeze(scat[:,1]), c=np.squeeze(scat[:,2]))
</code>```

Title: seaborn plot a numpy matrix with color

Body:
Do not use seaborn's scatterplot() if you are not using dataframes and if you don't need the functionality that it provides. Use matplotlib's scatter() directly instead.

PS: np.matrix seems to be deprecated, use np.array instead.

scat=np.array([[0,1,2],[10,11,12],[20,21,22]])
fig, ax = plt.subplots()
ax.scatter(np.squeeze(scat[:,0]), np.squeeze(scat[:,1]), c=np.squeeze(scat[:,2]))


来源: stackexchange

问:
Why the means are different when appending items to np.array and a list in Python
I have a code which looks like this:

```<code>list_a = []
arr = np.array([])
for _ in range(1,101):
    list_a.append(np.random.randint(1,1001,100).mean())
    arr = np.append(arr, np.random.randint(1,1001,100).mean())

print(f'casted list to np.array mean - {np.array(list_a).mean()}')
print(f'old school average - {sum(list_a)/len(list_a)}')
print(f'just arr.mean - {arr.mean()}')
print(f'first array element - {arr[0]}')
print(f'first list element - {list_a[0]}')
print(f'last arr element - {arr[99]}')
print(f'last list element - {list_a[99]}')
</code>```

This prints:

```<code>casted list to np.array mean - 498.9785
old school average - 498.97850000000005
just arr.mean - 499.5889000000001
first array element - 510.76
first list element - 518.8
last arr element - 527.54
last list element - 521.58
</code>```

Why do I get means that are not equal and why does the first and the last elements ( I am assuming the rest too ) are not equal when they are inside the same loop? Is there a difference when casting list to np.array and getting the mean vs just appending items to a np.array and getting the mean?

答:
Why do I get means that are not equal

Because the data is different, as you found with the other tests.

and why does the first and the last elements ( I am assuming the rest too ) are not equal when they are inside the same loop?

Because each time through the loop, you do np.random.randint(1,1001,100).mean() to determine a value to append to list_a, and then you do it again to determine a value to append to arr. np.random.randint is used to produce random numbers, so of course it produces a different array on each of those two calls; and so the means are different, and so the values stored are different.

Is there a difference when casting list to np.array and getting the mean vs just appending items to a np.array and getting the mean?

There is no such thing in Python as "casting", but no, you get the same value this way. I know, your output shows 498.9785 in one case and 498.97850000000005 in another. These are extremely close. Floating-point work sometimes involves a tiny amount of imprecision.

ContentLicense: CC BY-SA 4.0

Body:
I have a code which looks like this:

list_a = []
arr = np.array([])
for _ in range(1,101):
    list_a.append(np.random.randint(1,1001,100).mean())
    arr = np.append(arr, np.random.randint(1,1001,100).mean())

print(f'casted list to np.array mean - {np.array(list_a).mean()}')
print(f'old school average - {sum(list_a)/len(list_a)}')
print(f'just arr.mean - {arr.mean()}')
print(f'first array element - {arr[0]}')
print(f'first list element - {list_a[0]}')
print(f'last arr element - {arr[99]}')
print(f'last list element - {list_a[99]}')

This prints:

casted list to np.array mean - 498.9785
old school average - 498.97850000000005
just arr.mean - 499.5889000000001
first array element - 510.76
first list element - 518.8
last arr element - 527.54
last list element - 521.58

Why do I get means that are not equal and why does the first and the last elements ( I am assuming the rest too ) are not equal when they are inside the same loop? Is there a difference when casting list to np.array and getting the mean vs just appending items to a np.array and getting the mean?


问:
Create a 'release' entry in Github
I'd like to create a release entry on my Github project.

I tried this from the cli

```<code>git commit -a -m 123
git tag -a "123" -m "msg"
git push
</code>```

This commits the files but I don't see a release tab entry - nor do I see the tag.

Thanks.

答:
By default, the git push command doesn’t transfer tags to remote servers. You will have to explicitly push tags to a shared server after you have created them.

From Git Basics - Tagging

No need for the double quotes on git tag - git tag -a 123 -m "msg"

Use the --tags flag on push - git push --tags

Title: Create a 'release' entry in Github

Body:
I'd like to create a release entry on my Github project.

I tried this from the cli

git commit -a -m 123
git tag -a "123" -m "msg"
git push

This commits the files but I don't see a release tab entry - nor do I see the tag.

Thanks.


问:
How do I change the text of an Element in jsoup?
I'm iterating over an HTML document and changing the text of the elements, but Jsoup is not working when trying to change any of the elements' texts. My code is:

```<code>            // URL
            String url = "http://example.com/source.html";

            Document doc = Jsoup.connect(url)
                       .userAgent("Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0")
                       .referrer("http://www.google.com")
                       .ignoreHttpErrors(true).get();

            // Select all of the elements in the HTML
            Elements eles = doc.body().select("*");
            // For each element
            for (Element ele : eles) {

                String text = ele.ownText();
                System.out.println(text);
                ele.text("newText");

            }

            File htmlFile = new File("output.html");
            PrintWriter pw = new PrintWriter(htmlFile, "UTF-8");
            // Write our translated HTML to the output file
            pw.println(doc);
            pw.close();

</code>```

And the resulting HTML body that I get is:

```<code> <body>
  newText
 </body>
</code>```

答: You're selecting ALL elements in the document using .select("*") and the effect is that you replaced the content of the  as well so everything else is lost. Try to be more specific with selecting elements.

Body:
I'm iterating over an HTML document and changing the text of the elements, but Jsoup is not working when trying to change any of the elements' texts. My code is:

            // URL
            String url = "http://example.com/source.html";

            Document doc = Jsoup.connect(url)
                       .userAgent("Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0")
                       .referrer("http://www.google.com")
                       .ignoreHttpErrors(true).get();

            // Select all of the elements in the HTML
            Elements eles = doc.body().select("*");
            // For each element
            for (Element ele : eles) {

                String text = ele.ownText();
                System.out.println(text);
                ele.text("newText");

            }

            File htmlFile = new File("output.html");
            PrintWriter pw = new PrintWriter(htmlFile, "UTF-8");
            // Write our translated HTML to the output file
            pw.println(doc);
            pw.close();

And the resulting HTML body that I get is:

  newText

Body: You're selecting ALL elements in the document using .select("*") and the effect is that you replaced the content of the <body> as well so everything else is lost. Try to be more specific with selecting elements.


问:
How to send data to kafka topic with kafka sink?
Currently I have a sink connector which gets data from topic A and sends its to an external service.

Now I have a use case when based on some logic I should send it to topic B instead of the service.
And this logic based on the response of the target service,that will return response based on the data.
So because the data should be sent to the target system every time I couldnt use the stream api.

Is that feasible somehow?

Or should I add a kafka producer manually to my sink? If so is there any drawback?

答:
The first option, is to create a custom Kafka Connect Single Message Transform that will implement the desired logic and possibly use ExtractTopic as well (depending on how your custom smt looks like).

The second option is to build your own consumer. For example:

Step 1: Create one more topic on top of topic A

Create one more topic, say topic_a_to_target_system

Step 2: Implement your custom consumer

Implement a Kafka Consumer that consumes all the messages from topic topic_a.
At this point, you need to instantiate a Kafka Producer and based on the logic, decide whether the topic needs to be forwarded to topic_B or to the target system (topic_a_to_target_system).

Step 3: Start Sink connector on topic_a_to_target_system

Finally start your sink connector so that it sinks the data from topic topic_a_to_target_system to your target system.


问:
Error parsing parameter information in pentaho
I am developing a report using the Pentaho Report Designer. One of the parameters is DeviceId with displaytype Dropdown.
The query corresponding to this parameter is:select distinct DEVICE_ID as DeviceId from ${Categ}

When I try to publish the report in pentaho user console, I get an error message saying - "Error parsing parameter information".

If I hard code the query as:select distinct DEVICE_ID as DeviceId from dm_test,it is working fine.

Can someone please tell me where I am going wrong?

答:
You cannot parametrize the table name. Parameters in PRD are not variables you can replace before the query is passed to the JDBC driver. They're passed to JDBC as query parameters, and table names cannot be used.

You can do what you're trying to achieve with a PDI datasource (Pentaho Data Integration), passing the table name as a transformation parameter and ticking the "Replace variables in script" checkbox in a Table Input step.


问:
connect iOS/android project to firebase
When making one social media project on both Xcode and android studio platforms, how to connect both of them with firebase to make connection between the users of iPhone and android devices. </p>

答:
You should follow the setup guide for both Android and iOS

Once you've set them up on their respective IDE's and loaded them on your client they'll both connect to the same default databas thereby sharing the data.

Title: connect iOS/android project to firebase


问:
Changing CSS properties using jQuery for a markup and different CSS files
I've a HTML markup and I've several CSS files with different properties assigned for the HTML elements which will act as the theme of the markup. Say the Markup is something like

```<code><div id=main>
    <div>{More HTML elements, divs, spans etc}</div>
    <div>{More HTML elements, divs, spans etc}</div>
</div>
</code>```

And the css is like

```<code>/*first.css*/
#main{
    someProperty: values;
}

#main div, #main ul li {
    someProperty: values;
}
</code>```

Another css file

```<code>/*second.css*/
#main{
    someProperty: some other values;
}

#main div, #main ul li {
    someProperty: some other values;
}
</code>```

There are more css files with different properties and values.

What I want to do is, at the click of a button, I want to change the CSS of the markup without changing the markup. So it will be something like

```<code>$('.btn').click(function(){
    var file = $(this).attr('id');
    //remove the previous css file
    //add the new css file (filename is the js var file+'.css')
});
</code>```

I cannot keep doing $('#someId').css({ /* properties */}); as there are many properties in the CSS file.

So how do I best handle this??

答:
I would say you can have single css with different properties you want to have in different classes. Whenever you want to change something. Just remove the current class using .removeClass() and add the new class using .addClass().

In case you want to switch the css files . Have a look here

ContentLicense: CC BY-SA 3.0

Body:
I've a HTML markup and I've several CSS files with different properties assigned for the HTML elements which will act as the theme of the markup. Say the Markup is something like

{More HTML elements, divs, spans etc}

{More HTML elements, divs, spans etc}

And the css is like

/*first.css*/
#main{
    someProperty: values;
}

#main div, #main ul li {
    someProperty: values;
}

Another css file

/*second.css*/
#main{
    someProperty: some other values;
}

#main div, #main ul li {
    someProperty: some other values;
}

There are more css files with different properties and values.

What I want to do is, at the click of a button, I want to change the CSS of the markup without changing the markup. So it will be something like

$('.btn').click(function(){
    var file = $(this).attr('id');
    //remove the previous css file
    //add the new css file (filename is the js var file+'.css')
});

I cannot keep doing $('#someId').css({ /* properties */}); as there are many properties in the CSS file.

So how do I best handle this??


问:
How can I cut a hole through multiple divs to the background?
How can I cut a hole in multiple divs to the body background?

Using clip paths (Clip path inset circle?) you can cut a hole in a div, potentially animated.

But is there a way to cut through multiple divs, to either the body background, or a nominated parent div?

It would be theoretically possible to use javascript, to copy a clip-path to the parent, however it would need to be adjusted, and I could see animation being a potential issue.

答:
If you are using the radial-gradient trick, you can just stack the holes on top of each other.

Fiddle: https://jsfiddle.net/nh3reLg1/2/


问:
Javascript – return multiple values to chained "then" functions
I have a fetch call with a couple of then functions. In one of the then functions I'd like to pass two returned variables to the next then function. It doesn't work though.

```<code>.then(text => {
  let content = new DOMParser().parseFromString(text, "text/html");
  let main = content.querySelector('main').innerHTML;
  let title = content.querySelector('title').innerHTML;

  function thehtml() {
    return {
      main, title
    }
  }
})
.then(thehtml => {
  let theParsedHtml = thehtml();
  document.querySelector('main').innerHTML = theParsedHtml.main;
  document.title = theParsedHtml.title;
})
</code>```

Accessing the thehtml() function in the last then() throws a is not a function error. Thanks for any tips!

答:
You can modify the code like below, through which you can get access to the title and main in the other then method.

.then(text => {
  let content = new DOMParser().parseFromString(text, "text/html");
  let main = content.querySelector('main').innerHTML;
  let title = content.querySelector('title').innerHTML;

  return {
    main, title
  }
})
.then(thehtml => {
  document.querySelector('main').innerHTML = thehtml.main;
  document.title = thehtml.title;
})
```

Body:
I have a fetch call with a couple of then functions. In one of the then functions I'd like to pass two returned variables to the next then function. It doesn't work though.

.then(text => {
  let content = new DOMParser().parseFromString(text, "text/html");
  let main = content.querySelector('main').innerHTML;
  let title = content.querySelector('title').innerHTML;

  function thehtml() {
    return {
      main, title
    }
  }
})
.then(thehtml => {
  let theParsedHtml = thehtml();
  document.querySelector('main').innerHTML = theParsedHtml.main;
  document.title = theParsedHtml.title;
})

Accessing the thehtml() function in the last then() throws a is not a function error. Thanks for any tips!


问:
OneToMany relation when using custom identifier in GraphQL returns null/wrong data
I am using api-platform with Symfony 5 to build GraphQl API.

When using custom identifier that is not a primary key, OneToMany result set returns null or wrong data. This issue is caused because when fetching data from OneToMany table, the custom identifier value is used instead of primary key.

Example

Table Blog has a custom identifier slug and primary key id. This table have a OneToMany relationship with Table Image

These are the queries made while fetching data:

```<code>SELECT b0_.id AS id_0, b0_.content AS content_1,  b0_.slug AS slug_3 FROM blog b0_ WHERE b0_.slug = "highest peak"

SELECT i0_.id AS id_0, i0_.src AS src_1 FROM image i0_ WHERE i0_.blog_id = "highest peak" ORDER BY i0_.id ASC LIMIT 30
</code>```

While fetching from image , Blog ID should be sent in parameters but slug is used.

However, things are working fine in REST. Problem is encountered while using GraphQL.

答:
Downgrading to 2.5.4 from 2.5.6 fixed the problem.

Possible Issue

The src/Bridge/Doctrine/Orm/SubresourceDataProvider.php was updated on the version 2.5.5

Body:
I am using api-platform with Symfony 5 to build GraphQl API.

When using custom identifier that is not a primary key, OneToMany result set returns null or wrong data. This issue is caused because when fetching data from OneToMany table, the custom identifier value is used instead of primary key.

Example

Table Blog has a custom identifier slug and primary key id. This table have a OneToMany relationship with Table Image

These are the queries made while fetching data:

SELECT b0_.id AS id_0, b0_.content AS content_1,  b0_.slug AS slug_3 FROM blog b0_ WHERE b0_.slug = "highest peak"

SELECT i0_.id AS id_0, i0_.src AS src_1 FROM image i0_ WHERE i0_.blog_id = "highest peak" ORDER BY i0_.id ASC LIMIT 30

While fetching from image , Blog ID should be sent in parameters but slug is used.

However, things are working fine in REST. Problem is encountered while using GraphQL.


问:
using python selenium in web scraping, want to print a web table data on to console using for loop
Please help me with the below code. I want to print it in table format with total rows = 35, columns = 6.</p>

```<code>from bs4 import BeautifulSoup
import requests
#import urllib.request
from tabulate import tabulate
from selenium import webdriver   # for webdriver
from selenium.webdriver.chrome.options import Options  # for suppressing the browser

class States():
    def __init__(self):
        url = "https://www.mohfw.gov.in/"
        # self.res = requests.get(url)
        # self.soup = BeautifulSoup(self.res.text, 'lxml')
        self.op = webdriver.ChromeOptions()
        self.op.add_argument('headless')
        self.driver = webdriver.Chrome(executable_path= "C:\web drivers\drivers\chromedriver_win32\chromedriver.exe", options= self.op)
        self.driver.get(url)
        self.driver.find_element_by_class_name("open-table").click()

    def get_data(self):
        print("S.No"     "Name of State / UT"     "Active Cases*"     "Cured/Discharged/Migrated*"     "Deaths**"     "Total Confirmed cases*")
        self.base_table = self.driver.find_element_by_tag_name("table")
        table_row = 35
        table_cols = 6

        for i in range(1, table_row +1):
            for j in range(1, table_cols +1):
                print(self.base_table.find_element_by_xpath("//*[@id='state-data']/div/div/div/div/table/tbody/tr[" +str(i)+"]/td[" + str(j) + "]").text)

state=States()
state.get_data()
</code>```

答:
Could you please provide the url for better understanding? If you are particularly looking to scrape a table data from web, the best way to look use BeautifulSoup. identify the class name and you can simply loop through the row and individual data. have a look at the following snippet</p>

```<code>from bs4 import BeautifulSoup
import requests

url = "https://www.imdb.com/india/top-rated-indian-movies/?pf_rd_m=A2FGELUUNOQJNL&pf_rd_p=8a7876cd-2844-4017-846a-2c0876945b7b&pf_rd_r=JYVEVKT1J5S5HQZEVYN1&pf_rd_s=right-5&pf_rd_t=15506&pf_rd_i=boxoffice&ref_=chtbo_india_tr_rhs_1"

response = requests.get(url)
data = response.text
soup = BeautifulSoup(data,'html.parser')

movie_rating = []
movie_name = []

#identifying the table using class name
imdb_table = soup.find('table', class_ = 'chart full-width')

for imdb in imdb_table.find_all('tbody'):
    #find all rows together
    rows = imdb.find_all('tr')
    #simply loop through individual element
    for row in rows:
        name = row.find('td', class_ = 'titleColumn').text
        movie_name.append(re.sub('[^A-Za-z]+', ' ',name))
        rating = row.find('td', class_ = 'ratingColumn imdbRating').text
        movie_rating.append(float(rating))
</code>```

Body:
Please help me with the below code. I want to print it in table format with total rows = 35, columns = 6.

from bs4 import BeautifulSoup
import requests
#import urllib.request
from tabulate import tabulate
from selenium import webdriver   # for webdriver
from selenium.webdriver.chrome.options import Options  # for suppressing the browser

class States():
    def __init__(self):
        url = "https://www.mohfw.gov.in/"
        # self.res = requests.get(url)
        # self.soup = BeautifulSoup(self.res.text, 'lxml')
        self.op = webdriver.ChromeOptions()
        self.op.add_argument('headless')
        self.driver = webdriver.Chrome(executable_path= "C:\web drivers\drivers\chromedriver_win32\chromedriver.exe", options= self.op)
        self.driver.get(url)
        self.driver.find_element_by_class_name("open-table").click()

    def get_data(self):
        print("S.No"     "Name of State / UT"     "Active Cases*"     "Cured/Discharged/Migrated*"     "Deaths**"     "Total Confirmed cases*")
        self.base_table = self.driver.find_element_by_tag_name("table")
        table_row = 35
        table_cols = 6

        for i in range(1, table_row +1):
            for j in range(1, table_cols +1):
                print(self.base_table.find_element_by_xpath("//*[@id='state-data']/div/div/div/div/table/tbody/tr[" +str(i)+"]/td[" + str(j) + "]").text)

state=States()
state.get_data()

Body:
Could you please provide the url for better understanding? If you are particularly looking to scrape a table data from web, the best way to look use BeautifulSoup. identify the class name and you can simply loop through the row and individual data. have a look at the following snippet

from bs4 import BeautifulSoup
import requests

url = "https://www.imdb.com/india/top-rated-indian-movies/?pf_rd_m=A2FGELUUNOQJNL&pf_rd_p=8a7876cd-2844-4017-846a-2c0876945b7b&pf_rd_r=JYVEVKT1J5S5HQZEVYN1&pf_rd_s=right-5&pf_rd_t=15506&pf_rd_i=boxoffice&ref_=chtbo_india_tr_rhs_1"

response = requests.get(url)
data = response.text
soup = BeautifulSoup(data,'html.parser')

movie_rating = []
movie_name = []

#identifying the table using class name
imdb_table = soup.find('table', class_ = 'chart full-width')

for imdb in imdb_table.find_all('tbody'):
    #find all rows together
    rows = imdb.find_all('tr')
    #simply loop through individual element
    for row in rows:
        name = row.find('td', class_ = 'titleColumn').text
        movie_name.append(re.sub('[^A-Za-z]+', ' ',name))
        rating = row.find('td', class_ = 'ratingColumn imdbRating').text
        movie_rating.append(float(rating))


问:
How to pass 2 javascript events in one click?
I want to pass 2 javascript events in one click, I put 2 of them into href and onclick. But when I click, it always executes the onclick action. Click again or a third time, the href action gets executed. I do not know how it was like this.

How do I to solve it?

If I combine 2 javascript events in one part(href or onclick). is it could run well? how to?

thanks.

```<code><a href="javascript:function1('value1')" onclick="javascript:function2('value2')">
</code>```

答:
I think you could just do:</p>

```<code><a href="#" onclick="function1('value1'); function2('value2');">
</code>```

Body:
I think you could just do:

<a href="#" onclick="function1('value1'); function2('value2');">


问:
How can I set the date from one date input to another date input?
I have two date inputs. When I choose start date, I want jquery to automatically generate an end date that's 3 months later.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

    Start Date
    <input type="date" id="darbo_pradzia" name="darbo_pradzia" class="form-control">

    End date
    <input type="date" id="bandomasis_laikotarpis" name="bandomasis_laikotarpis" class="form-control">

```

答:
You should listen to change events of the first input and create a new Date with its value. After that, you can add 3 months to this object using new Date(date.setMonth(date.getMonth()+3)). The new date with the extra 3 months should be formatted into yyyy-mm-dd and set to the value of the second input. The complete program is:

$(document).ready(function() {
     $('#darbo_pradzia').change(function(){
          let date = new Date($(this).val());
          let newDate = addMonths(date, 3);
          var formatted = newDate.toISOString().split('T')[0]; //yyyy-mm-dd
          console.log(formatted);
          $('#bandomasis_laikotarpis').val(formatted);
     });
     //add months to date function
     function addMonths(date, months) {
          var d = date.getDate();
          date.setMonth(date.getMonth() + +months);
          if (date.getDate() != d) {
               date.setDate(0);
          }
          return date;
     }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://kit.fontawesome.com/04b00d367c.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

<div class="container">
     <div class="col-md-6">
          <label class="text-black" for="dpradzia">Start Date</label>
          <input type="date" id="darbo_pradzia" name="darbo_pradzia" class="form-control">
     </div>
     <div class="col-md-6">
          <label class="text-black" for="bandomasis_laikotarpis">End date </label>
          <input type="date" id="bandomasis_laikotarpis" name="bandomasis_laikotarpis" class="form-control">
     </div>
</div></code>```

EDIT :
According to @RobG's comment, adding a number of months to a date object has several unique test cases that need to be taken into consideration. Therefore, I used his answer in this post to achieve this operation.

Body:
You should listen to change events of the first input and create a new Date with its value. After that, you can add 3 months to this object using new Date(date.setMonth(date.getMonth()+3)). The new date with the extra 3 months should be formatted into yyyy-mm-dd and set to the value of the second input. The complete program is:

$(document).ready(function() {
     $('#darbo_pradzia').change(function(){
          let date = new Date($(this).val());
          let newDate = addMonths(date, 3);
          var formatted = newDate.toISOString().split('T')[0]; //yyyy-mm-dd
          console.log(formatted);
          $('#bandomasis_laikotarpis').val(formatted);
     });
     //add months to date function
     function addMonths(date, months) {
          var d = date.getDate();
          date.setMonth(date.getMonth() + +months);
          if (date.getDate() != d) {
               date.setDate(0);
          }
          return date;
     }
});

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://kit.fontawesome.com/04b00d367c.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

<div class="container">
     <div class="col-md-6">
          <label class="text-black" for="dpradzia">Start Date</label>
          <input type="date" id="darbo_pradzia" name="darbo_pradzia" class="form-control">
     </div>
     <div class="col-md-6">
          <label class="text-black" for="bandomasis_laikotarpis">End date </label>
          <input type="date" id="bandomasis_laikotarpis" name="bandomasis_laikotarpis" class="form-control">
     </div>
</div>

EDIT :
According to @RobG's comment, adding a number of months to a date object has several unique test cases that need to be taken into consideration. Therefore, I used his answer in this post to achieve this operation.


问:
Compare two object arrays and get the difference in Javascript
I have two arrays of objects:

```<code>\\offers
[
{DeskUID: "B11A13", Day: 06 Jun 2020}
{DeskUID: "B11A13", Day: 07 Jun 2020}
{DeskUID: "B12B34", Day: 23 Jun 2020}
]

\\reservations
[
{DeskUID: "B11A13", Day: 06 Jun 2020, Name: "Mike"}
{DeskUID: "B12B34", Day: 23 Jun 2020, Name: "Ali"}
]
</code>```

I would like to have a result where are available offers, that means only the offers without already reserved desks.

```<code>\\result
[
{DeskUID: "B11A13", Day: 07 Jun 2020}
]
</code>```

How to get the difference between two arrays of objects in JavaScript

I already tried solutions on the link above but without success, I just got a result array as sum of all objects from the two arrays.

```<code>            function comparer(otherArray){
                return function(current){
                var reserveDay = new Date (current.Day)
                    return otherArray.filter(function(other){
                        var offerDay = new Date (other.Day)
                        return other.DeskUID == current.DeskUID && offerDay == reserveDay
                    }).length == 0;
                }
            }

            var onlyInA = offers.filter(comparer(reservations));
            var onlyInB = reservations.filter(comparer(offers));

            result = onlyInA.concat(onlyInB);
</code>```

答:
You could take a Set and filter the reservations.

var getKey = ({ DeskUID, Day }) => [DeskUID, Day].join('|'),
    offers = [{ DeskUID: "B11A13", Day: "2020-06-06" }, { DeskUID: "B11A13", Day: "2020-06-07" }, { DeskUID: "B12B34", Day: "2020-06-23" }],
    reservations = [{ DeskUID: "B11A13", Day: "2020-06-06", Name: "Mike" }, { DeskUID: "B12B34", Day: "2020-06-23", Name: "Ali" }],
    reservationsSet = new Set(reservations.map(getKey)),
    open = offers.filter(o => !reservationsSet.has(getKey(o)));

console.log(open);```

Body:
I have two arrays of objects:

\\offers
[
{DeskUID: "B11A13", Day: 06 Jun 2020}
{DeskUID: "B11A13", Day: 07 Jun 2020}
{DeskUID: "B12B34", Day: 23 Jun 2020}
]

\\reservations
[
{DeskUID: "B11A13", Day: 06 Jun 2020, Name: "Mike"}
{DeskUID: "B12B34", Day: 23 Jun 2020, Name: "Ali"}
]

I would like to have a result where are available offers, that means only the offers without already reserved desks.

\\result
[
{DeskUID: "B11A13", Day: 07 Jun 2020}
]

How to get the difference between two arrays of objects in JavaScript

I already tried solutions on the link above but without success, I just got a result array as sum of all objects from the two arrays.

            function comparer(otherArray){
                return function(current){
                var reserveDay = new Date (current.Day)
                    return otherArray.filter(function(other){
                        var offerDay = new Date (other.Day)
                        return other.DeskUID == current.DeskUID && offerDay == reserveDay
                    }).length == 0;
                }
            }

            var onlyInA = offers.filter(comparer(reservations));
            var onlyInB = reservations.filter(comparer(offers));

            result = onlyInA.concat(onlyInB);


问:
Returning JSON results to API calls from already existing Controller actions in ASP.NET MVC 5
I am new to ASP.NET WebApi. I am working on an ASP.NET MVC 5 project.

When I started it, it wasn't built considering WebApi functionality. I kept on building on it. It's completely an MVC project as of now. I have coded lots of Controllers, which contain various actions, like fetching results of queries from DB.

Now I want to add WebApi support to the project. For eg: I have a controller action, which fetches a bunch of data from the DB. Now, I need to return the data in say, JSON format.

My question is, do I need to write all such functions once again to fetch the data and return it as JSON? I do have a lot of actions across various controllers. Rewriting those actions once again would be a lot of work. If possible, how can it be done with minimal addition to the code, while also not disrupting the normal functioning of the current MVC project?

This is just an example of an action in one of the MVC controllers:

```<code>public string GetName()
{
    string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
    string stud_name;

    using (SqlConnection con = new SqlConnection(constr))
    {
        SqlCommand cmd = new SqlCommand('SELECT name FROM Table WHERE id = 232', con);

        stud_name = Convert.ToString(cmd.ExecuteScalar());

    }

    return stud_name;

}
</code>```

I had written this function some time ago. There are several others like this, which return other things. Considering this action, how do I return the string as JSON object to the api call? Is there a way to do that without rewriting the function for ApiController?

答: You can add methods to the common class and call these methods from both types of controller's action methods.</p>

Body:
I am new to ASP.NET WebApi. I am working on an ASP.NET MVC 5 project.

When I started it, it wasn't built considering WebApi functionality. I kept on building on it. It's completely an MVC project as of now. I have coded lots of Controllers, which contain various actions, like fetching results of queries from DB.

Now I want to add WebApi support to the project. For eg: I have a controller action, which fetches a bunch of data from the DB. Now, I need to return the data in say, JSON format.

My question is, do I need to write all such functions once again to fetch the data and return it as JSON? I do have a lot of actions across various controllers. Rewriting those actions once again would be a lot of work. If possible, how can it be done with minimal addition to the code, while also not disrupting the normal functioning of the current MVC project?

This is just an example of an action in one of the MVC controllers:

public string GetName()
{
    string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
    string stud_name;

    using (SqlConnection con = new SqlConnection(constr))
    {
        SqlCommand cmd = new SqlCommand('SELECT name FROM Table WHERE id = 232', con);

        stud_name = Convert.ToString(cmd.ExecuteScalar());

    }

    return stud_name;

}

I had written this function some time ago. There are several others like this, which return other things. Considering this action, how do I return the string as JSON object to the api call? Is there a way to do that without rewriting the function for ApiController?


问:
how to type define a zip function in typescript
Say I want to create a zip function:

function zip(arrays){
    // assume more than 1 array is given and all arrays
    // share the same length
    const len = arrays[0].length;
    const toReturn = new Array(len);
    for (let i = 0; i < len; i++){
        toReturn[i] = arrays.map(array=>array[i]);
    }
    return toReturn;
}

console.log(zip([
    [1,2,3],
    [4,5,6],
    [7,8,9],
    [10,11,12],
]));
/*
Output:
(3) [Array(4), Array(4), Array(4)]
0: (4) [1, 4, 7, 10]
1: (4) [2, 5, 8, 11]
2: (4) [3, 6, 9, 12]
*/
```

<p>In order to type define this function when all arrays hold the same type of elements:</p>

<pre class="lang-js prettyprint-override"><code>    function zip<T>(arrays: T[][]): T[][]{/* codes omited here */}
</code>```

However, when arrays are of different types of elements, I get confused about how to use generic type to finish the type definition.

    const zipedResult = zip([[1,2,3],[true,false,true],['a','b','c']]);
    // error raises: Type 'false' is not assignable to type 'number'.(2322)
```

<p>what I want is </p>

<pre class="lang-js prettyprint-override"><code>    [[1,2,3],[true,false,true],['a','b','c']]
</code>```

could be automatically infered as (number|boolean|string)[][] without writing as (number|boolean|string)[][]
or EVEN
infered as [number[],boolean[],string[]] and result of zip infered as [number, boolean, string][]

How should I correctly type define zip to fullfill such features?

答:
The only way I can see to do this is to define a different zip function for each size of array you'd like to handle (as we need to be able to say exactly what is in each part of the zip result):

const zip3 = <T, U, V>(arrays: [T[], U[], V[]]): [T, U, V][] => {
    const len = arrays[0].length;
    const toReturn: [T, U, V][] = new Array(len);
    for (let i = 0; i < len; i++){
        toReturn[i] = [arrays[0][i], arrays[1][i], arrays[2][i]];
    }
    return toReturn;
};

const result = zip3([
    [1,2,3],
    [true, false, true],
    [7,8,9],
]);

console.log(result);
```

Hopefully someone can come in and show a better way to do this, without having to redefine the function dependent on how many arrays you'd like to zip;

Body:
Say I want to create a zip function:

function zip(arrays){
    // assume more than 1 array is given and all arrays
    // share the same length
    const len = arrays[0].length;
    const toReturn = new Array(len);
    for (let i = 0; i < len; i++){
        toReturn[i] = arrays.map(array=>array[i]);
    }
    return toReturn;
}

console.log(zip([
    [1,2,3],
    [4,5,6],
    [7,8,9],
    [10,11,12],
]));
/*
Output:
(3) [Array(4), Array(4), Array(4)]
0: (4) [1, 4, 7, 10]
1: (4) [2, 5, 8, 11]
2: (4) [3, 6, 9, 12]
*/

In order to type define this function when all arrays hold the same type of elements:

    function zip<T>(arrays: T[][]): T[][]{/* codes omited here */}

However, when arrays are of different types of elements, I get confused about how to use generic type to finish the type definition.

    const zipedResult = zip([[1,2,3],[true,false,true],['a','b','c']]);
    // error raises: Type 'false' is not assignable to type 'number'.(2322)

what I want is

    [[1,2,3],[true,false,true],['a','b','c']]

could be automatically infered as (number|boolean|string)[][] without writing as (number|boolean|string)[][]
or EVEN
infered as [number[],boolean[],string[]] and result of zip infered as [number, boolean, string][]

How should I correctly type define zip to fullfill such features?

Body:
The only way I can see to do this is to define a different zip function for each size of array you'd like to handle (as we need to be able to say exactly what is in each part of the zip result):

const zip3 = <T, U, V>(arrays: [T[], U[], V[]]): [T, U, V][] => {
    const len = arrays[0].length;
    const toReturn: [T, U, V][] = new Array(len);
    for (let i = 0; i < len; i++){
        toReturn[i] = [arrays[0][i], arrays[1][i], arrays[2][i]];
    }
    return toReturn;
};

const result = zip3([
    [1,2,3],
    [true, false, true],
    [7,8,9],
]);

console.log(result);

Hopefully someone can come in and show a better way to do this, without having to redefine the function dependent on how many arrays you'd like to zip;


问:
How do I enable "--enable-preview" for tests?
How do I enable "--enable-preview" for tests in Kotlin-based Gradle script ? I tried literally everything I could find online with https://stackoverflow.com/a/61849770/226895 being the closest to correct answer.

I still get following error on :test task

```<code>org.gradle.api.internal.tasks.testing.TestSuiteExecutionException: Could not execute test class 'com.blabla.playground.AppTest'.
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:53)
Caused by: java.lang.UnsupportedClassVersionError: Preview features are not enabled for com/blabla/playground/AppTest (class file version 58.65535). Try running with '--enable-preview'
    at java.base/java.lang.ClassLoader.defineClass1(Native Method)

</code>```

by script is

```<code>plugins {
    java
    application
}

repositories {
    jcenter()
}

dependencies {
    implementation("com.google.guava:guava:28.2-jre")
    testImplementation("org.junit.jupiter:junit-jupiter-api:5.6.0")
    testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.6.0")
}

application {
    mainClassName = "com.blabla.playground.App"
}

java {
    sourceCompatibility = JavaVersion.VERSION_14
    targetCompatibility = JavaVersion.VERSION_14
}

tasks {
    withType<Test>().all {
        allJvmArgs.add("--enable-preview")
        testLogging.showStandardStreams = true
        testLogging.showExceptions = true
        useJUnitPlatform {
        }
    }

    withType<JavaExec>().all {
        jvmArgs!!.add("--enable-preview")
    }

    withType<Wrapper>().all {
        gradleVersion = "6.4.1"
        distributionType = Wrapper.DistributionType.BIN
    }

    withType(JavaCompile::class.java).all {
        options.compilerArgs.addAll(listOf("--enable-preview", "-Xlint:preview"))
    }

    jar {
        manifest {
            attributes("Main-Class" to "com.blabla.playground.App")
        }
    }
}
</code>```

What am I missing?

答:
It turned out that the way you are configuring the flag for Test tasks does not really append the flag to allJvmArgs.

I managed to made it work by configuring the Test tasks like so :

```<code>withType<Test>().all {
    jvmArgs("--enable-preview")
}
</code>```

or

```<code>withType<Test>().all {
    allJvmArgs = listOf("--enable-preview")
}
</code>```

However the second option might not be preferable as it substitutes all JVM arguments for forked process (including arguments to define system properties, the minimum/maximum heap size, and the bootstrap classpath). The first option should be preferrable.

Body:
How do I enable "--enable-preview" for tests in Kotlin-based Gradle script ? I tried literally everything I could find online with https://stackoverflow.com/a/61849770/226895 being the closest to correct answer.

I still get following error on :test task

org.gradle.api.internal.tasks.testing.TestSuiteExecutionException: Could not execute test class 'com.blabla.playground.AppTest'.
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:53)
Caused by: java.lang.UnsupportedClassVersionError: Preview features are not enabled for com/blabla/playground/AppTest (class file version 58.65535). Try running with '--enable-preview'
    at java.base/java.lang.ClassLoader.defineClass1(Native Method)

by script is

plugins {
    java
    application
}

repositories {
    jcenter()
}

dependencies {
    implementation("com.google.guava:guava:28.2-jre")
    testImplementation("org.junit.jupiter:junit-jupiter-api:5.6.0")
    testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.6.0")
}

application {
    mainClassName = "com.blabla.playground.App"
}

java {
    sourceCompatibility = JavaVersion.VERSION_14
    targetCompatibility = JavaVersion.VERSION_14
}

tasks {
    withType<Test>().all {
        allJvmArgs.add("--enable-preview")
        testLogging.showStandardStreams = true
        testLogging.showExceptions = true
        useJUnitPlatform {
        }
    }

    withType<JavaExec>().all {
        jvmArgs!!.add("--enable-preview")
    }

    withType<Wrapper>().all {
        gradleVersion = "6.4.1"
        distributionType = Wrapper.DistributionType.BIN
    }

    withType(JavaCompile::class.java).all {
        options.compilerArgs.addAll(listOf("--enable-preview", "-Xlint:preview"))
    }

    jar {
        manifest {
            attributes("Main-Class" to "com.blabla.playground.App")
        }
    }
}

What am I missing?

Body:
It turned out that the way you are configuring the flag for Test tasks does not really append the flag to allJvmArgs.

I managed to made it work by configuring the Test tasks like so :

withType<Test>().all {
    jvmArgs("--enable-preview")
}

or

withType<Test>().all {
    allJvmArgs = listOf("--enable-preview")
}

However the second option might not be preferable as it substitutes all JVM arguments for forked process (including arguments to define system properties, the minimum/maximum heap size, and the bootstrap classpath). The first option should be preferrable.


问:
find the corresponding control in repeater control
I have a Repeater control which contains a CheckBox and a lable control in each row. When a CheckBox is selected. I want to retrieve the text of the Label for the corresponding CheckBox. How to get it?

答:
Add the following to the CheckBox.Checked event handler:

```<code>CheckBox checkBox = (CheckBox) sender;
Label label = (Label) checkBox.Parent.FindControl("LabelName");
String labelText = label.Text;
</code>```

Body:
Add the following to the CheckBox.Checked event handler:

CheckBox checkBox = (CheckBox) sender;
Label label = (Label) checkBox.Parent.FindControl("LabelName");
String labelText = label.Text;


问:
why switchMap not working in Angular interceptor ( Angular 9 )
I wrote an Interceptor to refresh token for me. But with the debugger I checked, it doesn't enter switchMap at all, and the request doesn't send it again.
Does anyone know where the problem comes from?

```<code>    import {HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from '@angular/common/http';
import {Injectable, Injector} from '@angular/core';
import {BehaviorSubject, Observable} from 'rxjs';
import {catchError, switchMap, tap} from 'rxjs/operators';
import {ResponseModel} from '../Models/responseModel';
import {UserDataModel} from '../Models/UserDataModel';
import {RoleEnum} from '../Enums/RoleEnum';
import {AuthService} from '../../auth/auth.service';
import {AuthModel} from '../Models/authModel';
import {LoginType} from '../Enums/LoginType';
import {LoginResponseModel} from '../Models/LoginResponseModel';

@Injectable({providedIn: 'root'})
export class TokenInterceptor implements HttpInterceptor {
    httpSubject: BehaviorSubject<LoginResponseModel> = new BehaviorSubject<LoginResponseModel>(null);

    constructor(private injector: Injector) {
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        let modifiedReq;
        const userData: {
            username: string,
            access_token: string,
            refresh_token: string,
            role: RoleEnum,
            _tokenexpirationDate: string
        } = (JSON.parse(localStorage.getItem('userData')));
        if (userData.access_token !== null && !req.headers.has('X-Skip-Interceptor')) {
            modifiedReq = req.clone({
                headers: req.headers.set('access_token', `${userData.access_token}`),
            });
        } else {
            modifiedReq = req.clone({
                setHeaders: {
                    'Content-Type': 'application/json',
                    'Access-Control-Allow-Origin': '*'
                }
            });
        }
        return next.handle(modifiedReq).pipe(tap(res => {
            if (res instanceof HttpResponse) {
                const response = (<HttpResponse<ResponseModel<string>>> res).body;
                /*const userdata: {
                    username: string,
                    access_token: string,
                    refresh_token: string,
                    role: RoleEnum,
                    _tokenexpirationDate: string
                } = (JSON.parse(localStorage.getItem('userData')));*/
                if (!response.is_successfull) {
                    if (new Date() > new Date(userData._tokenexpirationDate)) {
                        this.refreshToken(req, next, userData.refresh_token, userData.username);
                    }
                }
            }
        }));
    }

    refreshToken(req: HttpRequest<any>, next: HttpHandler, refreshtoken: string, username: string) {
        this.httpSubject.next(null);
        const authService = this.injector.get(AuthService);
        const authmodel: AuthModel = {
            email_address: '', grant_type: LoginType.RefreshToken, password: '', phone_number: '', phone_number_countery_iso2_code: '',
            refresh_token: refreshtoken, username: ''
        };

        debugger;
        return authService.Signin(authmodel).pipe(
            switchMap(result => {
                debugger;
                if (result.is_successfull && result.response.access_token !== null) {
                    const expirationDate = new Date(new Date().getTime() + +result.response.expires_in * 60000);
                    const user = new UserDataModel(username, result.response.access_token, result.response.refresh_token
                        , result.response.role, expirationDate);
                    localStorage.setItem('userData', JSON.stringify(user));
                    this.httpSubject.next(result.response);
                    req = req.clone({
                        setHeaders: {
                            access_token: `${result.response.access_token}`
                        }
                    });
                    return next.handle(req);

                }

            }) , catchError(err => {
                console.log(err);
                return Observable;
            }));
    }
}
</code>```

I would also like to say that if I use subscribe instead of pipe, switchMap, the token will be refreshed and only the request will not be repeated from the beginning.

答:
Your code should be :-

```<code>   import {HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from '@angular/common/http';
import {Injectable, Injector} from '@angular/core';
import {BehaviorSubject, Observable} from 'rxjs';
import {catchError, switchMap, tap} from 'rxjs/operators';
import {ResponseModel} from '../Models/responseModel';
import {UserDataModel} from '../Models/UserDataModel';
import {RoleEnum} from '../Enums/RoleEnum';
import {AuthService} from '../../auth/auth.service';
import {AuthModel} from '../Models/authModel';
import {LoginType} from '../Enums/LoginType';
import {LoginResponseModel} from '../Models/LoginResponseModel';

@Injectable({providedIn: 'root'})
export class TokenInterceptor implements HttpInterceptor {
    httpSubject: BehaviorSubject<LoginResponseModel> = new BehaviorSubject<LoginResponseModel>(null);

    constructor(private injector: Injector) {
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        let modifiedReq;
        const userData: {
            username: string,
            access_token: string,
            refresh_token: string,
            role: RoleEnum,
            _tokenexpirationDate: string
        } = (JSON.parse(localStorage.getItem('userData')));
        if (userData.access_token !== null && !req.headers.has('X-Skip-Interceptor')) {
            modifiedReq = req.clone({
                headers: req.headers.set('access_token', `${userData.access_token}`),
            });
        } else {
            modifiedReq = req.clone({
                setHeaders: {
                    'Content-Type': 'application/json',
                    'Access-Control-Allow-Origin': '*'
                }
            });
        }
        return next.handle(modifiedReq).pipe(tap(res => {
            if (res instanceof HttpResponse) {
                const response = (<HttpResponse<ResponseModel<string>>> res).body;
                /*const userdata: {
                    username: string,
                    access_token: string,
                    refresh_token: string,
                    role: RoleEnum,
                    _tokenexpirationDate: string
                } = (JSON.parse(localStorage.getItem('userData')));*/
                if (!response.is_successfull) {
                    if (new Date() > new Date(userData._tokenexpirationDate)) {
                        this.refreshToken(req, next, userData.refresh_token, userData.username).then((request)=> {

                                   modifiedRequest = request.clone();
                                   throw "replay";
                     });
                    }
                }

        }),retryWhen(errors => errors);
    }

refreshToken(req: HttpRequest<any>, next: HttpHandler, refreshtoken: string, username: string) {
            this.httpSubject.next(null);
            const authService = this.injector.get(AuthService);
            const authmodel: AuthModel = {
                email_address: '', grant_type: LoginType.RefreshToken, password: '', phone_number: '', phone_number_countery_iso2_code: '',
                refresh_token: refreshtoken, username: ''
            };

            debugger;
            return await authService.Signin(authmodel).pipe(
                map(result => {
                    debugger;
                    if (result.is_successfull && result.response.access_token !== null) {
                        const expirationDate = new Date(new Date().getTime() + +result.response.expires_in * 60000);
                        const user = new UserDataModel(username, result.response.access_token, result.response.refresh_token
                            , result.response.role, expirationDate);
                        localStorage.setItem('userData', JSON.stringify(user));
                        this.httpSubject.next(result.response);
                        req = req.clone({
                            setHeaders: {
                                access_token: `${result.response.access_token}`
                            }
                        });
                        return req;

                    }

                }) , catchError(err => {
                    console.log(err);
                    return Observable;
                })).toPromise();
        }
    }
</code>```

Reason :- Tap doesn't subscribe to inner observable you was returning. mergemap does that. stream combination should be done with proper operators.

Body:
I wrote an Interceptor to refresh token for me. But with the debugger I checked, it doesn't enter switchMap at all, and the request doesn't send it again.
Does anyone know where the problem comes from?

    import {HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from '@angular/common/http';
import {Injectable, Injector} from '@angular/core';
import {BehaviorSubject, Observable} from 'rxjs';
import {catchError, switchMap, tap} from 'rxjs/operators';
import {ResponseModel} from '../Models/responseModel';
import {UserDataModel} from '../Models/UserDataModel';
import {RoleEnum} from '../Enums/RoleEnum';
import {AuthService} from '../../auth/auth.service';
import {AuthModel} from '../Models/authModel';
import {LoginType} from '../Enums/LoginType';
import {LoginResponseModel} from '../Models/LoginResponseModel';

@Injectable({providedIn: 'root'})
export class TokenInterceptor implements HttpInterceptor {
    httpSubject: BehaviorSubject<LoginResponseModel> = new BehaviorSubject<LoginResponseModel>(null);

    constructor(private injector: Injector) {
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        let modifiedReq;
        const userData: {
            username: string,
            access_token: string,
            refresh_token: string,
            role: RoleEnum,
            _tokenexpirationDate: string
        } = (JSON.parse(localStorage.getItem('userData')));
        if (userData.access_token !== null && !req.headers.has('X-Skip-Interceptor')) {
            modifiedReq = req.clone({
                headers: req.headers.set('access_token', `${userData.access_token}`),
            });
        } else {
            modifiedReq = req.clone({
                setHeaders: {
                    'Content-Type': 'application/json',
                    'Access-Control-Allow-Origin': '*'
                }
            });
        }
        return next.handle(modifiedReq).pipe(tap(res => {
            if (res instanceof HttpResponse) {
                const response = (<HttpResponse<ResponseModel<string>>> res).body;
                /*const userdata: {
                    username: string,
                    access_token: string,
                    refresh_token: string,
                    role: RoleEnum,
                    _tokenexpirationDate: string
                } = (JSON.parse(localStorage.getItem('userData')));*/
                if (!response.is_successfull) {
                    if (new Date() > new Date(userData._tokenexpirationDate)) {
                        this.refreshToken(req, next, userData.refresh_token, userData.username);
                    }
                }
            }
        }));
    }

    refreshToken(req: HttpRequest<any>, next: HttpHandler, refreshtoken: string, username: string) {
        this.httpSubject.next(null);
        const authService = this.injector.get(AuthService);
        const authmodel: AuthModel = {
            email_address: '', grant_type: LoginType.RefreshToken, password: '', phone_number: '', phone_number_countery_iso2_code: '',
            refresh_token: refreshtoken, username: ''
        };

        debugger;
        return authService.Signin(authmodel).pipe(
            switchMap(result => {
                debugger;
                if (result.is_successfull && result.response.access_token !== null) {
                    const expirationDate = new Date(new Date().getTime() + +result.response.expires_in * 60000);
                    const user = new UserDataModel(username, result.response.access_token, result.response.refresh_token
                        , result.response.role, expirationDate);
                    localStorage.setItem('userData', JSON.stringify(user));
                    this.httpSubject.next(result.response);
                    req = req.clone({
                        setHeaders: {
                            access_token: `${result.response.access_token}`
                        }
                    });
                    return next.handle(req);

                }

            }) , catchError(err => {
                console.log(err);
                return Observable;
            }));
    }
}

I would also like to say that if I use subscribe instead of pipe, switchMap, the token will be refreshed and only the request will not be repeated from the beginning.

Body:
Your code should be :-

   import {HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from '@angular/common/http';
import {Injectable, Injector} from '@angular/core';
import {BehaviorSubject, Observable} from 'rxjs';
import {catchError, switchMap, tap} from 'rxjs/operators';
import {ResponseModel} from '../Models/responseModel';
import {UserDataModel} from '../Models/UserDataModel';
import {RoleEnum} from '../Enums/RoleEnum';
import {AuthService} from '../../auth/auth.service';
import {AuthModel} from '../Models/authModel';
import {LoginType} from '../Enums/LoginType';
import {LoginResponseModel} from '../Models/LoginResponseModel';

@Injectable({providedIn: 'root'})
export class TokenInterceptor implements HttpInterceptor {
    httpSubject: BehaviorSubject<LoginResponseModel> = new BehaviorSubject<LoginResponseModel>(null);

    constructor(private injector: Injector) {
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        let modifiedReq;
        const userData: {
            username: string,
            access_token: string,
            refresh_token: string,
            role: RoleEnum,
            _tokenexpirationDate: string
        } = (JSON.parse(localStorage.getItem('userData')));
        if (userData.access_token !== null && !req.headers.has('X-Skip-Interceptor')) {
            modifiedReq = req.clone({
                headers: req.headers.set('access_token', `${userData.access_token}`),
            });
        } else {
            modifiedReq = req.clone({
                setHeaders: {
                    'Content-Type': 'application/json',
                    'Access-Control-Allow-Origin': '*'
                }
            });
        }
        return next.handle(modifiedReq).pipe(tap(res => {
            if (res instanceof HttpResponse) {
                const response = (<HttpResponse<ResponseModel<string>>> res).body;
                /*const userdata: {
                    username: string,
                    access_token: string,
                    refresh_token: string,
                    role: RoleEnum,
                    _tokenexpirationDate: string
                } = (JSON.parse(localStorage.getItem('userData')));*/
                if (!response.is_successfull) {
                    if (new Date() > new Date(userData._tokenexpirationDate)) {
                        this.refreshToken(req, next, userData.refresh_token, userData.username).then((request)=> {

                                   modifiedRequest = request.clone();
                                   throw "replay";
                     });
                    }
                }

        }),retryWhen(errors => errors);
    }

refreshToken(req: HttpRequest<any>, next: HttpHandler, refreshtoken: string, username: string) {
            this.httpSubject.next(null);
            const authService = this.injector.get(AuthService);
            const authmodel: AuthModel = {
                email_address: '', grant_type: LoginType.RefreshToken, password: '', phone_number: '', phone_number_countery_iso2_code: '',
                refresh_token: refreshtoken, username: ''
            };

            debugger;
            return await authService.Signin(authmodel).pipe(
                map(result => {
                    debugger;
                    if (result.is_successfull && result.response.access_token !== null) {
                        const expirationDate = new Date(new Date().getTime() + +result.response.expires_in * 60000);
                        const user = new UserDataModel(username, result.response.access_token, result.response.refresh_token
                            , result.response.role, expirationDate);
                        localStorage.setItem('userData', JSON.stringify(user));
                        this.httpSubject.next(result.response);
                        req = req.clone({
                            setHeaders: {
                                access_token: `${result.response.access_token}`
                            }
                        });
                        return req;

                    }

                }) , catchError(err => {
                    console.log(err);
                    return Observable;
                })).toPromise();
        }
    }

Reason :- Tap doesn't subscribe to inner observable you was returning. mergemap does that. stream combination should be done with proper operators.


问:
Why app namespace doesn't have autocompletion in just one of my Android project layouts?
When I put "app:" in  main_activity.xml, doesn't work the autocompletion, it only shows 1 option:

```<code>   appNs
</code>```

But when I do in another xml like fragment_owl.xml, it gives me all the attributes of app namespace.
I have xmlns:app="http://schemas.android.com/apk/res-auto in both of them

this are my xmls

activity_main.xml: (that has autocompletion of app namespace attributes)

```<code>    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/holamundo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="69dp"
        android:text="Hola Mundo"
        android:textAllCaps="false"
        android:textSize="36sp"
        android:textStyle="bold"

        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/roll"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="134dp"
        android:text="GIRAR"
        android:textSize="36sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <ImageView
        android:id="@+id/dice"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/empty_dice"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:srcCompat = "@drawable/dice_1"
        />

<!--        android:src="@drawable/dice_1"-->

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

but in this another one:

```<code><?xml version="1.0" encoding="utf-8"?>

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            >

            <fragment

                android:id="@+id/navHostFragment"
                android:name="androidx.navigation.fragment.NavHostFragment"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:navGraph="@navigation/navigation"
                app:defaultNavHost="true"
                app <- NO AUTOCOMPLETION :(

                />
        </LinearLayout>

</layout>
</code>```

I've already try invalite cache and delete or override some folders but nothings seems to work for me.

答:
After doing some digging i found out the following

Changing your LinearLayout to a ConstraintLayout solves your problem, but why?

ConstraintLayout is from a library (you import it via your build.gradle androidx.constraintlayout:constraintlayout:*.*.*)

CommonsWare explains it here android.support.constraint is from a library, not the platform.

Taking this into account Android Studio maybe doesnt understand the app namespace for layouts that belong to the Android platform like LinearLayout as they are part of the android namespace.

This is my interpretation, hope it answers your question

Body:
When I put "app:" in  main_activity.xml, doesn't work the autocompletion, it only shows 1 option:

   appNs

But when I do in another xml like fragment_owl.xml, it gives me all the attributes of app namespace.
I have xmlns:app="http://schemas.android.com/apk/res-auto in both of them

this are my xmls

activity_main.xml: (that has autocompletion of app namespace attributes)

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/holamundo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="69dp"
        android:text="Hola Mundo"
        android:textAllCaps="false"
        android:textSize="36sp"
        android:textStyle="bold"

        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/roll"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="134dp"
        android:text="GIRAR"
        android:textSize="36sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <ImageView
        android:id="@+id/dice"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/empty_dice"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:srcCompat = "@drawable/dice_1"
        />

</androidx.constraintlayout.widget.ConstraintLayout>

but in this another one:

<?xml version="1.0" encoding="utf-8"?>

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            >

            <fragment

                android:id="@+id/navHostFragment"
                android:name="androidx.navigation.fragment.NavHostFragment"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:navGraph="@navigation/navigation"
                app:defaultNavHost="true"
                app <- NO AUTOCOMPLETION :(

                />
        </LinearLayout>

</layout>

I've already try invalite cache and delete or override some folders but nothings seems to work for me.


问:
Mockito method call stub not working - Mockito.doReturn(false).when(studentServiceImpl).myClass().isValidUser(ArgumentMatchers.anyInt());
adding test cases for getStudent method, this is having internal calls

1- is repository call - stubbing  this call working fine

2- validate user call - stubbing this call not working, showing some error and test case failed.

Service Class

```<code>@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    FakeStudentRepository fakeStudentRepository;
    @Override
    public Optional<Student> getStudent(int id) {
        Optional<Student> student = fakeStudentRepository.getStudent(id);
        boolean isValid = myClass().isValidUser(student.get().getId());
        if(!isValid) {
            return Optional.empty();
        }
        return student;
    }
    public MyTestClass myClass() {
        return new MyTestClass();
    }
 }
</code>```

MyTestClass

```<code>public class MyTestClass {
    public boolean isValidUser(int id) {
        return true;
    }
}
</code>```

Test Class

```<code>@SpringBootTest
class StudentServiceImplTest {

    @Mock
    FakeStudentRepository fakeStudentRepository;

    @InjectMocks
    StudentServiceImpl studentServiceImpl;

    @BeforeEach
    public void setup() {
        studentServiceImpl = Mockito.spy(StudentServiceImpl.class);
        MockitoAnnotations.initMocks(this);
    }

    @Test
    void getStudent() {
        Optional<Student> student = Optional.of(Student.builder().id(1).firstName("Rahul").lastName("rahul")
                .mobile("XXXXXX").build());

        Mockito.doReturn(student)
                .when(fakeStudentRepository).getStudent(ArgumentMatchers.anyInt());

        Mockito.doReturn(false)
                .when(studentServiceImpl).myClass().isValidUser(ArgumentMatchers.anyInt());

        Optional<Student> resultStudent = studentServiceImpl.getStudent(student.get().getId());
        assertEquals(resultStudent.get().getId(), student.get().getId());
    }
}
</code>```

Error

org.mockito.exceptions.misusing.WrongTypeOfReturnValue:  Boolean
  cannot be returned by myClass() myClass() should return MyTestClass

If you're unsure why you're getting above error read on. Due to the
  nature of the syntax above problem might occur because:
  1. This exception might occur in wrongly written multi-threaded tests.    Please refer to Mockito FAQ on limitations of concurrency
  testing.
  2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies -
     - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.

答:
The error Message says it: You are mocking studentServiceImpl.myClass() and try to return true. It’s not possible to mock the end of a call chain as you try with your second Mockito expression.

To do what you want requires to mock myClass() first by returning a mocked class instance and mock isValidUser on that.

Body:
adding test cases for getStudent method, this is having internal calls

1- is repository call - stubbing  this call working fine

2- validate user call - stubbing this call not working, showing some error and test case failed.

Service Class

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    FakeStudentRepository fakeStudentRepository;
    @Override
    public Optional<Student> getStudent(int id) {
        Optional<Student> student = fakeStudentRepository.getStudent(id);
        boolean isValid = myClass().isValidUser(student.get().getId());
        if(!isValid) {
            return Optional.empty();
        }
        return student;
    }
    public MyTestClass myClass() {
        return new MyTestClass();
    }
 }

MyTestClass

public class MyTestClass {
    public boolean isValidUser(int id) {
        return true;
    }
}

Test Class

@SpringBootTest
class StudentServiceImplTest {

    @Mock
    FakeStudentRepository fakeStudentRepository;

    @InjectMocks
    StudentServiceImpl studentServiceImpl;

    @BeforeEach
    public void setup() {
        studentServiceImpl = Mockito.spy(StudentServiceImpl.class);
        MockitoAnnotations.initMocks(this);
    }

    @Test
    void getStudent() {
        Optional<Student> student = Optional.of(Student.builder().id(1).firstName("Rahul").lastName("rahul")
                .mobile("XXXXXX").build());

        Mockito.doReturn(student)
                .when(fakeStudentRepository).getStudent(ArgumentMatchers.anyInt());

        Mockito.doReturn(false)
                .when(studentServiceImpl).myClass().isValidUser(ArgumentMatchers.anyInt());

        Optional<Student> resultStudent = studentServiceImpl.getStudent(student.get().getId());
        assertEquals(resultStudent.get().getId(), student.get().getId());
    }
}

Error

org.mockito.exceptions.misusing.WrongTypeOfReturnValue:  Boolean
  cannot be returned by myClass() myClass() should return MyTestClass

If you're unsure why you're getting above error read on. Due to the
  nature of the syntax above problem might occur because:
  1. This exception might occur in wrongly written multi-threaded tests.    Please refer to Mockito FAQ on limitations of concurrency
  testing.
  2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies -
     - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.


问:
ORA-00936 :missing expression
can you explain where the mistake is? when I run the program a notification appears like ORA-00936: missing expression</p>

```<code>Insert into vemp_10_20 (employee_id,last_name,hire_date,email,job_id,salary) values ('411','Michele',to date ( '17-Sep-2010','DD-MON-RRRR'),'michele@xyz.com','MK_REP','1000');
</code>```

答:
Function is TO_DATE, not TO DATE (missing underline _).

Also, consider using YYYY format mask, not RRRR (as you specify years in 4-digits format, which is correct).

Title: ORA-00936 :missing expression

Body:
can you explain where the mistake is? when I run the program a notification appears like ORA-00936: missing expression

Insert into vemp_10_20 (employee_id,last_name,hire_date,email,job_id,salary) values ('411','Michele',to date ( '17-Sep-2010','DD-MON-RRRR'),'michele@xyz.com','MK_REP','1000');


问:
Linking to a page to also load javascript
I want to be able to create a link to a specific page on my site and then also have that link load a specific piece of javascript on that page.

For example:

I link to this page:

```<code>http://www.myexample.com/cat/test.html
</code>```

Then I want the link to also open a topic on arrival by executing a piece of javascript:

javascript:showContentDesc(59, 11, 'left'), scroll(0,120)

I have done some research and I believe I have to do the following:

1- Modify the URL to specify the DIV to open
2- Have an onLoad handler that parses the URL and opens the appropriate DIV.

So I will then have a URL like this:

```<code>http://www.myexample.com/cat/test.html#1
</code>```

The link will take me toe the page where an onLoad Handler will parse the URL and then call the

```<code>javascript:showContentDesc(59, 11, 'left'), scroll(0,120)  piece of script.
</code>```

If the URL were

```<code>http://www.myexample.com/cat/test.html#2
</code>```

it would then be parsed by the online handler and run a different piece of javascript

```<code>javascript:showContentDesc(60, 11, 'left'), scroll(0,120)
</code>```

So my question is, based on this being correct:

1 - What do I need to do to create the onLoad Handler?
2 - How do I make the script that parses the url and then runs the the appropriate piece of javascript?

I hope this is understandable.

Thanks for the help as always!

OK so this is what I have figured out thus far...

In my joomla module (The one I want to be able to load a spesific topic of has this piece of code on the bottom.

```<code><script type="text/javascript">
showContentDesc("<?php echo $module->id; ?>",0,"<?php echo $menuPositions; ?>");
</script>
</code>```

This tells the browser to load topic 0 - this can be changed to 2 or what ever I want.

So I believe all I have to do now is add a handler that parses the URL somewhere and then have the 0 in the code be the value of the part the handler parses ??

Any help???

答:
This made it work!</p>

```<code> <script type="text/javascript">
showContentDesc("<?php echo $module->id; ?>"<?php $page=$_GET['page'];

if(isset($_GET['page']))
echo  "$page";
else
echo "0";
?>"<?php echo $menuPositions; ?>");
</script>
</code>```

Body:
I want to be able to create a link to a specific page on my site and then also have that link load a specific piece of javascript on that page.

For example:

I link to this page:

http://www.myexample.com/cat/test.html

Then I want the link to also open a topic on arrival by executing a piece of javascript:

javascript:showContentDesc(59, 11, 'left'), scroll(0,120)

I have done some research and I believe I have to do the following:

1- Modify the URL to specify the DIV to open
2- Have an onLoad handler that parses the URL and opens the appropriate DIV.

So I will then have a URL like this:

http://www.myexample.com/cat/test.html#1

The link will take me toe the page where an onLoad Handler will parse the URL and then call the

javascript:showContentDesc(59, 11, 'left'), scroll(0,120)  piece of script.

If the URL were

http://www.myexample.com/cat/test.html#2

it would then be parsed by the online handler and run a different piece of javascript

javascript:showContentDesc(60, 11, 'left'), scroll(0,120)

So my question is, based on this being correct:

1 - What do I need to do to create the onLoad Handler?
2 - How do I make the script that parses the url and then runs the the appropriate piece of javascript?

I hope this is understandable.

Thanks for the help as always!

OK so this is what I have figured out thus far...

In my joomla module (The one I want to be able to load a spesific topic of has this piece of code on the bottom.

This tells the browser to load topic 0 - this can be changed to 2 or what ever I want.

So I believe all I have to do now is add a handler that parses the URL somewhere and then have the 0 in the code be the value of the part the handler parses ??

Any help???

Body:
This made it work!

 <script type="text/javascript">
showContentDesc("<?php echo $module->id; ?>"<?php $page=$_GET['page'];

if(isset($_GET['page']))
echo  "$page";
else
echo "0";
?>"<?php echo $menuPositions; ?>");
</script>


答:
The most common solution would be:</p>

```<code>declare type UnionTypes = number[] | string[] | boolean[];
function zip(arrays: UnionTypes[]): UnionTypes[]
</code>```

Title: how to type define a zip function in typescript

Body:
The most common solution would be:

declare type UnionTypes = number[] | string[] | boolean[];
function zip(arrays: UnionTypes[]): UnionTypes[]


问:
Could not find or load main class com.android.sdkmanager.Main
I read these, and these, and these issues about Android SDK installation troubles.

Nothing works for me.

Every time I get the error

```<code>C:\Users\user\AppData\Local\Android\android-sdk\tools>android
Error: Could not find or load main class com.android.sdkmanager.Main
</code>```

when I try to start android.bat.

My environment:

```<code>C:\Users\user\AppData\Local\Android\android-sdk\tools>java -version
java version "1.7.0_71"
Java(TM) SE Runtime Environment (build 1.7.0_71-b14)
Java HotSpot(TM) 64-Bit Server VM (build 24.71-b01, mixed mode)

JAVA_HOME=c:\Program Files\Java\jdk1.7.0_71\jre\bin

PATH=c:\Program Files\Java\jdk1.7.0_71\jre\bin\;%SystemRoot%\system32;%SystemRoot%;...
</code>```

I use latest android SDK version (on Dec 8, 2014) - installer_r23.0.2-windows.exe, tried to use latest JDK7 & JDK8 builds. Same error all the time.

How to fix this?

答:
I fixed the problem by setting the correct folder hierarchy.
which is ANDROID_HOME>cmdline-tools>tools

Copy the tools folder which contain all the files of command line tools into a folder named cmdline-tools. Then it will work.

The tools installed using sdkmanager (eg platform-tools) will be installed in the folder which contains the cmdline-tools folder, in my case ANDROID_HOME folder

Body:
I read these, and these, and these issues about Android SDK installation troubles.

Nothing works for me.

Every time I get the error

C:\Users\user\AppData\Local\Android\android-sdk\tools>android
Error: Could not find or load main class com.android.sdkmanager.Main

when I try to start android.bat.

My environment:

C:\Users\user\AppData\Local\Android\android-sdk\tools>java -version
java version "1.7.0_71"
Java(TM) SE Runtime Environment (build 1.7.0_71-b14)
Java HotSpot(TM) 64-Bit Server VM (build 24.71-b01, mixed mode)

JAVA_HOME=c:\Program Files\Java\jdk1.7.0_71\jre\bin

PATH=c:\Program Files\Java\jdk1.7.0_71\jre\bin\;%SystemRoot%\system32;%SystemRoot%;...

I use latest android SDK version (on Dec 8, 2014) - installer_r23.0.2-windows.exe, tried to use latest JDK7 & JDK8 builds. Same error all the time.

How to fix this?


问:
Is there any option to calculate the pricing of certain resource in my GCP project.?
I need to calculate the pricing of selected resources like compute engine,dataproc and cloud sql in my gcp project. Is there any way to manage and calculate the cost programatically?</p>

答: You could use gcp pricing calculator for usage of resources in gcp [1]</p>


问:
std::launder use cases in C++20
[1]

Are there any cases in which the addition of p0593r6 into C++20 (§ 6.7.2.11 Object model [intro.object]) made std::launder not necessary, where the same use case in C++17 required std::launder, or are they completely orthogonal?

[2]

The example in the spec for [ptr::launder] is:

```<code>struct X { int n; };
const X *p = new const X{3};
const int a = p->n;
new (const_cast<X*>(p)) const X{5}; // p does not point to new object ([basic.life]) because its type is const
const int b = p->n;                 // undefined behavior
const int c = std::launder(p)->n;   // OK
</code>```

Another example is given by @Nicol Bolas in this SO answer, using a pointer that points to a valid storage but of a different type:

```<code>aligned_storage<sizeof(int), alignof(int)>::type data;
new(&data) int;
int *p = std::launder(reinterpret_cast<int*>(&data));
</code>```

Are there other use cases, not related to allowing casting of two objects which are not transparently replaceable, for using std::launder?

Specifically:

Would reinterpret_cast from A* to B*, both are pointer-interconvertible, may require using std::launder in any case? (i.e. can two pointers be pointer-interconvertible and yet not be transparently replaceable? the spec didn't relate between these two terms).

Does reinterpret_cast from void* to T* require using std::launder?

Does the following code below require use of std::launder? If so, under which case in the spec does it fall to require that?

A struct with reference member, inspired by this discussion:

```<code>struct A {
    constexpr A(int &x) : ref(x) {}
    int &ref;
};

int main() {
    int n1 = 1, n2 = 2;
    A a { n1 };
    a.~A();
    new (&a) A {n2};
    a.ref = 3; // do we need to launder somebody here?
    std::cout << a.ref << ' ' << n1 << ' ' << n2 << std::endl;
}
</code>```

答:
Before C++17, a pointer with a given address and type always pointed to an object of that type located at that address, provided that the code respects the rules of [basic.life]. (see: Is a pointer with the right address and type still always a valid pointer since C++17?).

But in the C++17 standard added a new quality to a pointer value. This quality is not encode within the pointer type but qualifies directly the value, independently of the type (this is the case also of the traceability). It is described in [basic.compound]/3

Every value of pointer type is one of the following:

a pointer to an object or function (the pointer is said to point to the object or function), or

a pointer past the end of an object ([expr.add]), or

the null pointer value for that type, or
an invalid pointer value.

This quality of a pointer value has its own semantic (transition rules), and for the case of reinterpret_cast it is described in the next paragraph:

If two objects are pointer-interconvertible, then they have the same address, and it is possible to obtain a pointer to one from a pointer to the other via a reinterpret_cast.

In [basic-life], we can find an other rule that describes how transitions this quality when an object storage is reused:

If, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, a new object is created at the storage location which the original object occupied, a pointer that pointed to the original object, a reference that referred to the original object, or the name of the original object will automatically refer to the new object and, [...]

As you can see the quality "pointer to an object" is attached to a specific object.

That means that in the variation bellow of the first example you give, the reinterpret_cast does not allow us not to use the pointer optimization barrier:

```<code>struct X { int n; };
const X *p = new const X{3};
const int a = p->n;
new (const_cast<X*>(p)) const X{5}; // p does not point to new object ([basic.life]) because its type is const
const int b = *reinterpret_cast <int*> (p);                 // undefined behavior
const int c = *std::launder(reinterpret_cast <int*> (p));
</code>```

A reinterpret_cast is not a pointer optimization barrier: reinterpret_cast <int*>(p) points to the member of the destroyed object.

An other way to conceive it is that the "pointer to" quality is conserved by reinterpret_cast as long as the object are pointer inter-convertible or if its casted to void and then back to a pointer inter-convertible type. (See [exp.static_cast]/13).  So reinterpret_cast <int*>(reinterpret_cast <void*>(p)) still points to the destroyed object.

For the last example you gives, the name a refers to a non const complete object, so the original a is transparently replaceable by the new object.

For the first question you ask: "Are there any cases in which the addition of p0593r6 into C++20 (§ 6.7.2.11 Object model [intro.object]) made std::launder not necessary, where the same use case in C++17 required std::launder, or are they completely orthogonal?"

Honestly, I have not been able to find any cases that where std::launder could compensate implict-lifetime objects. But I found an example were implicit-lifetime object makes std::launder usefull:

```<code>  class my_buffer {
      alignas(int) std::byte buffer [2*sizeof(int)];

      int * begin(){
         //implictly created array of int inside the buffer
         //nevertheless to get a pointer to this array,
         //std::launder is necessary as the buffer is not
         //pointer inconvertible with that array
         return *std::launder (reinterpret_cast <int(*)[2]>(&buffer));
         }
      create_int(std::size_t index, int value){
         new (begin()+index) auto{value};
         }
       };

</code>```

Title: std::launder use cases in C++20

Body:
[1]

Are there any cases in which the addition of p0593r6 into C++20 (§ 6.7.2.11 Object model [intro.object]) made std::launder not necessary, where the same use case in C++17 required std::launder, or are they completely orthogonal?

[2]

The example in the spec for [ptr::launder] is:

struct X { int n; };
const X *p = new const X{3};
const int a = p->n;
new (const_cast<X*>(p)) const X{5}; // p does not point to new object ([basic.life]) because its type is const
const int b = p->n;                 // undefined behavior
const int c = std::launder(p)->n;   // OK

Another example is given by @Nicol Bolas in this SO answer, using a pointer that points to a valid storage but of a different type:

aligned_storage<sizeof(int), alignof(int)>::type data;
new(&data) int;
int *p = std::launder(reinterpret_cast<int*>(&data));

Are there other use cases, not related to allowing casting of two objects which are not transparently replaceable, for using std::launder?

Specifically:

Would reinterpret_cast from A* to B*, both are pointer-interconvertible, may require using std::launder in any case? (i.e. can two pointers be pointer-interconvertible and yet not be transparently replaceable? the spec didn't relate between these two terms).

Does reinterpret_cast from void* to T* require using std::launder?

Does the following code below require use of std::launder? If so, under which case in the spec does it fall to require that?

A struct with reference member, inspired by this discussion:

struct A {
    constexpr A(int &x) : ref(x) {}
    int &ref;
};

int main() {
    int n1 = 1, n2 = 2;
    A a { n1 };
    a.~A();
    new (&a) A {n2};
    a.ref = 3; // do we need to launder somebody here?
    std::cout << a.ref << ' ' << n1 << ' ' << n2 << std::endl;
}

Body:
Before C++17, a pointer with a given address and type always pointed to an object of that type located at that address, provided that the code respects the rules of [basic.life]. (see: Is a pointer with the right address and type still always a valid pointer since C++17?).

But in the C++17 standard added a new quality to a pointer value. This quality is not encode within the pointer type but qualifies directly the value, independently of the type (this is the case also of the traceability). It is described in [basic.compound]/3

Every value of pointer type is one of the following:

a pointer to an object or function (the pointer is said to point to the object or function), or

a pointer past the end of an object ([expr.add]), or

the null pointer value for that type, or
an invalid pointer value.

This quality of a pointer value has its own semantic (transition rules), and for the case of reinterpret_cast it is described in the next paragraph:

If two objects are pointer-interconvertible, then they have the same address, and it is possible to obtain a pointer to one from a pointer to the other via a reinterpret_cast.

In [basic-life], we can find an other rule that describes how transitions this quality when an object storage is reused:

If, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, a new object is created at the storage location which the original object occupied, a pointer that pointed to the original object, a reference that referred to the original object, or the name of the original object will automatically refer to the new object and, [...]

As you can see the quality "pointer to an object" is attached to a specific object.

That means that in the variation bellow of the first example you give, the reinterpret_cast does not allow us not to use the pointer optimization barrier:

struct X { int n; };
const X *p = new const X{3};
const int a = p->n;
new (const_cast<X*>(p)) const X{5}; // p does not point to new object ([basic.life]) because its type is const
const int b = *reinterpret_cast <int*> (p);                 // undefined behavior
const int c = *std::launder(reinterpret_cast <int*> (p));

A reinterpret_cast is not a pointer optimization barrier: reinterpret_cast <int*>(p) points to the member of the destroyed object.

An other way to conceive it is that the "pointer to" quality is conserved by reinterpret_cast as long as the object are pointer inter-convertible or if its casted to void and then back to a pointer inter-convertible type. (See [exp.static_cast]/13).  So reinterpret_cast <int*>(reinterpret_cast <void*>(p)) still points to the destroyed object.

For the last example you gives, the name a refers to a non const complete object, so the original a is transparently replaceable by the new object.

For the first question you ask: "Are there any cases in which the addition of p0593r6 into C++20 (§ 6.7.2.11 Object model [intro.object]) made std::launder not necessary, where the same use case in C++17 required std::launder, or are they completely orthogonal?"

Honestly, I have not been able to find any cases that where std::launder could compensate implict-lifetime objects. But I found an example were implicit-lifetime object makes std::launder usefull:

  class my_buffer {
      alignas(int) std::byte buffer [2*sizeof(int)];

      int * begin(){
         //implictly created array of int inside the buffer
         //nevertheless to get a pointer to this array,
         //std::launder is necessary as the buffer is not
         //pointer inconvertible with that array
         return *std::launder (reinterpret_cast <int(*)[2]>(&buffer));
         }
      create_int(std::size_t index, int value){
         new (begin()+index) auto{value};
         }
       };


问:
TYPO3 Add Copy and Paste icons to Content Elements
Is it possible to add icons to the left or right side for Content Elements? I would like to move some of the functionality from the contextMenu to the icon bar, is that possible? Perhaps by TSConfig ? See attachment.

答:
Several options exist for multiple TYPO3 versions and depending on where you would prefer to add the copy/cut icon, or indeed, any other icon you might wish:

Before 10.3 and without fluid-based page layout module:

$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['recStatInfoHooks']

$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['cms/layout/class.tx_cms_layout.php']['tt_content_drawFooter']

$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['cms/layout/class.tx_cms_layout.php']['tt_content_drawItem'] through $outHeader variable.

After 10.3 with fluid-based page layout module:

All of the above, plus

Overlay of template EXT:backend/Resources/Private/Partials/PageLayout/Record/Header.html, or

Overlay of template EXT:backend/Resources/Private/Partials/PageLayout/Record/Footer.html, or

Overlay of template EXT:backend/Resources/Private/Partials/PageLayout/Record.html depending on where you want the icon to be placed

These should provide you with every conceivable option for adding the icon precisely where you wish it to be added. TYPO3 10.3 with fluid based page module enabled provides you with the createst flexibility. Earlier versions or with fluid based page module disabled should probably use $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['recStatInfoHooks'].