问:
Plotting processing time
Below is the average time taken for a robot to process a single request on any given day. I am trying to plot this on an excel chart but I am having trouble formatting. I want the date on the x axis and the processing time on the y axis. Any advice would be appreciated. </p>

```<code>11/23/2017  0:02:40
11/24/2017  0:02:33
11/25/2017  0:02:54
11/26/2017  0:02:50
11/27/2017  0:03:01
11/28/2017  0:02:42
11/29/2017  0:03:07
11/30/2017  0:02:42
12/1/2017   0:02:55
</code>```

答:
Create a line chart. With the data in two columns, make sure there is a header row. Delete any content in the date header, so the cell is blank. If there is text in the column header, Excel will try to plot the dates as numbers, and that is not what you want.

Click any cell in the table and insert a line chart. By default, if Excel recognizes a date for the X axis values, it will plot the data on a timeline. In the screenshot, notice that there is a gap of a few days and the chart plots the data correctly per day.

Title: Plotting processing time

Body:
Below is the average time taken for a robot to process a single request on any given day. I am trying to plot this on an excel chart but I am having trouble formatting. I want the date on the x axis and the processing time on the y axis. Any advice would be appreciated.

11/23/2017  0:02:40
11/24/2017  0:02:33
11/25/2017  0:02:54
11/26/2017  0:02:50
11/27/2017  0:03:01
11/28/2017  0:02:42
11/29/2017  0:03:07
11/30/2017  0:02:42
12/1/2017   0:02:55


来源: stackexchange

问:
Java String object references
I would like to clear some doubts on java objects, i have this code:

```<code>public class Strut
{
    public static void main(String[] args)
    {
        String s=new String("wooo!");
        String t=s;
        System.out.println(s+","+t);
        t="blaaaah";
        System.out.println(s+","+t);
    }
}
</code>```

If i got it right object are always allocated on the heap, because java doesn't allocate objects on the stack by design.
so the variable s and t are merely references to the same object in the code that i wrote right?
so when i print s and t for the first time i expect the same result and it's fine.
but after i modify t and print the strings again they are different,
shouldn't s have become blaaaah since t and s are references to the same object?
thanks

答:
That can be answered in one phrase: Strings are immutable.

So yes, everytime you use quotation marks, you are in fact, making a new String object. Thats's why instead of doing:

```<code>String s=new String("wooo!");
</code>```

You could just do:

```<code>String s = "wooo!";
</code>```

And it would be the same.

PS.:Immutable means each String object will ever have the same value, until it's destroyed, if a String refference changes value, you can know for sure that it is refferencing a different object.

ContentLicense: CC BY-SA 3.0

Title: Java String object references

Body:
I would like to clear some doubts on java objects, i have this code:

public class Strut
{
    public static void main(String[] args)
    {
        String s=new String("wooo!");
        String t=s;
        System.out.println(s+","+t);
        t="blaaaah";
        System.out.println(s+","+t);
    }
}

If i got it right object are always allocated on the heap, because java doesn't allocate objects on the stack by design.
so the variable s and t are merely references to the same object in the code that i wrote right?
so when i print s and t for the first time i expect the same result and it's fine.
but after i modify t and print the strings again they are different,
shouldn't s have become blaaaah since t and s are references to the same object?
thanks

Body:
That can be answered in one phrase: Strings are immutable.

So yes, everytime you use quotation marks, you are in fact, making a new String object. Thats's why instead of doing:

String s=new String("wooo!");

You could just do:

String s = "wooo!";

And it would be the same.

PS.:Immutable means each String object will ever have the same value, until it's destroyed, if a String refference changes value, you can know for sure that it is refferencing a different object.


Title: converting pandas dataframe to contain a dictionary or list of lists

Body:
      state      Year  Month  count
0       alabama  2017.0   10.0     31
1       alabama  2017.0   11.0     30
2       alabama  2017.0   12.0     31
3       alabama  2018.0    1.0     31
4       alabama  2018.0    2.0     28
5       alabama  2018.0    3.0     31
6       alabama  2018.0    4.0     30
7       alabama  2018.0    5.0     31
8       alabama  2018.0    6.0     30
9       alabama  2018.0    7.0     14
10     arkansas  2017.0   10.0     31
11     arkansas  2017.0   11.0     30
12     arkansas  2017.0   12.0     31

Can I convert dataframe above to:

                                                            Month
state
alabama         {2017:10.0, 2017:11.0, 2017:12.0, 2018:1.0, 2018:2.0, 2018:3.0, 2018:4.0, 2018:5.0, 2018:6.0, 2018:7.0}
arkansas        {2017:10.0, 2017:11.0, 2017:12.0}

related to converting pandas dataframe to contain a list

based on @Vaishali's comment below, since dictionary cannot contain duplicate keys, this should be ok too:

                                                            Month
state
alabama         [[2017,10.0], [2017,11.0], [2017,12.0], [2018,1.0], [2018,2.0], [2018,3.0], [2018,4.0], [2018,5.0], [2018,6.0], 2[018,7.0]]
arkansas        [[2017,10.0], [2017,11.0], [2017,12.0]]

Body:
In [73]: (df.groupby('state')['Year','Month']
            .apply(lambda x: x.values.tolist())
            .to_frame('Month')
            .reset_index())
Out[73]:
      state                                              Month
0   alabama  [[2017.0, 10.0], [2017.0, 11.0], [2017.0, 12.0...
1  arkansas   [[2017.0, 10.0], [2017.0, 11.0], [2017.0, 12.0]]


问:
How can you insert a templated number into an APIMocker response?
According to the API Mocker GitHub page here, it says you can template your response using placeholders.

As an example, if you use this configuration entry...

```<code>"template/:Name/:Number" :{
    "mockFile": "templateSample.json",
    "verbs":["get"],
    "enableTemplate": true
    "contentType":"application/json"
}
</code>```

Then you use this as your 'templateSample.json'...

```<code>{
    "Name": "@Name",
    "Number": "@Number"
}
</code>```

If you call /John/12345 it says you will be returned this...

```<code>{
    "Name": "John"
    "Number": 12345
}
</code>```

But that's not what we're getting.  We're getting this (note the quotes around '12345')...

```<code>{
    "Name": "John"
    "Number": "12345"
}
</code>```

The problem is our endpoints are expecting a pure number there, not a string.  Is there anything we can do to configure APIMocker to not wrap the values in quotes?

答:
Ok, I figured it out.  The documentation is wrong.  In the template, you're not supposed to wrap the placeholder in quotes.  However, there's a huge caveat:

If you use a placeholder whose value you don't want wrapped in quotes, the template file will no longer be valid JSON, meaning you can't edit it in a JSON editor.  You have to edit it in a plain-text editor.

That's what stumped me. I thought the templates had to be valid JSON. They don't.  They become valid JSON after the substitutions are performed, but they don't have to be beforehand.

Anyway, hope this helps others!

Body:
According to the API Mocker GitHub page here, it says you can template your response using placeholders.

As an example, if you use this configuration entry...

"template/:Name/:Number" :{
    "mockFile": "templateSample.json",
    "verbs":["get"],
    "enableTemplate": true
    "contentType":"application/json"
}

Then you use this as your 'templateSample.json'...

{
    "Name": "@Name",
    "Number": "@Number"
}

If you call /John/12345 it says you will be returned this...

{
    "Name": "John"
    "Number": 12345
}

But that's not what we're getting.  We're getting this (note the quotes around '12345')...

{
    "Name": "John"
    "Number": "12345"
}

The problem is our endpoints are expecting a pure number there, not a string.  Is there anything we can do to configure APIMocker to not wrap the values in quotes?


问:
If statements in Excel
I am trying to write an if statement to further classify my data by type. Basically the cells currently contain the ID number and tissue type, but i want to figure out a way to insert the tissue type classification into the cell below.

So for example the ID # and tissue type (all in the same excel cell) is written 868686 Skin. And in the cell below, I wrote the formula IF(B2="Skin", "Skin", " ") but because I didn't have the whole contents of the cell (the ID#) included, it didn't find it. So is there a way to say IF B2 contains the word skin, then do this...

thanks.

答:
I believe you're looking to use the FIND command.

https://support.office.com/en-us/article/FIND-FINDB-functions-c7912941-af2a-4bdf-a553-d0d89b0a0628

Title: If statements in Excel


问:
MySQL - the cheapest order
I have 2 MySQL tables:

```<code>Persons:
person_id
person_name

Orders:
person_id
cost
order_name
</code>```

I need to make a ONE sql-query to get person name and it's cheapest order.
Want to write some like this: SELECT person_name, order=(SELECT order_name FROM orders WHERE order.person_id = person.person_id ORDER BY order.cost ASC LIMIT 1) FROM person
But it don't work.

答:
I would use a correlated query. There are many ways to do it: as a subquery in the SELECT clause, or as a subquery in the WHERE clause. </p>

<p>In this case, I implemented the second option: </p>

```<code>SELECT
    person_name,
    order_name
FROM Persons
    INNER JOIN Orders ON Persons.person_id = Orders.person_id
WHERE
(
    cost = (
        SELECT MIN(cost)
        FROM Orders
        WHERE
            (Orders.person_id = Persons.person_id)
    )
)
</code>```

Title: MySQL - the cheapest order

Body:
I have 2 MySQL tables:

Persons:
person_id
person_name

Orders:
person_id
cost
order_name

I need to make a ONE sql-query to get person name and it's cheapest order.
Want to write some like this: SELECT person_name, order=(SELECT order_name FROM orders WHERE order.person_id = person.person_id ORDER BY order.cost ASC LIMIT 1) FROM person
But it don't work.

Body:
I would use a correlated query. There are many ways to do it: as a subquery in the SELECT clause, or as a subquery in the WHERE clause.

In this case, I implemented the second option:

SELECT
    person_name,
    order_name
FROM Persons
    INNER JOIN Orders ON Persons.person_id = Orders.person_id
WHERE
(
    cost = (
        SELECT MIN(cost)
        FROM Orders
        WHERE
            (Orders.person_id = Persons.person_id)
    )
)


问:
Sitecore Remote Publishing Targets - One of Two Fails Silently
I have configured two Remote Publishing Targets in the connection string config and web.config file and in the content tree per the Sitecore docs.

Target 1 is on the same physical machine and uses the same database server as the authoring site. Target 2 is on a different physical machine with a different database server from the authoring site. I used the Data Source configuration utility to insure that the authoring server could connect to the database server for Target 2 and validated the server name, database name, user name, and password are all correct. Connection works just fine.

I modified the security on the remote publishing targets in the content tree to allow my publishing lead to select the target for publishing. Both targets have the same security settings applied.

Publishing works to target #1 but not to target #2. The "Click here for more information" says that there were 2 updates made to both Target #1 and Target #2 so it looks on the face to be working but it really isn't.

How do I get more information about what exactly is failing so that I can get this resolved?

Many thanks!

答: Have you looked at the Sitecore logs? They will likely contain publish info. Check them on both the auth side and the slave side.</p>

ContentLicense: CC BY-SA 2.5


问:
Firebase dynamicLinks: Do i need an app on the store for my link to work correctly?
I created a dynamic link on firebase dynamics like in their tutorial here
https://firebase.google.com/docs/dynamic-links/ios/receive
using an app ID (WhatsApp) which is not mine because not yet on App Store.

When i click on it (in Notes or Mail), it goes to Safari and ask if i want to open WhatsApp in AppStore.
When i come back to my app, i don't receive any link.

Do i need to publish my app to the appstore before it works?

答:
You do not need to publish your App in AppStore in order to test the Firebase Dynamic Links.

Did you followed steps here https://firebase.google.com/docs/dynamic-links/ios/receive regarding Set up Firebase and the Dynamic Links SDK and Open Dynamic Links in your app?
Is your App receiving any link in UIApplicationDelegate's openURL: method? Can you reproduce the issue with quick-start App https://github.com/firebase/quickstart-ios/tree/master/dynamiclinks ?


Body:
Try

df.groupby('state').apply(lambda x: list(zip(x['Year'], x['Month'])))

state
alabama     [(2017.0, 10.0), (2017.0, 11.0), (2017.0, 12.0...
arkansas     [(2017.0, 10.0), (2017.0, 11.0), (2017.0, 12.0)]


问:
Issues passing Edit text into an If statement
I have a quiz app that should contains the following:
1- radio groups/buttons
2- checkbox
3- editText

all should calculate a score.  I manage to get the radio groups, checkbox to work and calculate the score. however having problems with the editText

I am trying to compare the value of what's in name2 variable but I am unable to do so. I've implemented the .equals syntax but it's not working accordingly.

Any suggestions/solutions are grateful.

```<code>public class Quiz extends AppCompatActivity {
int score = 0;
String name;
String name2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_quiz);

}

public void onRadioButtonCliked(View view) {

    Boolean checked = ((RadioButton) view).isChecked();
    switch (view.getId()) {
        case R.id.yes_radio_buttonG1B3:
            if (checked)
                score++;
            break;
        case R.id.yes_radio_buttonG2B2:
            if (checked)
                score++;
            break;
        case R.id.yes_radio_buttonG3B2:
            score++;
            if (checked)
                break;
        case R.id.yes_radio_buttonG4B1:
            if (checked)
                score++;
            break;
        case R.id.yes_radio_buttonG5B2:
            if (checked)
                score++;
            break;
        case R.id.yes_radio_buttonG6B3:
            if (checked)
                score++;
            break;
    }
}

public void onCheckBoxCliked(View view) {

    Boolean checked = ((CheckBox) view).isChecked();
    CheckBox cB1 = (CheckBox) findViewById(R.id.checkBox1);
    CheckBox cB2 = (CheckBox) findViewById((R.id.checkBox2));
    CheckBox cB3 = (CheckBox) findViewById(R.id.checkBox3);

    if (cB1.isChecked() && cB2.isChecked() && !cB3.isChecked()) {
        score++;
    }

}

public void EditText(View view) {
    EditText text = (EditText) findViewById(R.id.editText1);
    name2 = text.getText().toString();

    if (name2.equals("8")) {
        score++;

    }
}

public void submitOrder(View view) {
    EditText username = (EditText) findViewById(R.id.editText);
    name = username.getText().toString();

    Toast.makeText(this, "Thank you " + name, Toast.LENGTH_SHORT).show();

    Toast.makeText(this, "You have got 8/" + score, Toast.LENGTH_SHORT).show();

    }
}
</code>```

答:
Since it's a string variable, you must use "" to indicate it's a string.
Whole number are only applicable for int variable type.</p>

```<code>if(name2.equals("8")){
    score++;
}
</code>```

Body:
I have a quiz app that should contains the following:
1- radio groups/buttons
2- checkbox
3- editText

all should calculate a score.  I manage to get the radio groups, checkbox to work and calculate the score. however having problems with the editText

I am trying to compare the value of what's in name2 variable but I am unable to do so. I've implemented the .equals syntax but it's not working accordingly.

Any suggestions/solutions are grateful.

public class Quiz extends AppCompatActivity {
int score = 0;
String name;
String name2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_quiz);

}

public void onRadioButtonCliked(View view) {

    Boolean checked = ((RadioButton) view).isChecked();
    switch (view.getId()) {
        case R.id.yes_radio_buttonG1B3:
            if (checked)
                score++;
            break;
        case R.id.yes_radio_buttonG2B2:
            if (checked)
                score++;
            break;
        case R.id.yes_radio_buttonG3B2:
            score++;
            if (checked)
                break;
        case R.id.yes_radio_buttonG4B1:
            if (checked)
                score++;
            break;
        case R.id.yes_radio_buttonG5B2:
            if (checked)
                score++;
            break;
        case R.id.yes_radio_buttonG6B3:
            if (checked)
                score++;
            break;
    }
}

public void onCheckBoxCliked(View view) {

    Boolean checked = ((CheckBox) view).isChecked();
    CheckBox cB1 = (CheckBox) findViewById(R.id.checkBox1);
    CheckBox cB2 = (CheckBox) findViewById((R.id.checkBox2));
    CheckBox cB3 = (CheckBox) findViewById(R.id.checkBox3);

    if (cB1.isChecked() && cB2.isChecked() && !cB3.isChecked()) {
        score++;
    }

}

public void EditText(View view) {
    EditText text = (EditText) findViewById(R.id.editText1);
    name2 = text.getText().toString();

    if (name2.equals("8")) {
        score++;

    }
}

public void submitOrder(View view) {
    EditText username = (EditText) findViewById(R.id.editText);
    name = username.getText().toString();

    Toast.makeText(this, "Thank you " + name, Toast.LENGTH_SHORT).show();

    Toast.makeText(this, "You have got 8/" + score, Toast.LENGTH_SHORT).show();

    }
}

Body:
Since it's a string variable, you must use "" to indicate it's a string.
Whole number are only applicable for int variable type.

if(name2.equals("8")){
    score++;
}


问:
iOS 11.2 beta released, but not a corresponding Xcode beta
I've just installed iOS 11.2 Beta and downloaded the latest Xcode (which is 9.1 - beta 2. 9B46).

But when I try to run the app on the device it says it doesn't have the necessary support files.

So how am I supposed to develop with 11.2 beta if there's no corresponding Xcode yet?

答: Xcode 9.2 is now available for download via App Store or directly at: https://download.developer.apple.com/Developer_Tools/Xcode_9.2/Xcode_9.2.xip (may require login)</p>


问:
Select elements of html table and change contents using jquery

Hello Professionals

I have a table in my asp.net page

Search Results : 25

          No.
          Album Name
          Year
          Artist

          1

             Al Muallim

          2003
          Sami Yusuf

          2

             Barakah

          2017
          Sami Yusuf

```
</div>
</div>
</p>

<p><br />
the table you see is an html template, it has 25 rows as you see in the <code><span></code> in the <code><h4></code> . <br /><br />
I get data of Albums by ajax and I want by jQuery to assign the values in there palces in the table. <br />
I am using a loop on the 25 rows, and for every row I must reach the <code><img></code> in the second <code><td></code> to change its <code>src</code> , same for the <code><spane></code> beside it to change the text inside it which is the album name.<br />
In the third <code><td></code> also to change the year in it .<br />
In the forth <code><td></code> I need to change the <code>href</code> of <code><a></code> and the text of <code><a></code> which is the name of the artist. <br />
Do you see that <code>id="a"</code> in the first <code><div></code>, this is because I have like this table for every letter in the alphabet, where the letter is the <code>id</code> for that table, <br /> and there is an A-ZList of the letters where a click on a letter wil make request to bring the albums with names start with the clicked letter, and assing them from the <code>XmlHttpRequest.responseText</code> to the table. <br />
Thats why I use <code>letter</code> variable in this jQuery code to pass the <code>id</code> of the first <code><div></code> to assign the values into the table , because there is another <code><div id="b"></code> and so on <br /></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function AssignAlbumIntoDOM(albumName, albumYear, albumPhotoPath, artistName, albumsCount, i, letter) {
  if (i < 25 && i >= 0) { // keep calling until i is 25
    jQuery("#" + letter + " h4 span").text(albumsCount);
    jQuery("#" + letter + " table tbody").children().eq(i).children().eq(1).children().eq(0).children().eq(0).attr("src", albumPhotoPath);
    jQuery("#" + letter + " table tbody").children().eq(i).children().eq(2).text(albumYear);
    jQuery("#" + letter + " table tbody").children().eq(i).children().eq(3).children().eq(0).text(artistName);
  }
}</code>```

by the this code I can assing the albumYear in the third  and artistName in thr fourth ,
 but could not change in the second  the albumPhotoPath in  src and the albumName in the

Can I extend the question

This page as you see from the explanation, is a search page

And I have all the information of the album except the songs of the album, so how can I pass these information to a page called Single.aspx dedcated to show an album information and its songs after clicking the  in the second , and in the Single.aspx I only need by ajax to request the songs of the album not all the information again.

I think the passing will be as a QueryString in the href of  in the second , is there another way?

I thank you so much so much

答:
Your best bet is to assign id's or indexes to your row objects in the dom and reference them that way. Something like this:

```<code><div role="tabpanel" class="tab-pane fade in active" id="a" aria-labelledby="all-tab">
  <div class="agile-news-table">
    <div class="w3ls-news-result">
      <h4>Search Results : <span>25</span></h4>
    </div>
    <table id="table-breakpoint">
      <thead>
        <tr>
          <th>No.</th>
          <th>Movie Name</th>
          <th>Year</th>
          <th>Artist</th>
        </tr>
      </thead>
      <tbody>
        <tr id="1">
          <td>1</td>
          <td class="w3-list-img">
            <a href="single.html"><img src="images/m1.jpg" alt="" /> <span>Al Muallim</span></a>
          </td>
          <td>2003</td>
          <td class="w3-list-info"><a href="comedy.html">Sami Yusuf</a></td>
        </tr>
        <tr id="2">
          <td>2</td>
          <td class="w3-list-img">
            <a href="single.html"><img src="images/m2.jpg" alt="" /> <span>Barakah</span></a>
          </td>
          <td>2017</td>
          <td class="w3-list-info"><a href="genre.html">Sami Yusuf</a></td>
        </tr>
      </tbody>
    </table>
  </div>
</div>
</code>```

Then, when loading the content, use the nth-child selector to target the specific table cell you want to populate:

```<code>function AssignAlbumIntoDOM(albumName, albumYear, albumPhotoPath, artistName, albumsCount, i, letter) {
  if (i < 25 && i >= 0) { // this raises some red flags. check your calling function.
    jQuery("#" + letter + " h4 span").text(albumsCount);
    jQuery("#" + i + " td:nth-child(2) img").attr('src',albumPhotoPath);
    jQuery("#" + i + " td:nth-child(3)").html(albumYear);
    jQuery("#" + i + " td:nth-child(4)").html(artistName);
  }
}
</code>```

I changed the index of nth-child because  is the second child because nth-child starts indexing from 1 not 0

and .text(albumsCount) is not in side the table rows to use i

Body:
Hello Professionals

I have a table in my asp.net page

Search Results : 25

          No.
          Album Name
          Year
          Artist

          1

             Al Muallim

          2003
          Sami Yusuf

          2

             Barakah

          2017
          Sami Yusuf

the table you see is an html template, it has 25 rows as you see in the  in the
 .

I get data of Albums by ajax and I want by jQuery to assign the values in there palces in the table.

I am using a loop on the 25 rows, and for every row I must reach the  in the second  to change its src , same for the <spane> beside it to change the text inside it which is the album name.

In the third  also to change the year in it .

In the forth  I need to change the href of  and the text of  which is the name of the artist.

Do you see that id="a" in the first
, this is because I have like this table for every letter in the alphabet, where the letter is the id for that table,
 and there is an A-ZList of the letters where a click on a letter wil make request to bring the albums with names start with the clicked letter, and assing them from the XmlHttpRequest.responseText to the table.

Thats why I use letter variable in this jQuery code to pass the id of the first
 to assign the values into the table , because there is another
 and so on

function AssignAlbumIntoDOM(albumName, albumYear, albumPhotoPath, artistName, albumsCount, i, letter) {
  if (i < 25 && i >= 0) { // keep calling until i is 25
    jQuery("#" + letter + " h4 span").text(albumsCount);
    jQuery("#" + letter + " table tbody").children().eq(i).children().eq(1).children().eq(0).children().eq(0).attr("src", albumPhotoPath);
    jQuery("#" + letter + " table tbody").children().eq(i).children().eq(2).text(albumYear);
    jQuery("#" + letter + " table tbody").children().eq(i).children().eq(3).children().eq(0).text(artistName);
  }
}

by the this code I can assing the albumYear in the third  and artistName in thr fourth ,
 but could not change in the second  the albumPhotoPath in  src and the albumName in the

Can I extend the question

This page as you see from the explanation, is a search page

And I have all the information of the album except the songs of the album, so how can I pass these information to a page called Single.aspx dedcated to show an album information and its songs after clicking the  in the second , and in the Single.aspx I only need by ajax to request the songs of the album not all the information again.

I think the passing will be as a QueryString in the href of  in the second , is there another way?

I thank you so much so much

Body:
Your best bet is to assign id's or indexes to your row objects in the dom and reference them that way. Something like this:

<div role="tabpanel" class="tab-pane fade in active" id="a" aria-labelledby="all-tab">
  <div class="agile-news-table">
    <div class="w3ls-news-result">
      <h4>Search Results : <span>25</span></h4>
    </div>
    <table id="table-breakpoint">
      <thead>
        <tr>
          <th>No.</th>
          <th>Movie Name</th>
          <th>Year</th>
          <th>Artist</th>
        </tr>
      </thead>
      <tbody>
        <tr id="1">
          <td>1</td>
          <td class="w3-list-img">
            <a href="single.html"><img src="images/m1.jpg" alt="" /> <span>Al Muallim</span></a>
          </td>
          <td>2003</td>
          <td class="w3-list-info"><a href="comedy.html">Sami Yusuf</a></td>
        </tr>
        <tr id="2">
          <td>2</td>
          <td class="w3-list-img">
            <a href="single.html"><img src="images/m2.jpg" alt="" /> <span>Barakah</span></a>
          </td>
          <td>2017</td>
          <td class="w3-list-info"><a href="genre.html">Sami Yusuf</a></td>
        </tr>
      </tbody>
    </table>
  </div>
</div>

Then, when loading the content, use the nth-child selector to target the specific table cell you want to populate:

function AssignAlbumIntoDOM(albumName, albumYear, albumPhotoPath, artistName, albumsCount, i, letter) {
  if (i < 25 && i >= 0) { // this raises some red flags. check your calling function.
    jQuery("#" + letter + " h4 span").text(albumsCount);
    jQuery("#" + i + " td:nth-child(2) img").attr('src',albumPhotoPath);
    jQuery("#" + i + " td:nth-child(3)").html(albumYear);
    jQuery("#" + i + " td:nth-child(4)").html(artistName);
  }
}

I changed the index of nth-child because <img> is the second child because nth-child starts indexing from 1 not 0

and .text(albumsCount) is not in side the table rows to use i


问:
Replacing strings recursively in a Linked list in Java
Trying to create a method that will replace all instances of a string in a linked list with the chosen replacement string.

However, what I've got only seems to check the node chosen by the third argument, and does not recur through the list.

```<code>public void replace(String firstItem, String replaceItem, Node n){
    if (n != null) {
        if (n.getItem().equals(firstItem)) {
            n.setItem(replaceItem);
            n = n.next();
        }
    }
}
</code>```

Here is the main app:

```<code>public class ListApp {

    public static void main(String[] args){
        Node n4 = new Node("green", null);
        Node n3 = new Node("red", n4);
        Node n2 = new Node("red", n3);
        Node n1 = new Node("red", n2);

        LinkedList list = new LinkedList(n1);

        System.out.println(list);

        list.replace("red", "RED", n1); // CALLING THE METHOD

        System.out.println(list);

    }
}
</code>```

However the output comes out as:

```<code>RED, red, red, green
</code>```

Not sure what I need to do to make it so it checks every node.

If needed, the node library:

```<code>package lib;

public class Node {
    private String item;
    private Node nextItem;

    public Node(String str, Node n){
        item = str;
        nextItem = n;
    }
    public String getItem(){
        return item;
    }
    public void setItem(String str){
        item = str;
    }
    public Node next(){
        return nextItem;
    }
    public void setNext(Node n){
        nextItem = n;
    }
}
</code>```

Any information would be greatly appreciated, thanks!

答:
You almost had it:</p>

```<code>public void replace(String firstItem, String replaceItem, Node n){
    if (n != null) {
        if (n.getItem().equals(firstItem)) {
            n.setItem(replaceItem);
            n = n.next();
        }
        replace(firstItem, replaceItem, n); //Recursive call here
    }
}
</code>```

Body:
Trying to create a method that will replace all instances of a string in a linked list with the chosen replacement string.

However, what I've got only seems to check the node chosen by the third argument, and does not recur through the list.

public void replace(String firstItem, String replaceItem, Node n){
    if (n != null) {
        if (n.getItem().equals(firstItem)) {
            n.setItem(replaceItem);
            n = n.next();
        }
    }
}

Here is the main app:

public class ListApp {

    public static void main(String[] args){
        Node n4 = new Node("green", null);
        Node n3 = new Node("red", n4);
        Node n2 = new Node("red", n3);
        Node n1 = new Node("red", n2);

        LinkedList list = new LinkedList(n1);

        System.out.println(list);

        list.replace("red", "RED", n1); // CALLING THE METHOD

        System.out.println(list);

    }
}

However the output comes out as:

RED, red, red, green

Not sure what I need to do to make it so it checks every node.

If needed, the node library:

package lib;

public class Node {
    private String item;
    private Node nextItem;

    public Node(String str, Node n){
        item = str;
        nextItem = n;
    }
    public String getItem(){
        return item;
    }
    public void setItem(String str){
        item = str;
    }
    public Node next(){
        return nextItem;
    }
    public void setNext(Node n){
        nextItem = n;
    }
}

Any information would be greatly appreciated, thanks!

Body:
You almost had it:

public void replace(String firstItem, String replaceItem, Node n){
    if (n != null) {
        if (n.getItem().equals(firstItem)) {
            n.setItem(replaceItem);
            n = n.next();
        }
        replace(firstItem, replaceItem, n); //Recursive call here
    }
}


问:
Mongoose find return only exact property from object
I am using Mongoose with MongoDB and i have found this problem. I find one object in database, then i return only the object property, but when i call the variable it returns whole object not the wanted property.

```<code>var CharacterInDbCounter = await UserModel.findOne({battletag: req.user.battletag}, function(err, user){
    if (err) {
        console.log(err);
    } else {
        return user.characters
    }
})
console.log(CharacterInDbCounter);
</code>```

returns:

```<code>{ _id: 5a25a14a05656b24accfe231,
  id: 1234,
  battletag: 'Something',
  provider: 'bnet',
  __v: 0,
  characters:
   [ 5a25a14a05656b24accfe218,
     5a25a14a05656b24accfe219,
     5a25a14a05656b24accfe21a,
     5a25a14a05656b24accfe21b,
     5a25a14a05656b24accfe21c,
     5a25a14a05656b24accfe21d,
     5a25a14a05656b24accfe21e,
     5a25a14a05656b24accfe21f,
     5a25a14a05656b24accfe220,
     5a25a14a05656b24accfe221,
     5a25a14a05656b24accfe222,
     5a25a14a05656b24accfe223,
     5a25a14a05656b24accfe224,
     5a25a14a05656b24accfe225,
     5a25a14a05656b24accfe226,
     5a25a14a05656b24accfe227,
     5a25a14a05656b24accfe228,
     5a25a14a05656b24accfe229,
     5a25a14a05656b24accfe22a,
     5a25a14a05656b24accfe22b,
     5a25a14a05656b24accfe22c,
     5a25a14a05656b24accfe22d,
     5a25a14a05656b24accfe22e,
     5a25a14a05656b24accfe22f ] }
</code>```

答:
In order to achieve your goal you must do it in promise way

```<code>var CharacterInDbCounter = await UserModel.findOne({battletag: req.user.battletag})
    .then(function(user){
        return user.characters
    })
console.log(CharacterInDbCounter);
</code>```

Unfortunately when you use await you cannot catch errors by promise catch, you must surround your code in try/catch to catch exception and inside then check if user argument is not undefined or empty

```<code>try {
    var CharacterInDbCounter = await UserModel.findOne({battletag: req.user.battletag})
        .then(function(user) {
            if (!user) {
                // user not found
            }
            return user.characters
        })
    console.log(CharacterInDbCounter);

} catch(e) {
    // catch unexpected errors
}
</code>```

Body:
I am using Mongoose with MongoDB and i have found this problem. I find one object in database, then i return only the object property, but when i call the variable it returns whole object not the wanted property.

var CharacterInDbCounter = await UserModel.findOne({battletag: req.user.battletag}, function(err, user){
    if (err) {
        console.log(err);
    } else {
        return user.characters
    }
})
console.log(CharacterInDbCounter);

returns:

{ _id: 5a25a14a05656b24accfe231,
  id: 1234,
  battletag: 'Something',
  provider: 'bnet',
  __v: 0,
  characters:
   [ 5a25a14a05656b24accfe218,
     5a25a14a05656b24accfe219,
     5a25a14a05656b24accfe21a,
     5a25a14a05656b24accfe21b,
     5a25a14a05656b24accfe21c,
     5a25a14a05656b24accfe21d,
     5a25a14a05656b24accfe21e,
     5a25a14a05656b24accfe21f,
     5a25a14a05656b24accfe220,
     5a25a14a05656b24accfe221,
     5a25a14a05656b24accfe222,
     5a25a14a05656b24accfe223,
     5a25a14a05656b24accfe224,
     5a25a14a05656b24accfe225,
     5a25a14a05656b24accfe226,
     5a25a14a05656b24accfe227,
     5a25a14a05656b24accfe228,
     5a25a14a05656b24accfe229,
     5a25a14a05656b24accfe22a,
     5a25a14a05656b24accfe22b,
     5a25a14a05656b24accfe22c,
     5a25a14a05656b24accfe22d,
     5a25a14a05656b24accfe22e,
     5a25a14a05656b24accfe22f ] }

Body:
In order to achieve your goal you must do it in promise way

var CharacterInDbCounter = await UserModel.findOne({battletag: req.user.battletag})
    .then(function(user){
        return user.characters
    })
console.log(CharacterInDbCounter);

Unfortunately when you use await you cannot catch errors by promise catch, you must surround your code in try/catch to catch exception and inside then check if user argument is not undefined or empty

try {
    var CharacterInDbCounter = await UserModel.findOne({battletag: req.user.battletag})
        .then(function(user) {
            if (!user) {
                // user not found
            }
            return user.characters
        })
    console.log(CharacterInDbCounter);

} catch(e) {
    // catch unexpected errors
}


问:
How to pass RawQuerySet result as a JSONResponse in DJango?
I have two models like this:

```<code>class McqQuestion(models.Model):
    mcq_question_id = models.IntegerField()
    test_id = models.ForeignKey('exam.Test')
    mcq_right_answer = models.IntegerField()

class UserMcqAnswer(models.Model):
    user = models.ForeignKey('exam.UserInfo')
    test_id = models.ForeignKey('exam.Test')
    mcq_question_id=models.ForeignKey('exam.McqQuestion')
    user_answer = models.IntegerField()
</code>```

I need to match the user_answer and mcq_right_answer. Able to do that by executing the below raw query.

```<code>rightAns=UserMcqAnswer.objects.raw('SELECT B.id, COUNT(A.mcq_question_id) AS RightAns\
                    FROM exam_mcqquestion AS A\
                    LEFT JOIN exam_usermcqanswer AS B\
                    ON A.mcq_question_id=B.mcq_question_id_id\
                    WHERE B.test_id_id=%s AND B.user_id=%s AND\
                    A.mcq_right_answer=B.user_answer',[test_id,user_id])
</code>```

1) But the problem is that couldn't able to pass the result as JSONResponse because it says TypeError: Object of type 'RawQuerySet' is not JSON serializable
2) Is there any alternative to this raw query by using the objects and filtered querysets?

答:
Django's serialize function's second argument can be any iterator that yields Django model instances.

So, in principle, you can use that raw SQL query that you worked on, using something like this:

```<code>query = """SELECT B.id, COUNT(A.mcq_question_id) AS RightAns\
                    FROM exam_mcqquestion AS A\
                    LEFT JOIN exam_usermcqanswer AS B\
                    ON A.mcq_question_id=B.mcq_question_id_id\
                    WHERE B.test_id_id=%s AND B.user_id=%s AND\
                    A.mcq_right_answer=B.user_answer"""%(test_id, user_id)
</code>```

and then getting the json data you'll return, as:

```<code>from django.core import serializers
data = serializers.serialize('json', UserMcqAnswer.objects.raw(query), fields=('some_field_you_want', 'another_field', 'and_some_other_field'))
</code>```

Good luck finding the best way to solve your issue

Edit: small fix, added an import

Body:
I have two models like this:

class McqQuestion(models.Model):
    mcq_question_id = models.IntegerField()
    test_id = models.ForeignKey('exam.Test')
    mcq_right_answer = models.IntegerField()

class UserMcqAnswer(models.Model):
    user = models.ForeignKey('exam.UserInfo')
    test_id = models.ForeignKey('exam.Test')
    mcq_question_id=models.ForeignKey('exam.McqQuestion')
    user_answer = models.IntegerField()

I need to match the user_answer and mcq_right_answer. Able to do that by executing the below raw query.

rightAns=UserMcqAnswer.objects.raw('SELECT B.id, COUNT(A.mcq_question_id) AS RightAns\
                    FROM exam_mcqquestion AS A\
                    LEFT JOIN exam_usermcqanswer AS B\
                    ON A.mcq_question_id=B.mcq_question_id_id\
                    WHERE B.test_id_id=%s AND B.user_id=%s AND\
                    A.mcq_right_answer=B.user_answer',[test_id,user_id])

1) But the problem is that couldn't able to pass the result as JSONResponse because it says TypeError: Object of type 'RawQuerySet' is not JSON serializable
2) Is there any alternative to this raw query by using the objects and filtered querysets?

Body:
Django's serialize function's second argument can be any iterator that yields Django model instances.

So, in principle, you can use that raw SQL query that you worked on, using something like this:

query = """SELECT B.id, COUNT(A.mcq_question_id) AS RightAns\
                    FROM exam_mcqquestion AS A\
                    LEFT JOIN exam_usermcqanswer AS B\
                    ON A.mcq_question_id=B.mcq_question_id_id\
                    WHERE B.test_id_id=%s AND B.user_id=%s AND\
                    A.mcq_right_answer=B.user_answer"""%(test_id, user_id)

and then getting the json data you'll return, as:

from django.core import serializers
data = serializers.serialize('json', UserMcqAnswer.objects.raw(query), fields=('some_field_you_want', 'another_field', 'and_some_other_field'))

Good luck finding the best way to solve your issue

Edit: small fix, added an import


问:
POST/PATCH works in LoopBack Explorer but not Postman
I am building an Angular app that uses a REST API built from NodeJS and LoopBack.  When trying to create new records, I'm getting a weird error both from my app and also in Postman. (Property names have been changed to protect the innocent)

```<code>The `ObjectName` instance is not valid.
Details: `id` can't be blank (value: undefined);
`property2` can't be blank (value: undefined);
`property3` can't be blank (value: undefined).
</code>```

This is what I have posted:

```<code>{
    "id":0,
    "property2":"foo",
    "property3":"bar",
    "property4":"R"
}
</code>```

The weirdest part of this is that when I try to run this through the LoopBack API Explorer, it works just fine.  I have the same issues with PATCH methods as well.

Any thoughts?

Thanks

答:
I found the cause. In previous APIs I have worked with, the back-end was set up with a model binder that would apply the properties it needed and discard the ones it did not.  So I have typically send the entire object in POSTs/PUTs/etc.  In this case, we do not have that, so it was throwing this weird error.  Once I added a method to my Angular auto-mapper that would strip the object down to only the bare necessities, it worked just fine.

In the end, I could have figured that out if the error message had been better.

Body:
I am building an Angular app that uses a REST API built from NodeJS and LoopBack.  When trying to create new records, I'm getting a weird error both from my app and also in Postman. (Property names have been changed to protect the innocent)

The `ObjectName` instance is not valid.
Details: `id` can't be blank (value: undefined);
`property2` can't be blank (value: undefined);
`property3` can't be blank (value: undefined).

This is what I have posted:

{
    "id":0,
    "property2":"foo",
    "property3":"bar",
    "property4":"R"
}

The weirdest part of this is that when I try to run this through the LoopBack API Explorer, it works just fine.  I have the same issues with PATCH methods as well.

Any thoughts?

Thanks


问:
See if any values match between 2 comma delimited strings
What would be the best way to return a bool denoting whether any values match between two comma delimited strings? For example:

"1,2,3,4" and "2,5,6,7" returns true because both strings have element 2

ex2:

"1,2,3,4" and "5,6,7,8" returns false because there are no common elements

答:
You can Split your strings by comma and use Intersect and Any methods. Like this:

```<code>var result = str1.Split(',').Intersect(str2.Split(',')).Any();
</code>```

Body:
You can Split your strings by comma and use Intersect and Any methods. Like this:

var result = str1.Split(',').Intersect(str2.Split(',')).Any();


问:
Data cleaning sentiment analysis
Lets say we have a vector (input):

```<code>v = ["apple", "man", "ship", " man", " apple"]
</code>```

The desired output should look something like:

```<code>y = [[1,5],[2,4]]
</code>```

Essentially y is an array of arrays that contains indices for words that differ by a "space" character (e.g. "apple" and " apple").

Any suggestions on how this can be done in MATLAB?

答:
I'm assuming that you want y to be a 2-D array where each row contains the indices for a string followed by its space-padded version. You can do that using the functions strip (or strtrim), setdiff, and ismember like so:

```<code>[strWithSpace, index1] = setdiff(v, strip(v));
[~, index2] = ismember(strip(strWithSpace), v);
y = [index2(:) index1(:)];
</code>```

And the result for your sample case:

```<code>y =

     1     5
     2     4
</code>```

Note that the above will work equally well for a string array as it will for a cell array of character arrays. So, your input could be either of the following:

```<code>v = ["apple", "man", "ship", " man", " apple"];
v = {'apple', 'man', 'ship', ' man', ' apple'};
</code>```

Title: Data cleaning sentiment analysis

Body:
Lets say we have a vector (input):

v = ["apple", "man", "ship", " man", " apple"]

The desired output should look something like:

y = [[1,5],[2,4]]

Essentially y is an array of arrays that contains indices for words that differ by a "space" character (e.g. "apple" and " apple").

Any suggestions on how this can be done in MATLAB?

Body:
I'm assuming that you want y to be a 2-D array where each row contains the indices for a string followed by its space-padded version. You can do that using the functions strip (or strtrim), setdiff, and ismember like so:

[strWithSpace, index1] = setdiff(v, strip(v));
[~, index2] = ismember(strip(strWithSpace), v);
y = [index2(:) index1(:)];

And the result for your sample case:

y =

     1     5
     2     4

Note that the above will work equally well for a string array as it will for a cell array of character arrays. So, your input could be either of the following:

v = ["apple", "man", "ship", " man", " apple"];
v = {'apple', 'man', 'ship', ' man', ' apple'};


问:
Reject String If Contains Any Non-Alpha Numeric Character
I am writing a program and want the program to not loop and request another search pattern if the search pattern (word) contains any non alpha numeric characters.

I have setup a Boolean word to false and an if statement to change the Boolean to true if the word contains letters or numbers. Then another if statement to allow the program to execute if the Boolean is true.

My logic must be off because it is still executing through the search pattern if I simply enter "/". The search pattern cannot contain any non alpha numeric characters to include spaces. I am trying to use Regex to solve this problem.

Sample problematic output:

```<code>Please enter a search pattern: /
Line number 1
this.a 2test/austin
            ^

Line number 8
ra charity Charityis 4 times a day/a.a-A
                                  ^
</code>```

Here is my applicable code:

```<code>while (again) {

   boolean found = false;
   System.out.printf("%n%s", "Please enter a search pattern: ", "%n");
   String wordToSearch = input.next();

   if (wordToSearch.equals("EINPUT")) {
      System.out.printf("%s", "Bye!");
      System.exit(0);
   }

   Pattern p = Pattern.compile("\\W*");
   Matcher m = p.matcher(wordToSearch);

   if (m.find())
      found = true;

   String data;
   int lineCount = 1;

   if (found = true) {
      try (FileInputStream fis =
                 new FileInputStream(this.inputPath.getPath())) {
         File file1 = this.inputPath;
         byte[] buffer2 = new byte[fis.available()];
         fis.read(buffer2);
         data = new String(buffer2);
         Scanner in = new Scanner(data).useDelimiter("\\\\|[^a-zA-z0-9]+");
         while (in.hasNextLine()) {

            String line = in.nextLine();

            Pattern pattern = Pattern.compile("\\b" + wordToSearch + "\\b");
            Matcher matcher = pattern.matcher(line);

            if (matcher.find()) {
               System.out.println("Line number " + lineCount);
               String stringToFile = f.findWords(line, wordToSearch);
               System.out.println();
            }
            lineCount++;
         }
      }
   }
}
</code>```

答:
Right now, what's happening is if the search pattern contains non alphanumeric characters, then do the loop. This is because found = true when the non alphanumeric characters are detected.

```<code>if(m.find())
    found = true;
</code>```

What it should be:

```<code>if(!m.find())
    found = true;
</code>```

It should be checking for the absence of nonalphanumeric characters.

Also, the boolean flag can just be simplified to:

```<code>boolean found = !m.find();
</code>```

You don't need to use the if statement.

Body:
I am writing a program and want the program to not loop and request another search pattern if the search pattern (word) contains any non alpha numeric characters.

I have setup a Boolean word to false and an if statement to change the Boolean to true if the word contains letters or numbers. Then another if statement to allow the program to execute if the Boolean is true.

My logic must be off because it is still executing through the search pattern if I simply enter "/". The search pattern cannot contain any non alpha numeric characters to include spaces. I am trying to use Regex to solve this problem.

Sample problematic output:

Please enter a search pattern: /
Line number 1
this.a 2test/austin
            ^

Line number 8
ra charity Charityis 4 times a day/a.a-A
                                  ^

Here is my applicable code:

while (again) {

   boolean found = false;
   System.out.printf("%n%s", "Please enter a search pattern: ", "%n");
   String wordToSearch = input.next();

   if (wordToSearch.equals("EINPUT")) {
      System.out.printf("%s", "Bye!");
      System.exit(0);
   }

   Pattern p = Pattern.compile("\\W*");
   Matcher m = p.matcher(wordToSearch);

   if (m.find())
      found = true;

   String data;
   int lineCount = 1;

   if (found = true) {
      try (FileInputStream fis =
                 new FileInputStream(this.inputPath.getPath())) {
         File file1 = this.inputPath;
         byte[] buffer2 = new byte[fis.available()];
         fis.read(buffer2);
         data = new String(buffer2);
         Scanner in = new Scanner(data).useDelimiter("\\\\|[^a-zA-z0-9]+");
         while (in.hasNextLine()) {

            String line = in.nextLine();

            Pattern pattern = Pattern.compile("\\b" + wordToSearch + "\\b");
            Matcher matcher = pattern.matcher(line);

            if (matcher.find()) {
               System.out.println("Line number " + lineCount);
               String stringToFile = f.findWords(line, wordToSearch);
               System.out.println();
            }
            lineCount++;
         }
      }
   }
}

Body:
Right now, what's happening is if the search pattern contains non alphanumeric characters, then do the loop. This is because found = true when the non alphanumeric characters are detected.

if(m.find())
    found = true;

What it should be:

if(!m.find())
    found = true;

It should be checking for the absence of nonalphanumeric characters.

Also, the boolean flag can just be simplified to:

boolean found = !m.find();

You don't need to use the if statement.


答: Try replacing the 8 with "8" as you are supposed to be comparing a String, not an integer.</p>

Title: Issues passing Edit text into an If statement


问:
Which one is more efficient: boolean or binary integer?
I have to store a binary value in a variable or an array element, to indicate that an option is enabled or disabled.

I believe using "Yes" or "No" is less efficient than 1 or 0 (or empty), but I wonder whether there's any difference between 1/0 and TRUE/FALSE, in terms of performance or memory usage or anything else.

Between

```<code>$option = 1; # if the option is enabled
$option = 0; # if the option is disabled OR
$option = ""; # if the option is disabled
</code>```

and

```<code>$option = TRUE; # if the option is enabled
$option = FALSE; # if the option is disabled
</code>```

which way is recommended? Why?

Thanks.

答: In the 'Anything else' category; a human will immediately understand if option is a Boolean type from Yes/No/True/False/On/Off, but not from 0/1, which can be a numerical option as well. This issue can be remedied by naming the option with suffix like _bool that indicates that it is a Boolean option and not an Integer option, this is then visible and obvious both in the code and any possible configuration file for options.</p>

Body:
I have to store a binary value in a variable or an array element, to indicate that an option is enabled or disabled.

I believe using "Yes" or "No" is less efficient than 1 or 0 (or empty), but I wonder whether there's any difference between 1/0 and TRUE/FALSE, in terms of performance or memory usage or anything else.

Between

$option = 1; # if the option is enabled
$option = 0; # if the option is disabled OR
$option = ""; # if the option is disabled

and

$option = TRUE; # if the option is enabled
$option = FALSE; # if the option is disabled

which way is recommended? Why?

Thanks.


问:
__cinit__() takes exactly 2 positional arguments when extending a Cython class
I want to extend scikit-learn's ClassificationCriterion class which is defined as a Cython class in an internal module sklearn.tree._criterion. I would like to do that in Python, as normally I don't have access to the pyx/pxd files of sklearn (so I cannot cimport them). However, when I try to extend ClassificationCriterion, I get the error TypeError: __cinit__() takes exactly 2 positional arguments (0 given). The below MWE reproduces the error, and shows that the error occurs after __new__ but before __init__.

Is there any way to extend a Cython class like this?

```<code>from sklearn.tree import DecisionTreeClassifier
from sklearn.tree._criterion import ClassificationCriterion

class MaxChildPrecision(ClassificationCriterion):
    def __new__(self, *args, **kwargs):
        print('new')
        super().__new__(MaxChildPrecision, *args, **kwargs)

    def __init__(self, *args, **kwargs):
        print('init')
        super(MaxChildPrecision).__init__(*args, **kwargs)

clf = DecisionTreeClassifier(criterion=MaxChildPrecision())
</code>```

答:
There two issues. Firstly, ClassificationCriterion requires two specific arguments to its constructor that you aren't passing it. You will have to work out what these arguments represent and pass them to the base class.

Secondly, there's a Cython issue. If we look at the description of how to use __cinit__ then we see:

Any arguments passed to the constructor will be passed to both the __cinit__() method and the __init__() method. If you anticipate subclassing your extension type in Python, you may find it useful to give the __cinit__() method * and ** arguments so that it can accept and ignore extra arguments. Otherwise, any Python subclass which has an init() with a different signature will have to override __new__() as well as __init__()

Unfortunately, the writers of sklearn didn't provide * and ** arguments, so you do have to override __new__. Something like this should work:

```<code>class MaxChildPrecision(ClassificationCriterion):
    def __init__(self,*args, **kwargs):
        pass

    def __new__(cls,*args,**kwargs):
        # I have NO IDEA if these arguments make sense!
        return super().__new__(cls,n_outputs=5,
                           n_classes=np.ones((2,),dtype=np.int))
</code>```

I pass the necessary arguments to ClassificationCriterion in __new__ and deal with the rest in __init__ as I see fit. I don't need to call the base class __init__ (because the base class doesn't define __init__).

Body:
I want to extend scikit-learn's ClassificationCriterion class which is defined as a Cython class in an internal module sklearn.tree._criterion. I would like to do that in Python, as normally I don't have access to the pyx/pxd files of sklearn (so I cannot cimport them). However, when I try to extend ClassificationCriterion, I get the error TypeError: __cinit__() takes exactly 2 positional arguments (0 given). The below MWE reproduces the error, and shows that the error occurs after __new__ but before __init__.

Is there any way to extend a Cython class like this?

from sklearn.tree import DecisionTreeClassifier
from sklearn.tree._criterion import ClassificationCriterion

class MaxChildPrecision(ClassificationCriterion):
    def __new__(self, *args, **kwargs):
        print('new')
        super().__new__(MaxChildPrecision, *args, **kwargs)

    def __init__(self, *args, **kwargs):
        print('init')
        super(MaxChildPrecision).__init__(*args, **kwargs)

clf = DecisionTreeClassifier(criterion=MaxChildPrecision())

Body:
There two issues. Firstly, ClassificationCriterion requires two specific arguments to its constructor that you aren't passing it. You will have to work out what these arguments represent and pass them to the base class.

Secondly, there's a Cython issue. If we look at the description of how to use __cinit__ then we see:

Any arguments passed to the constructor will be passed to both the __cinit__() method and the __init__() method. If you anticipate subclassing your extension type in Python, you may find it useful to give the __cinit__() method * and ** arguments so that it can accept and ignore extra arguments. Otherwise, any Python subclass which has an init() with a different signature will have to override __new__() as well as __init__()

Unfortunately, the writers of sklearn didn't provide * and ** arguments, so you do have to override __new__. Something like this should work:

class MaxChildPrecision(ClassificationCriterion):
    def __init__(self,*args, **kwargs):
        pass

    def __new__(cls,*args,**kwargs):
        # I have NO IDEA if these arguments make sense!
        return super().__new__(cls,n_outputs=5,
                           n_classes=np.ones((2,),dtype=np.int))

I pass the necessary arguments to ClassificationCriterion in __new__ and deal with the rest in __init__ as I see fit. I don't need to call the base class __init__ (because the base class doesn't define __init__).


问:
simple method postcondition might not hold
I'm having problems with this simple method in Dafny and I don't know why it doesn't work. Since there are no debugger and I'm new to this language I hope somebody can help. I think the specification is incomplete..

```<code>method Q2(x : int, y : int) returns (big : int, small : int)
  ensures big > small;
{
  if (x > y)
    {big, small := x, y;}
  else
    {big, small := y, x;}
}
</code>```

When I run it in the microsoft dafny compiler I get the following:

A postcondition might not hold on this return path. (Line 8)
This is the postcondition that might not hold. (Line 2)

答:
The issue is that x and y might be equal, in which case, big and small will also be equal.

You can fix the postcondition by changing it to big >= small. Or, you want to forbid the caller from ever passing equal x and y, you could add a precondition requiring that x != y.

Body:
I'm having problems with this simple method in Dafny and I don't know why it doesn't work. Since there are no debugger and I'm new to this language I hope somebody can help. I think the specification is incomplete..

method Q2(x : int, y : int) returns (big : int, small : int)
  ensures big > small;
{
  if (x > y)
    {big, small := x, y;}
  else
    {big, small := y, x;}
}

When I run it in the microsoft dafny compiler I get the following:

A postcondition might not hold on this return path. (Line 8)
This is the postcondition that might not hold. (Line 2)


问:
Why IS NULL not working in SQL?
I have a category table where there are some entries. I want to show those category names which don't have any mpid , spid and pid. I don't know what I did wrong, but my IS NULL statement is not working in here. My sql:

```<code>function select_all_main_category_info() {
        require 'db_connect_temp.php';
        $sql="SELECT * FROM tbl_category WHERE mpid IS NULL AND spid IS NULL AND pid IS NULL AND deletion_status=1";
        if (mysqli_query($db_connect, $sql)) {
            $query_result=mysqli_query($db_connect, $sql);
            return $query_result;
        } else {
            die("Query Problem". mysqli_error($db_connect));
        }
    }
</code>```

My PHP code to display category names:

```<code><?php

include_once 'applications.php';

$res=select_all_main_category_info();

while($info=mysqli_fetch_assoc($res)) {
    echo $info['category_name'];
    echo '<br>';
}
</code>```

The category table:

Can anyone please help?

答:
My issue is resolved. I wasn't aware of the IS NULL and empty statement. Here's the SQL which fixed the issue:

```<code>$sql="SELECT * FROM tbl_category WHERE mpid ='' AND spid ='' AND pid='' AND deletion_status=1";
</code>```

Title: Why IS NULL not working in SQL?

Body:
I have a category table where there are some entries. I want to show those category names which don't have any mpid , spid and pid. I don't know what I did wrong, but my IS NULL statement is not working in here. My sql:

function select_all_main_category_info() {
        require 'db_connect_temp.php';
        $sql="SELECT * FROM tbl_category WHERE mpid IS NULL AND spid IS NULL AND pid IS NULL AND deletion_status=1";
        if (mysqli_query($db_connect, $sql)) {
            $query_result=mysqli_query($db_connect, $sql);
            return $query_result;
        } else {
            die("Query Problem". mysqli_error($db_connect));
        }
    }

My PHP code to display category names:

<?php

include_once 'applications.php';

$res=select_all_main_category_info();

while($info=mysqli_fetch_assoc($res)) {
    echo $info['category_name'];
    echo '
';
}

The category table:

Can anyone please help?

Body:
My issue is resolved. I wasn't aware of the IS NULL and empty statement. Here's the SQL which fixed the issue:

$sql="SELECT * FROM tbl_category WHERE mpid ='' AND spid ='' AND pid='' AND deletion_status=1";


问:
Adding Data to other table based on fields
I am trying to get my CountryID field in tblCrater to match my other CountryID field in tblCountry based on the Country Name fields I have in both tables. It probably is a simple answer, but I cannot find the solution anywhere. I do not want a temporary join, and thanks for taking the time to assist, as I am an amateur at SQL at the moment.

Much Appreciated, and let me know if I need to clarify more.

```<code>USE master
GO
IF EXISTS(SELECT * FROM sys.databases WHERE name='DeepImpact2')
DROP DATABASE DeepImpact

CREATE DATABASE DeepImpact
GO
USE DeepImpact

IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'yourTABLEname' AND TABLE_SCHEMA = 'dbo')
    DROP TABLE dbo.tblCountry, dbo.tblCrater;

GO

CREATE TABLE tblCountry
(
CountryID INT IDENTITY(1,1)NOT NULL,
CountryName VARCHAR(MAX) NULL,
CountryCode VARCHAR(5) NULL,
)

CREATE TABLE tblCrater
(
CraterID INT IDENTITY(1,1) NOT NULL,
CraterName VARCHAR(MAX) NULL,
CountryID INT NULL,
Diameter DECIMAL(8,3)NULL,
Age INT NULL,
CountryName VARCHAR(MAX) NULL,
Lattitude DECIMAL(9,6) NULL,
Longitude DECIMAL(9,6) NULL,
CraterRegion VARCHAR(MAX) NULL
)
GO
ALTER TABLE tblCountry ADD PRIMARY KEY (CountryID)
ALTER TABLE tblCrater ADD PRIMARY KEY (CraterID)
GO

ALTER TABLE tblCrater
ADD FOREIGN KEY (CountryID)
REFERENCES tblCountry (CountryID)
GO

INSERT INTO tblCrater (CraterName, CraterRegion, CountryName, Diameter, Lattitude, Longitude, Age)
VALUES
('Boxhole','Northern Territory','Australia',0.2,-22.6166666666667,135.2,-3400),
('Campo del Cielo','Chaco','Argentina',0.1,-27.6333333333333,-61.7,-2000),
('Henbury','Northern Territory','Australia',0.2,-24.5666666666667,133.133333333333,-2200),
('Kaali','Saaremaa','Estonia',0.1,58.4,22.6666666666667,-1500),
('Macha','Sakha Republic','Russia', 0.3,60.1,117.583333333333,-5300),
('Morasko','Stare Miasto','Poland',0.1, 52.4833333333333,16.9,-3000),
('Rio Cuarto','Cordoba Province','Argentina',4.5,-32.8783333333333,-64.2233333333333,-8000),
('Wabar','Rub al Khali desert','Saudi Arabia',0.1,21.5,50.4666666666667,-1800),
('Tenoumer','Sahara Desert','Mauritania',1.9,22.9166666666667,-10.4083333333333,-19000),
('Meteor Crater','Arizona','United States',1.2,35.0333333333333,-111.016666666667,-47000),
('Xiuyan','Xiuyan','China',1.8, 40.35, 123.45,-48000),
('Lonar','Maharashtra','India',1.8,19.9666666666667,76.5166666666667,-50000),
('Agoudal','Atlas Mountains','Morocco',3.0,31.9833333333333,-5.5,-103000),
('Tswaing','Pretoria Saltpan','South Africa',1.1,-25.4,28.0816666666667,-218000),
('Zhamanshin','Kazakhstan','Kazakhstan',14.0,48.4,60.9666666666667,-948000),
('Bosumtwi','Ashanti','Ghana',10.0,6.505,-1.40833333333333,-1100000),
('Elgygytgyn','Chukotka Autonomous','Russia',18.0,67.5,172,-3500000),
('Bigach','Kazakhstan','Kazakhstan',8.0,48.5666666666667,82.0166666666667,-5000000),
('Karla','Tatarstan','Russia',10.0,54.9166666666667,48.0333333333333,-5000000),
('Karakul','Pamir Mountains','Tajikistan',52.0,39.0166666666667,73.45,-5000000),
('Vredefort','Free State','South Africa',300.0,-27,27.5,-2032000000),
('Sudbury','Ontario','Canada',250.0,46.6,-81.1833333333333,-1849000000),
('Chicxulub','Yucatan','Mexico',180.0,21.3333333333333,-89.5,-66000000),
('Popigai','Siberia','Russia',100.0,71.65,111.183333333333,-35000000),
('Manicouagan','Quebec','Canada',90,51.3833333333333,-68.7,-215000000),
('Acraman South','Australia','Australia',90.0,-32.0166666666667,135.45,-580000000),
('Morokweng','Kalahari Desert','South Africa',70.0,-26.4666666666667,23.5333333333333,-145000000),
('Kara','Nenetsia','Russia',65,69.1,64.15,-70000000),
('Beaverhead','Idaho and Montana','United States',60.0,44.25,114.00,-600000000),
('Tookoonooka','Queensland','Australia',55.0,-27.1166666666667,142.833333333333,-120000000),
('Charlevoix','Quebec','Canada',54.0,47.5333333333333,-70.3,-314000000),
('Siljan Ring','Dalarna','Sweden',52.0,61.0333333333333,14.8666666666667,-377000000),
('Karakul','Pamir Mountains','Tajikistan',52.0,39.0166666666667,73.45,-15000000),
('Montagnais','Nova Scotia','Canada',45.0,42.8833333333333,-64.2166666666667,-50500000),
('Araguainha','Central Brazil','Brazil',40.0,-16.7833333333333,-52.9833333333333,-244400000),
('Chesapeake Bay','Virginia','United States',40.0,37.2833333333333,-76.0166666666667,-35000000),
('Mjølnir','Barents Sea','Norway',40.0, 3.8,29.6666666666667,-142000000),
('Puchezh-Katunki','Nizhny Novgorod Oblast','Russia',40.0,56.9666666666667,43.7166666666667,-167000000),
('Saint Martin','Manitoba','Canada',40.0,51.7833333333333,-98.5333333333333,-227000000),
('Woodleigh','Western Australia','Australia',40.0,-26.05,114.666666666667,-364000000),
('Carswell','Saskatchewan','Canada',39.0,58.45,-109.5,-115000000),
('Clearwater','West Quebec','Canada',36.0,56.2166666666667,-74.5,-290000000),
('Manson','Iowa','United States',35.0,42.5833333333333,-94.55,-74000000),
('Slate Islands','Ontario','Canada',30.0,48.6666666666667,-87.00,-450000000),
('Yarrabubba','Western','Australia',30.0,-27.1666666666667,118.833333333333,-1800000000),
('Keurusselk','Western Finland','Finland',30.0,62.1333333333333,24.6,-1450000000),
('Shoemaker','Western Australia','Australia',30.0,-25.8666666666667,120.883333333333,-1630000000),
('Mistastin','Newfoundland','Canada',28.0,55.8833333333333,-63.3,-36400000),
('Clearwater','East Quebec','Canada',26.0,56.0666666666667,-74.1,-290000000),
('Kamensk','Southern Federal Dist','Russia',25.0,48.35,40.50,-49000000),
('Steen River','Alberta','Canada',25.0,59.5,-117.633333333333,-91000000),
('Strangways','Northern Territory','Australia',25.0,-15.2,133.583333333333,-646000000),
('Tunnunik','Northwest Territories','Canada',25.0,72.4666666666667,-113.966666666667,-280000000),
('Boltysh','Kirovohrad Oblast','Ukraine',24.0,48.9,32.25,-65170000),
('Nordlinger','Ries Bavaria','Germany',24.0,48.8833333333333,10.5666666666667,-144000000),
('Presquole','Quebec','Canada',24.0,49.7166666666667,-74.8,-500000000),
('Haughton','Nunavut','Canada',23.0,75.3833333333333,-89.6666666666667,-39000000),
('Lappajorvi','Western Finland','Finland',23.0,63.2,23.7,-73300000),
('Rochechouart','France','France',23.0,45.825,0.783333333333333,-206920000),
('Gosses Bluff','Northern Territory','Australia',22.0,-23.8166666666667,132.308333333333,-142500000),
('Amelia Creek','Northern Territory','Australia',20.0,-20.9166666666667,134.833333333333,-1030000000),
('Logancha','Siberia','Russia',20.0,65.5166666666667,95.9333333333333,-40000000),
('Obolon','Poltava Oblast','Ukraine',20.0,49.5833333333333,32.9166666666667,-169000000)

INSERT INTO tblCountry (CountryName, CountryCode)
VALUES
('Afghanistan','AF'),
('Aland Islands','AX'),
('Albania','AL'),
('Algeria','DZ'),
('American Samoa','AS'),
('Andorra','AD'),
('Angola','AO'),
('Anguilla','AI'),
('Antarctica','AQ'),
('Antigua and Barbuda','AG'),
('Argentina','AR'),
('Armenia','AM'),
('Aruba','AW'),
('Australia','AU'),
('Austria','AT'),
('Azerbaijan','AZ'),
('Bahamas','BS'),
('Bahrain','BH'),
('Bangladesh','BD'),
('Barbados','BB'),
('Belarus','BY'),
('Belgium','BE'),
('Belize','BZ'),
('Benin','BJ'),
('Bermuda','BM'),
('Bhutan','BT'),
('Bolivia'', Plurinational State of','BO'),
('Bonaire'', Sint Eustatius and Saba','BQ'),
('Bosnia and Herzegovina','BA'),
('Botswana','BW'),
('Bouvet Island','BV'),
('Brazil','BR'),
('British Indian Ocean Territory','IO'),
('Brunei Darussalam','BN'),
('Bulgaria','BG'),
('Burkina Faso','BF'),
('Burundi','BI'),
('Cambodia','KH'),
('Cameroon','CM'),
('Canada','CA'),
('Cape Verde','CV'),
('Cayman Islands','KY'),
('Central African Republic','CF'),
('Chad','TD'),
('Chile','CL'),
('China','CN'),
('Christmas Island','CX'),
('Cocos (Keeling) Islands','CC'),
('Colombia','CO'),
('Comoros','KM'),
('Congo','CG'),
('Congo'', the Democratic Republic of the','CD'),
('Cook Islands','CK'),
('Costa Rica','CR'),
('Côte d''Ivoire','CI'),
('Croatia','HR'),
('Cuba','CU'),
('Curaçao','CW'),
('Cyprus','CY'),
('Czech Republic','CZ'),
('Denmark','DK'),
('Djibouti','DJ'),
('Dominica','DM'),
('Dominican Republic','DO'),
('Ecuador','EC'),
('Egypt','EG'),
('El Salvador','SV'),
('Equatorial Guinea','GQ'),
('Eritrea','ER'),
('Estonia','EE'),
('Ethiopia','ET'),
('Falkland Islands (Malvinas)','FK'),
('Faroe Islands','FO'),
('Fiji','FJ'),
('Finland','FI'),
('France','FR'),
('French Guiana','GF'),
('French Polynesia','PF'),
('French Southern Territories','TF'),
('Gabon','GA'),
('Gambia','GM'),
('Georgia','GE'),
('Germany','DE'),
('Ghana','GH'),
('Gibraltar','GI'),
('Greece','GR'),
('Greenland','GL'),
('Grenada','GD'),
('Guadeloupe','GP'),
('Guam','GU'),
('Guatemala','GT'),
('Guernsey','GG'),
('Guinea','GN'),
('Guinea-Bissau','GW'),
('Guyana','GY'),
('Haiti','HT'),
('Heard Island and McDonald Islands','HM'),
('Holy See (Vatican City State)','VA'),
('Honduras','HN'),
('Hong Kong','HK'),
('Hungary','HU'),
('Iceland','IS'),
('India','IN'),
('Indonesia','ID'),
('Iran'', Islamic Republic of','IR'),
('Iraq','IQ'),
('Ireland','IE'),
('Isle of Man','IM'),
('Israel','IL'),
('Italy','IT'),
('Jamaica','JM'),
('Japan','JP'),
('Jersey','JE'),
('Jordan','JO'),
('Kazakhstan','KZ'),
('Kenya','KE'),
('Kiribati','KI'),
('Korea'', Democratic People''s Republic of','KP'),
('Korea'', Republic of','KR'),
('Kuwait','KW'),
('Kyrgyzstan','KG'),
('Lao People''s Democratic Republic','LA'),
('Latvia','LV'),
('Lebanon','LB'),
('Lesotho','LS'),
('Liberia','LR'),
('Libya','LY'),
('Liechtenstein','LI'),
('Lithuania','LT'),
('Luxembourg','LU'),
('Macao','MO'),
('Macedonia'', the Former Yugoslav Republic of','MK'),
('Madagascar','MG'),
('Malawi','MW'),
('Malaysia','MY'),
('Maldives','MV'),
('Mali','ML'),
('Malta','MT'),
('Marshall Islands','MH'),
('Martinique','MQ'),
('Mauritania','MR'),
('Mauritius','MU'),
('Mayotte','YT'),
('Mexico','MX'),
('Micronesia'', Federated States of','FM'),
('Moldova'', Republic of','MD'),
('Monaco','MC'),
('Mongolia','MN'),
('Montenegro','ME'),
('Montserrat','MS'),
('Morocco','MA'),
('Mozambique','MZ'),
('Myanmar','MM'),
('Namibia','NA'),
('Nauru','NR'),
('Nepal','NP'),
('Netherlands','NL'),
('New Caledonia','NC'),
('New Zealand','NZ'),
('Nicaragua','NI'),
('Niger','NE'),
('Nigeria','NG'),
('Niue','NU'),
('Norfolk Island','NF'),
('Northern Mariana Islands','MP'),
('Norway','NO'),
('Oman','OM'),
('Pakistan','PK'),
('Palau','PW'),
('Palestine'', State of','PS'),
('Panama','PA'),
('Papua New Guinea','PG'),
('Paraguay','PY'),
('Peru','PE'),
('Philippines','PH'),
('Pitcairn','PN'),
('Poland','PL'),
('Portugal','PT'),
('Puerto Rico','PR'),
('Qatar','QA'),
('Réunion','RE'),
('Romania','RO'),
('Russian Federation','RU'),
('Rwanda','RW'),
('Saint Barthélemy','BL'),
('Saint Helena'', Ascension and Tristan da Cunha','SH'),
('Saint Kitts and Nevis','KN'),
('Saint Lucia','LC'),
('Saint Martin (French part)','MF'),
('Saint Pierre and Miquelon','PM'),
('Saint Vincent and the Grenadines','VC'),
('Samoa','WS'),
('San Marino','SM'),
('Sao Tome and Principe','ST'),
('Saudi Arabia','SA'),
('Senegal','SN'),
('Serbia','RS'),
('Seychelles','SC'),
('Sierra Leone','SL'),
('Singapore','SG'),
('Sint Maarten (Dutch part)','SX'),
('Slovakia','SK'),
('Slovenia','SI'),
('Solomon Islands','SB'),
('Somalia','SO'),
('South Africa','ZA'),
('South Georgia and the South Sandwich Islands','GS'),
('South Sudan','SS'),
('Spain','ES'),
('Sri Lanka','LK'),
('Sudan','SD'),
('Suriname','SR'),
('Svalbard and Jan Mayen','SJ'),
('Swaziland','SZ'),
('Sweden','SE'),
('Switzerland','CH'),
('Syrian Arab Republic','SY'),
('Taiwan'', Province of China','TW'),
('Tajikistan','TJ'),
('Tanzania'', United Republic of','TZ'),
('Thailand','TH'),
('Timor-Leste','TL'),
('Togo','TG'),
('Tokelau','TK'),
('Tonga','TO'),
('Trinidad and Tobago','TT'),
('Tunisia','TN'),
('Turkey','TR'),
('Turkmenistan','TM'),
('Turks and Caicos Islands','TC'),
('Tuvalu','TV'),
('Uganda','UG'),
('Ukraine','UA'),
('United Arab Emirates','AE'),
('United Kingdom','GB'),
('United States','US'),
('United States Minor Outlying Islands','UM'),
('Uruguay','UY'),
('Uzbekistan','UZ'),
('Vanuatu','VU'),
('Venezuela'', Bolivarian Republic of','VE'),
('Viet Nam','VN'),
('Virgin Islands'', British','VG'),
('Virgin Islands'', U.S.','VI'),
('Wallis and Futuna','WF'),
('Western Sahara','EH'),
('Yemen','YE'),
('Zambia','ZM'),
('Zimbabwe','ZW')

SELECT * FROM tblCrater
SELECT * FROM tblCountry
</code>```

答:
Because tblCrater accepts NULL values, you can keep your queries and add this one. It will change tblCrater's CountryID value to match tblCountry's value for the same CountryName

```<code>UPDATE tblCrater
SET tblCrater.CountryID = tblCrater.CountryID
FROM tblCrater
INNER JOIN tblCountry
        ON tblCrater.CountryName = tblCountry.CountryName
</code>```

EDIT : This is only good if you add data only once. A trigger could be an alternate solution if more data will be add to the tables over time

```<code>CREATE TRIGGER add_countryid
ON tblCrater
AFTER INSERT, UPDATE
AS BEGIN
    UPDATE x
        SET x.CountryID = tblCrater.CountryID
        FROM tblCrater x
        INNER JOIN INSERTED i
            ON i.CraterID = x.CraterID
        INNER JOIN tblCountry
            ON x.CountryName = tblCountry.CountryName
END
GO
</code>```

Body:
I am trying to get my CountryID field in tblCrater to match my other CountryID field in tblCountry based on the Country Name fields I have in both tables. It probably is a simple answer, but I cannot find the solution anywhere. I do not want a temporary join, and thanks for taking the time to assist, as I am an amateur at SQL at the moment.

Much Appreciated, and let me know if I need to clarify more.

USE master
GO
IF EXISTS(SELECT * FROM sys.databases WHERE name='DeepImpact2')
DROP DATABASE DeepImpact

CREATE DATABASE DeepImpact
GO
USE DeepImpact

IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'yourTABLEname' AND TABLE_SCHEMA = 'dbo')
    DROP TABLE dbo.tblCountry, dbo.tblCrater;

GO

CREATE TABLE tblCountry
(
CountryID INT IDENTITY(1,1)NOT NULL,
CountryName VARCHAR(MAX) NULL,
CountryCode VARCHAR(5) NULL,
)

CREATE TABLE tblCrater
(
CraterID INT IDENTITY(1,1) NOT NULL,
CraterName VARCHAR(MAX) NULL,
CountryID INT NULL,
Diameter DECIMAL(8,3)NULL,
Age INT NULL,
CountryName VARCHAR(MAX) NULL,
Lattitude DECIMAL(9,6) NULL,
Longitude DECIMAL(9,6) NULL,
CraterRegion VARCHAR(MAX) NULL
)
GO
ALTER TABLE tblCountry ADD PRIMARY KEY (CountryID)
ALTER TABLE tblCrater ADD PRIMARY KEY (CraterID)
GO

ALTER TABLE tblCrater
ADD FOREIGN KEY (CountryID)
REFERENCES tblCountry (CountryID)
GO

INSERT INTO tblCrater (CraterName, CraterRegion, CountryName, Diameter, Lattitude, Longitude, Age)
VALUES
('Boxhole','Northern Territory','Australia',0.2,-22.6166666666667,135.2,-3400),
('Campo del Cielo','Chaco','Argentina',0.1,-27.6333333333333,-61.7,-2000),
('Henbury','Northern Territory','Australia',0.2,-24.5666666666667,133.133333333333,-2200),
('Kaali','Saaremaa','Estonia',0.1,58.4,22.6666666666667,-1500),
('Macha','Sakha Republic','Russia', 0.3,60.1,117.583333333333,-5300),
('Morasko','Stare Miasto','Poland',0.1, 52.4833333333333,16.9,-3000),
('Rio Cuarto','Cordoba Province','Argentina',4.5,-32.8783333333333,-64.2233333333333,-8000),
('Wabar','Rub al Khali desert','Saudi Arabia',0.1,21.5,50.4666666666667,-1800),
('Tenoumer','Sahara Desert','Mauritania',1.9,22.9166666666667,-10.4083333333333,-19000),
('Meteor Crater','Arizona','United States',1.2,35.0333333333333,-111.016666666667,-47000),
('Xiuyan','Xiuyan','China',1.8, 40.35, 123.45,-48000),
('Lonar','Maharashtra','India',1.8,19.9666666666667,76.5166666666667,-50000),
('Agoudal','Atlas Mountains','Morocco',3.0,31.9833333333333,-5.5,-103000),
('Tswaing','Pretoria Saltpan','South Africa',1.1,-25.4,28.0816666666667,-218000),
('Zhamanshin','Kazakhstan','Kazakhstan',14.0,48.4,60.9666666666667,-948000),
('Bosumtwi','Ashanti','Ghana',10.0,6.505,-1.40833333333333,-1100000),
('Elgygytgyn','Chukotka Autonomous','Russia',18.0,67.5,172,-3500000),
('Bigach','Kazakhstan','Kazakhstan',8.0,48.5666666666667,82.0166666666667,-5000000),
('Karla','Tatarstan','Russia',10.0,54.9166666666667,48.0333333333333,-5000000),
('Karakul','Pamir Mountains','Tajikistan',52.0,39.0166666666667,73.45,-5000000),
('Vredefort','Free State','South Africa',300.0,-27,27.5,-2032000000),
('Sudbury','Ontario','Canada',250.0,46.6,-81.1833333333333,-1849000000),
('Chicxulub','Yucatan','Mexico',180.0,21.3333333333333,-89.5,-66000000),
('Popigai','Siberia','Russia',100.0,71.65,111.183333333333,-35000000),
('Manicouagan','Quebec','Canada',90,51.3833333333333,-68.7,-215000000),
('Acraman South','Australia','Australia',90.0,-32.0166666666667,135.45,-580000000),
('Morokweng','Kalahari Desert','South Africa',70.0,-26.4666666666667,23.5333333333333,-145000000),
('Kara','Nenetsia','Russia',65,69.1,64.15,-70000000),
('Beaverhead','Idaho and Montana','United States',60.0,44.25,114.00,-600000000),
('Tookoonooka','Queensland','Australia',55.0,-27.1166666666667,142.833333333333,-120000000),
('Charlevoix','Quebec','Canada',54.0,47.5333333333333,-70.3,-314000000),
('Siljan Ring','Dalarna','Sweden',52.0,61.0333333333333,14.8666666666667,-377000000),
('Karakul','Pamir Mountains','Tajikistan',52.0,39.0166666666667,73.45,-15000000),
('Montagnais','Nova Scotia','Canada',45.0,42.8833333333333,-64.2166666666667,-50500000),
('Araguainha','Central Brazil','Brazil',40.0,-16.7833333333333,-52.9833333333333,-244400000),
('Chesapeake Bay','Virginia','United States',40.0,37.2833333333333,-76.0166666666667,-35000000),
('Mjølnir','Barents Sea','Norway',40.0, 3.8,29.6666666666667,-142000000),
('Puchezh-Katunki','Nizhny Novgorod Oblast','Russia',40.0,56.9666666666667,43.7166666666667,-167000000),
('Saint Martin','Manitoba','Canada',40.0,51.7833333333333,-98.5333333333333,-227000000),
('Woodleigh','Western Australia','Australia',40.0,-26.05,114.666666666667,-364000000),
('Carswell','Saskatchewan','Canada',39.0,58.45,-109.5,-115000000),
('Clearwater','West Quebec','Canada',36.0,56.2166666666667,-74.5,-290000000),
('Manson','Iowa','United States',35.0,42.5833333333333,-94.55,-74000000),
('Slate Islands','Ontario','Canada',30.0,48.6666666666667,-87.00,-450000000),
('Yarrabubba','Western','Australia',30.0,-27.1666666666667,118.833333333333,-1800000000),
('Keurusselk','Western Finland','Finland',30.0,62.1333333333333,24.6,-1450000000),
('Shoemaker','Western Australia','Australia',30.0,-25.8666666666667,120.883333333333,-1630000000),
('Mistastin','Newfoundland','Canada',28.0,55.8833333333333,-63.3,-36400000),
('Clearwater','East Quebec','Canada',26.0,56.0666666666667,-74.1,-290000000),
('Kamensk','Southern Federal Dist','Russia',25.0,48.35,40.50,-49000000),
('Steen River','Alberta','Canada',25.0,59.5,-117.633333333333,-91000000),
('Strangways','Northern Territory','Australia',25.0,-15.2,133.583333333333,-646000000),
('Tunnunik','Northwest Territories','Canada',25.0,72.4666666666667,-113.966666666667,-280000000),
('Boltysh','Kirovohrad Oblast','Ukraine',24.0,48.9,32.25,-65170000),
('Nordlinger','Ries Bavaria','Germany',24.0,48.8833333333333,10.5666666666667,-144000000),
('Presquole','Quebec','Canada',24.0,49.7166666666667,-74.8,-500000000),
('Haughton','Nunavut','Canada',23.0,75.3833333333333,-89.6666666666667,-39000000),
('Lappajorvi','Western Finland','Finland',23.0,63.2,23.7,-73300000),
('Rochechouart','France','France',23.0,45.825,0.783333333333333,-206920000),
('Gosses Bluff','Northern Territory','Australia',22.0,-23.8166666666667,132.308333333333,-142500000),
('Amelia Creek','Northern Territory','Australia',20.0,-20.9166666666667,134.833333333333,-1030000000),
('Logancha','Siberia','Russia',20.0,65.5166666666667,95.9333333333333,-40000000),
('Obolon','Poltava Oblast','Ukraine',20.0,49.5833333333333,32.9166666666667,-169000000)

INSERT INTO tblCountry (CountryName, CountryCode)
VALUES
('Afghanistan','AF'),
('Aland Islands','AX'),
('Albania','AL'),
('Algeria','DZ'),
('American Samoa','AS'),
('Andorra','AD'),
('Angola','AO'),
('Anguilla','AI'),
('Antarctica','AQ'),
('Antigua and Barbuda','AG'),
('Argentina','AR'),
('Armenia','AM'),
('Aruba','AW'),
('Australia','AU'),
('Austria','AT'),
('Azerbaijan','AZ'),
('Bahamas','BS'),
('Bahrain','BH'),
('Bangladesh','BD'),
('Barbados','BB'),
('Belarus','BY'),
('Belgium','BE'),
('Belize','BZ'),
('Benin','BJ'),
('Bermuda','BM'),
('Bhutan','BT'),
('Bolivia'', Plurinational State of','BO'),
('Bonaire'', Sint Eustatius and Saba','BQ'),
('Bosnia and Herzegovina','BA'),
('Botswana','BW'),
('Bouvet Island','BV'),
('Brazil','BR'),
('British Indian Ocean Territory','IO'),
('Brunei Darussalam','BN'),
('Bulgaria','BG'),
('Burkina Faso','BF'),
('Burundi','BI'),
('Cambodia','KH'),
('Cameroon','CM'),
('Canada','CA'),
('Cape Verde','CV'),
('Cayman Islands','KY'),
('Central African Republic','CF'),
('Chad','TD'),
('Chile','CL'),
('China','CN'),
('Christmas Island','CX'),
('Cocos (Keeling) Islands','CC'),
('Colombia','CO'),
('Comoros','KM'),
('Congo','CG'),
('Congo'', the Democratic Republic of the','CD'),
('Cook Islands','CK'),
('Costa Rica','CR'),
('Côte d''Ivoire','CI'),
('Croatia','HR'),
('Cuba','CU'),
('Curaçao','CW'),
('Cyprus','CY'),
('Czech Republic','CZ'),
('Denmark','DK'),
('Djibouti','DJ'),
('Dominica','DM'),
('Dominican Republic','DO'),
('Ecuador','EC'),
('Egypt','EG'),
('El Salvador','SV'),
('Equatorial Guinea','GQ'),
('Eritrea','ER'),
('Estonia','EE'),
('Ethiopia','ET'),
('Falkland Islands (Malvinas)','FK'),
('Faroe Islands','FO'),
('Fiji','FJ'),
('Finland','FI'),
('France','FR'),
('French Guiana','GF'),
('French Polynesia','PF'),
('French Southern Territories','TF'),
('Gabon','GA'),
('Gambia','GM'),
('Georgia','GE'),
('Germany','DE'),
('Ghana','GH'),
('Gibraltar','GI'),
('Greece','GR'),
('Greenland','GL'),
('Grenada','GD'),
('Guadeloupe','GP'),
('Guam','GU'),
('Guatemala','GT'),
('Guernsey','GG'),
('Guinea','GN'),
('Guinea-Bissau','GW'),
('Guyana','GY'),
('Haiti','HT'),
('Heard Island and McDonald Islands','HM'),
('Holy See (Vatican City State)','VA'),
('Honduras','HN'),
('Hong Kong','HK'),
('Hungary','HU'),
('Iceland','IS'),
('India','IN'),
('Indonesia','ID'),
('Iran'', Islamic Republic of','IR'),
('Iraq','IQ'),
('Ireland','IE'),
('Isle of Man','IM'),
('Israel','IL'),
('Italy','IT'),
('Jamaica','JM'),
('Japan','JP'),
('Jersey','JE'),
('Jordan','JO'),
('Kazakhstan','KZ'),
('Kenya','KE'),
('Kiribati','KI'),
('Korea'', Democratic People''s Republic of','KP'),
('Korea'', Republic of','KR'),
('Kuwait','KW'),
('Kyrgyzstan','KG'),
('Lao People''s Democratic Republic','LA'),
('Latvia','LV'),
('Lebanon','LB'),
('Lesotho','LS'),
('Liberia','LR'),
('Libya','LY'),
('Liechtenstein','LI'),
('Lithuania','LT'),
('Luxembourg','LU'),
('Macao','MO'),
('Macedonia'', the Former Yugoslav Republic of','MK'),
('Madagascar','MG'),
('Malawi','MW'),
('Malaysia','MY'),
('Maldives','MV'),
('Mali','ML'),
('Malta','MT'),
('Marshall Islands','MH'),
('Martinique','MQ'),
('Mauritania','MR'),
('Mauritius','MU'),
('Mayotte','YT'),
('Mexico','MX'),
('Micronesia'', Federated States of','FM'),
('Moldova'', Republic of','MD'),
('Monaco','MC'),
('Mongolia','MN'),
('Montenegro','ME'),
('Montserrat','MS'),
('Morocco','MA'),
('Mozambique','MZ'),
('Myanmar','MM'),
('Namibia','NA'),
('Nauru','NR'),
('Nepal','NP'),
('Netherlands','NL'),
('New Caledonia','NC'),
('New Zealand','NZ'),
('Nicaragua','NI'),
('Niger','NE'),
('Nigeria','NG'),
('Niue','NU'),
('Norfolk Island','NF'),
('Northern Mariana Islands','MP'),
('Norway','NO'),
('Oman','OM'),
('Pakistan','PK'),
('Palau','PW'),
('Palestine'', State of','PS'),
('Panama','PA'),
('Papua New Guinea','PG'),
('Paraguay','PY'),
('Peru','PE'),
('Philippines','PH'),
('Pitcairn','PN'),
('Poland','PL'),
('Portugal','PT'),
('Puerto Rico','PR'),
('Qatar','QA'),
('Réunion','RE'),
('Romania','RO'),
('Russian Federation','RU'),
('Rwanda','RW'),
('Saint Barthélemy','BL'),
('Saint Helena'', Ascension and Tristan da Cunha','SH'),
('Saint Kitts and Nevis','KN'),
('Saint Lucia','LC'),
('Saint Martin (French part)','MF'),
('Saint Pierre and Miquelon','PM'),
('Saint Vincent and the Grenadines','VC'),
('Samoa','WS'),
('San Marino','SM'),
('Sao Tome and Principe','ST'),
('Saudi Arabia','SA'),
('Senegal','SN'),
('Serbia','RS'),
('Seychelles','SC'),
('Sierra Leone','SL'),
('Singapore','SG'),
('Sint Maarten (Dutch part)','SX'),
('Slovakia','SK'),
('Slovenia','SI'),
('Solomon Islands','SB'),
('Somalia','SO'),
('South Africa','ZA'),
('South Georgia and the South Sandwich Islands','GS'),
('South Sudan','SS'),
('Spain','ES'),
('Sri Lanka','LK'),
('Sudan','SD'),
('Suriname','SR'),
('Svalbard and Jan Mayen','SJ'),
('Swaziland','SZ'),
('Sweden','SE'),
('Switzerland','CH'),
('Syrian Arab Republic','SY'),
('Taiwan'', Province of China','TW'),
('Tajikistan','TJ'),
('Tanzania'', United Republic of','TZ'),
('Thailand','TH'),
('Timor-Leste','TL'),
('Togo','TG'),
('Tokelau','TK'),
('Tonga','TO'),
('Trinidad and Tobago','TT'),
('Tunisia','TN'),
('Turkey','TR'),
('Turkmenistan','TM'),
('Turks and Caicos Islands','TC'),
('Tuvalu','TV'),
('Uganda','UG'),
('Ukraine','UA'),
('United Arab Emirates','AE'),
('United Kingdom','GB'),
('United States','US'),
('United States Minor Outlying Islands','UM'),
('Uruguay','UY'),
('Uzbekistan','UZ'),
('Vanuatu','VU'),
('Venezuela'', Bolivarian Republic of','VE'),
('Viet Nam','VN'),
('Virgin Islands'', British','VG'),
('Virgin Islands'', U.S.','VI'),
('Wallis and Futuna','WF'),
('Western Sahara','EH'),
('Yemen','YE'),
('Zambia','ZM'),
('Zimbabwe','ZW')

SELECT * FROM tblCrater
SELECT * FROM tblCountry

Body:
Because tblCrater accepts NULL values, you can keep your queries and add this one. It will change tblCrater's CountryID value to match tblCountry's value for the same CountryName

UPDATE tblCrater
SET tblCrater.CountryID = tblCrater.CountryID
FROM tblCrater
INNER JOIN tblCountry
        ON tblCrater.CountryName = tblCountry.CountryName

EDIT : This is only good if you add data only once. A trigger could be an alternate solution if more data will be add to the tables over time

CREATE TRIGGER add_countryid
ON tblCrater
AFTER INSERT, UPDATE
AS BEGIN
    UPDATE x
        SET x.CountryID = tblCrater.CountryID
        FROM tblCrater x
        INNER JOIN INSERTED i
            ON i.CraterID = x.CraterID
        INNER JOIN tblCountry
            ON x.CountryName = tblCountry.CountryName
END
GO


问:
linq data context abstraction
I'm finding myself writing this line for every query:

```<code>using ( MyDataModel thisDataContext = new MyDataModel() )
{
  linq query
}
</code>```

Is there a better way to declare a data context?

Thanks.

答:
We actually put our data context object on the current thread as Thread Static object. Doing this does away with us having to pass the context object around to each method that needs it.

We have an n-tier architecture, and when our middle tier is called from a client, we just new up a context object and put it on the thread. Then, any method that needs to make a database call just pulls the context object off the thread. So, there are very few places in our middle-tier code where we are actually creating a context object. In fact, just one place, if I recall correctly.

Even with this method, our context objects don't live all that long (which is a good thing).

Title: linq data context abstraction

Body:
I'm finding myself writing this line for every query:

using ( MyDataModel thisDataContext = new MyDataModel() )
{
  linq query
}

Is there a better way to declare a data context?

Thanks.


问:
MDX Excel Pivot formula
Would appreciate any help with this, I’m struggling with the MDX  trying to calculate BMI ( Body Mass Index = Weight / Height Squared ), as a Calculated Member in PivotTable Tools -> Analyze -> OLAP Tools -> MDX Calculated Member.

I believe I need an IF, as Height might be 0 in some cases, and hence /DIV0 issues.

IF [Height] IS > 0 THEN ( [Weight] / ( [Height] * [Height] ) ELSE 0 END IF

Thanks in advance for any help.

Thanks
Gav

答:
please try the below in the calculated field:

```<code>=IF(Height> 0,Weight/(Height *Height ),0)
</code>```

If this is not what you are looking for please let me know :)

Title: MDX Excel Pivot formula

Body:
please try the below in the calculated field:

=IF(Height> 0,Weight/(Height *Height ),0)

If this is not what you are looking for please let me know :)


问:
PhpStorm meta and multiple factory arguments
I've been trying to setup the .phpstorm.meta.php file for factory methods but I can't get it to fully work. It works for factory methods that only takes 1 argument, but if there are 2 or more arguments, it doesn't work.

So basically, all factory methods that takes more than 1 argument is affected, especially splat arguments i.e factory(string $className, ...$ctorArgs).

Here is an example of my meta file;

```<code><?php
namespace PHPSTORM_META {
    override(
        \ContainerInterface::make(0),
        map([
            '' => '@',
        ])
    );
}
</code>```

This is the signature;

```<code><?php
interface ContainerInterface{
    /* @return mixed */
    public function make (string $className, ...$ctorArgs);
}
</code>```

And here is an example of expected/results;

```<code><?php
$container->make(MyClass::class, "hello", "world")-> // Nothing is indicated here, should indicate MyClass props/methods
</code>```

Am I doing something wrong here?

答: This is apparently a known bug; https://youtrack.jetbrains.com/issue/WI-38403</p>

Body:
I've been trying to setup the .phpstorm.meta.php file for factory methods but I can't get it to fully work. It works for factory methods that only takes 1 argument, but if there are 2 or more arguments, it doesn't work.

So basically, all factory methods that takes more than 1 argument is affected, especially splat arguments i.e factory(string $className, ...$ctorArgs).

Here is an example of my meta file;

<?php
namespace PHPSTORM_META {
    override(
        \ContainerInterface::make(0),
        map([
            '' => '@',
        ])
    );
}

This is the signature;

<?php
interface ContainerInterface{
    /* @return mixed */
    public function make (string $className, ...$ctorArgs);
}

And here is an example of expected/results;

<?php
$container->make(MyClass::class, "hello", "world")-> // Nothing is indicated here, should indicate MyClass props/methods

Am I doing something wrong here?


问:
Docker: how to connect from local container to local swarm port
We have swarm running on 6 hosts and about 15 containers. There are one accesspoint open as port 3010.

On every host, which are nodes of swarm, there is local isolated network with 3 docker containers. On each host, one of this containers want to connect to that publish port 3010.

I like to use port on that host, which is currently running that container. I do not know, if this is wise?

How to solve the name of host to use on docker container to connect to the local swarm port. Localhost and 127.0.0.1 are not available. I can connect container on overlay network on swarm, but it is not possible, when starting container, because of local isolated network.

答:
How to solve the name of host to use on docker container to connect to the local swarm port.

It the name of your service name.

E.g. when docker service create --name blue --network dev markuman/color

then you can attache to this service container with figuring out the exactly name id

```<code>docker ps| grep blueeb46c52d0568        markuman/color:latest
"/bin/sh -c '/bin/..."   51 seconds ago      Up 49 seconds       80/tcp              blue.1.o5w76smq3kh5jlomltf6yohj3
</code>```

and simply do

```<code>docker exec -ti blue.1.o5w76smq3kh5jlomltf6yohj3 bash
</code>```

That's it. From there you can ping or ssh into other serivces which are assigned to the same network.

E.g. when docker service create --name apache ... is running in the same network, just do a ping apache. That's sufficient

Body:
How to solve the name of host to use on docker container to connect to the local swarm port.

It the name of your service name.

E.g. when docker service create --name blue --network dev markuman/color

then you can attache to this service container with figuring out the exactly name id

docker ps| grep blueeb46c52d0568        markuman/color:latest
"/bin/sh -c '/bin/..."   51 seconds ago      Up 49 seconds       80/tcp              blue.1.o5w76smq3kh5jlomltf6yohj3

and simply do

docker exec -ti blue.1.o5w76smq3kh5jlomltf6yohj3 bash

That's it. From there you can ping or ssh into other serivces which are assigned to the same network.

E.g. when docker service create --name apache ... is running in the same network, just do a ping apache. That's sufficient


问:
When developing a maven project with intellj idea, the module display is sorted
I want to display it on the left in the order of modules in the pom.xml file, as follows：

I know "sort by type",but this is not what I want:

答:
There is no way to sort module like this,
refer to the following link: https://intellij-support.jetbrains.com/hc/en-us/community/posts/206256729-Can-I-sort-modules-according-to-the-maven-pom-xml-

The Project view shows the physical structure of your project on disk, not logical structure according to some
criteria


问:
C++ sizeof on string array not returning expected results when passed to a function
Trying to find the size of an array dynamically. Getting the size while in main() works fine but doesn't when i pass it to the GetSize function.

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

using namespace std;

string GetSize(string array[]);

int main()
{
  string array[] = {"A", "B", "C", "D", "E"};
  int ARRAY_SIZE = (sizeof(array) / sizeof(array[0]));

  cout << "Total Size: " << sizeof(array) << endl;
  cout << "Single Element Size: " << sizeof(array[0]) << endl;

  // Pass the array as an argument to GetSize()
  GetSize(array);
}

string GetSize(string array[])
{
  // Get size of the array
  int ARRAY_SIZE = (sizeof(array) / sizeof(array[0]));

  cout << "Size of array is: " << sizeof(array) << endl;
  cout << "Size of 1st element is: " << sizeof(array[0]);
}
</code>```

Output

```<code>// Total Size: 160
// Single Element Size: 32
// Size of array is: 8
// Size of 1st element is: 32
</code>```

I have no clue why the discrepancy between the Total Size and the Size of array.

Repl Sandbox: https://repl.it/@phreelyfe/Size-Of-Error

答:
What about

```<code>template <typename T, std::size_t N>
constexpr std::size_t getArrSize (const T(&)[N])
 { return N; }
</code>```

?

I mean: different arrays, with different sizes, are different types.

So you have to explicit the size for the incoming argument.

When you write

```<code>string GetSize(string array[])
</code>```

the compiler consider string array[] as a string * array, so you get sizeof(array) as the size of the pointer (8).

In main() the sizeof(array) is the size of the string[5], so 160.

Body:
Trying to find the size of an array dynamically. Getting the size while in main() works fine but doesn't when i pass it to the GetSize function.

#include <iostream>
#include <string>

using namespace std;

string GetSize(string array[]);

int main()
{
  string array[] = {"A", "B", "C", "D", "E"};
  int ARRAY_SIZE = (sizeof(array) / sizeof(array[0]));

  cout << "Total Size: " << sizeof(array) << endl;
  cout << "Single Element Size: " << sizeof(array[0]) << endl;

  // Pass the array as an argument to GetSize()
  GetSize(array);
}

string GetSize(string array[])
{
  // Get size of the array
  int ARRAY_SIZE = (sizeof(array) / sizeof(array[0]));

  cout << "Size of array is: " << sizeof(array) << endl;
  cout << "Size of 1st element is: " << sizeof(array[0]);
}

Output

// Total Size: 160
// Single Element Size: 32
// Size of array is: 8
// Size of 1st element is: 32

I have no clue why the discrepancy between the Total Size and the Size of array.

Repl Sandbox: https://repl.it/@phreelyfe/Size-Of-Error

Body:
What about

template <typename T, std::size_t N>
constexpr std::size_t getArrSize (const T(&)[N])
 { return N; }

?

I mean: different arrays, with different sizes, are different types.

So you have to explicit the size for the incoming argument.

When you write

string GetSize(string array[])

the compiler consider string array[] as a string * array, so you get sizeof(array) as the size of the pointer (8).

In main() the sizeof(array) is the size of the string[5], so 160.