问:
How do I sort an array full of null Values WITHOUT using Comparator?
this is my first post. As you can guess, this is a related homework question but I am having some trouble on this topic because others have been able to use Comparators to compare null objects to eachother, I cannot. Here is my code:

This is where the string is declared and located

```<code>public class OrderedStringArrayList {

    private String[] array;

    @SuppressWarnings("unchecked")

    public OrderedStringArrayList() {
        array = new String[10];

    }
</code>```

This is the actual sort

```<code> public int insert(String item) {
        boolean arrIsOpen = false;
        //------------------------Insert Sort Vars---------------------------
        int parseOne = 0;
        int parseTwo = 0;
        int reaLen = array.length;
        String check = "";
        //-------------------------------------------------------------------

        for (int i = 0; i < array.length; i++) {
            /*---------------------------------------------Check for Open slot-----------------------------------------------*/
            if (array[i] == null) {
                arrIsOpen = true;
            }
            if (arrIsOpen == true) {
                array[i] = item;
                break;
            }
        }
            /*--------------------------------------------------------------------------------------------*/
        if (arrIsOpen == true) { //Insert Sort here

            for (parseOne = 1; parseOne < (reaLen); parseOne++) {
                check = array[parseOne];

                parseTwo = parseOne - 1;
                while (parseTwo >= 0 && ((check.compareTo(array[parseTwo]) < 0))) {
                    array[parseTwo + 1] = array[parseTwo];
                    parseTwo--;
                }
                array[parseTwo + 1] = check;
            }
        }
        else {                  // Grow the array by factor of 2 and copy over elements
            String[] backingArray = new String[2 * array.length];
            for (int i = 0; i < array.length; i++) {
                backingArray[i] = array[i];
            }
            /*----------------------------------------------------------------------Sort--------------------*/
            reaLen = backingArray.length;
            for (parseOne = 1; parseOne < (reaLen); parseOne++) {
                check = array[parseOne];

                parseTwo = parseOne - 1;
                while (parseTwo >= 0 && (check.compareTo(array[parseTwo]) < 0)) {

                    array[parseTwo + 1] = array[parseTwo];
                    parseTwo--;
                }
                array[parseTwo + 1] = check;
            }
        }
        return 0;
    }
</code>```

and here is the test

```<code>
    @Test
    public void insertOneItem() {
        OrderedStringArrayList a = new OrderedStringArrayList();
        assertEquals("Size should be 0 after construction!", 0, a.size());
        a.insert("Hello!");
        assertEquals("Size should be 1 after one insert!", 1, a.size());
    }

</code>```

My error occurs on the second code block on this line:

```<code>while (parseTwo >= 0 && (check.compareTo(array[parseTwo]) < 0)) {
</code>```

I get a NullPointerException because check == null and its trying to compare. Thing is,  I cannot use comparators to sort this. My end goal is to place an item in this array, grow it by 2 if there is no room. In order to check if there is room, there needs to be an empty (null) spot in my string array, but I cannot compare anything to the null spot so I cannot sort the array. This has been bugging me for days please help.

EDIT: Here is the Stacktrace / Error

```<code>java.lang.NullPointerException
    at OrderedStringArrayList.insert(OrderedStringArrayList.java:57)
    at OrderedStringArrayListTests.insertOneItem(OrderedStringArrayListTests.java:15)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
</code>```

答:
If your array content count is 1, it is already sorted, it is a special case where you don't go over your sorting mechanism</p>

```<code>public class OrderedStringArrayList {

   private String[] array;
   private int arrayContentCount = 0;

   @SuppressWarnings("unchecked")

    public OrderedStringArrayList() {
       array = new String[10];

    }
}

public int insert(String item) {

   if(arrayContentCount == 0) { <--- this
         //insert the item and be done with it.
     array[0] = item;
     arrayContentCount++;
     return;
   }
    boolean arrIsOpen = false;
    //------------------------Insert Sort Vars---------------------------
    int parseOne = 0;
    int parseTwo = 0;
    int reaLen = array.length;
    String check = "";
    //-------------------------------------------------------------------

    for (int i = 0; i < array.length; i++) {
        /*---------------------------------------------Check for Open slot-----------------------------------------------*/
        if (array[i] == null) {
            arrIsOpen = true;
        }
        if (arrIsOpen == true) {
            array[i] = item;
            break;
        }
    }
        /*--------------------------------------------------------------------------------------------*/
    if (arrIsOpen == true) { //Insert Sort here

        for (parseOne = 1; parseOne < (reaLen); parseOne++) {
            check = array[parseOne];
            if (check == null) {
                check = "0";
            }

            parseTwo = parseOne - 1;
            while (parseTwo >= 0 && ((check.compareTo(array[parseTwo]) < 0))) {
                array[parseTwo + 1] = array[parseTwo];
                parseTwo--;
            }
            array[parseTwo + 1] = check;
        }
    }
    else {                  // Grow the array by factor of 2 and copy over elements
        String[] backingArray = new String[2 * array.length];
        for (int i = 0; i < array.length; i++) {
            backingArray[i] = array[i];
        }
        /*----------------------------------------------------------------------Sort--------------------*/
        reaLen = backingArray.length;
        for (parseOne = 1; parseOne < (reaLen); parseOne++) {
            check = array[parseOne];

            parseTwo = parseOne - 1;
            while (parseTwo >= 0 && (check.compareTo(array[parseTwo]) < 0)) {

                array[parseTwo + 1] = array[parseTwo];
                parseTwo--;
            }
            array[parseTwo + 1] = check;
        }
    }

    //assuming that the item was inserted by now
    //arrayContentCount++;
    return 0;
}
</code>```

Body:
this is my first post. As you can guess, this is a related homework question but I am having some trouble on this topic because others have been able to use Comparators to compare null objects to eachother, I cannot. Here is my code:

This is where the string is declared and located

public class OrderedStringArrayList {

    private String[] array;

    @SuppressWarnings("unchecked")

    public OrderedStringArrayList() {
        array = new String[10];

    }

This is the actual sort

 public int insert(String item) {
        boolean arrIsOpen = false;
        //------------------------Insert Sort Vars---------------------------
        int parseOne = 0;
        int parseTwo = 0;
        int reaLen = array.length;
        String check = "";
        //-------------------------------------------------------------------

        for (int i = 0; i < array.length; i++) {
            /*---------------------------------------------Check for Open slot-----------------------------------------------*/
            if (array[i] == null) {
                arrIsOpen = true;
            }
            if (arrIsOpen == true) {
                array[i] = item;
                break;
            }
        }
            /*--------------------------------------------------------------------------------------------*/
        if (arrIsOpen == true) { //Insert Sort here

            for (parseOne = 1; parseOne < (reaLen); parseOne++) {
                check = array[parseOne];

                parseTwo = parseOne - 1;
                while (parseTwo >= 0 && ((check.compareTo(array[parseTwo]) < 0))) {
                    array[parseTwo + 1] = array[parseTwo];
                    parseTwo--;
                }
                array[parseTwo + 1] = check;
            }
        }
        else {                  // Grow the array by factor of 2 and copy over elements
            String[] backingArray = new String[2 * array.length];
            for (int i = 0; i < array.length; i++) {
                backingArray[i] = array[i];
            }
            /*----------------------------------------------------------------------Sort--------------------*/
            reaLen = backingArray.length;
            for (parseOne = 1; parseOne < (reaLen); parseOne++) {
                check = array[parseOne];

                parseTwo = parseOne - 1;
                while (parseTwo >= 0 && (check.compareTo(array[parseTwo]) < 0)) {

                    array[parseTwo + 1] = array[parseTwo];
                    parseTwo--;
                }
                array[parseTwo + 1] = check;
            }
        }
        return 0;
    }

and here is the test

    @Test
    public void insertOneItem() {
        OrderedStringArrayList a = new OrderedStringArrayList();
        assertEquals("Size should be 0 after construction!", 0, a.size());
        a.insert("Hello!");
        assertEquals("Size should be 1 after one insert!", 1, a.size());
    }

My error occurs on the second code block on this line:

while (parseTwo >= 0 && (check.compareTo(array[parseTwo]) < 0)) {

I get a NullPointerException because check == null and its trying to compare. Thing is,  I cannot use comparators to sort this. My end goal is to place an item in this array, grow it by 2 if there is no room. In order to check if there is room, there needs to be an empty (null) spot in my string array, but I cannot compare anything to the null spot so I cannot sort the array. This has been bugging me for days please help.

EDIT: Here is the Stacktrace / Error

java.lang.NullPointerException
    at OrderedStringArrayList.insert(OrderedStringArrayList.java:57)
    at OrderedStringArrayListTests.insertOneItem(OrderedStringArrayListTests.java:15)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)

Body:
If your array content count is 1, it is already sorted, it is a special case where you don't go over your sorting mechanism

public class OrderedStringArrayList {

   private String[] array;
   private int arrayContentCount = 0;

   @SuppressWarnings("unchecked")

    public OrderedStringArrayList() {
       array = new String[10];

    }
}

public int insert(String item) {

   if(arrayContentCount == 0) { <--- this
         //insert the item and be done with it.
     array[0] = item;
     arrayContentCount++;
     return;
   }
    boolean arrIsOpen = false;
    //------------------------Insert Sort Vars---------------------------
    int parseOne = 0;
    int parseTwo = 0;
    int reaLen = array.length;
    String check = "";
    //-------------------------------------------------------------------

    for (int i = 0; i < array.length; i++) {
        /*---------------------------------------------Check for Open slot-----------------------------------------------*/
        if (array[i] == null) {
            arrIsOpen = true;
        }
        if (arrIsOpen == true) {
            array[i] = item;
            break;
        }
    }
        /*--------------------------------------------------------------------------------------------*/
    if (arrIsOpen == true) { //Insert Sort here

        for (parseOne = 1; parseOne < (reaLen); parseOne++) {
            check = array[parseOne];
            if (check == null) {
                check = "0";
            }

            parseTwo = parseOne - 1;
            while (parseTwo >= 0 && ((check.compareTo(array[parseTwo]) < 0))) {
                array[parseTwo + 1] = array[parseTwo];
                parseTwo--;
            }
            array[parseTwo + 1] = check;
        }
    }
    else {                  // Grow the array by factor of 2 and copy over elements
        String[] backingArray = new String[2 * array.length];
        for (int i = 0; i < array.length; i++) {
            backingArray[i] = array[i];
        }
        /*----------------------------------------------------------------------Sort--------------------*/
        reaLen = backingArray.length;
        for (parseOne = 1; parseOne < (reaLen); parseOne++) {
            check = array[parseOne];

            parseTwo = parseOne - 1;
            while (parseTwo >= 0 && (check.compareTo(array[parseTwo]) < 0)) {

                array[parseTwo + 1] = array[parseTwo];
                parseTwo--;
            }
            array[parseTwo + 1] = check;
        }
    }

    //assuming that the item was inserted by now
    //arrayContentCount++;
    return 0;
}


来源: stackexchange

问:
firebase fails to save all data that i m trying to import
i m trying to to import data from a dict in the firebase and it looks like its loading it but instead of adding the data fields it looks like its just iterating though it cuz i can see all different values change and then it just saves the last one. how do i make it save it all? </p>

```<code>data=dict(zip(time, counts))

for i,j in data.items():
    doc_ref = db.collection(u'data_storage').document(u'some_data')
    doc_ref.set({
     u'time' : i,
     u'counts' : j
</code>```

答:
All your writes target the same document:

```<code>doc_ref = db.collection(u'data_storage').document(u'some_data')
</code>```

This loop overwrites the some_data document again and again. Here's how to create a new document for each data point:

```<code>for i, j in data.items():
    coll_ref = db.collection(u'data_storage').document(u'some_data').collection(u'data')
    coll_ref.add({
     u'time': i,
     u'counts': j})
</code>```

Each new document gets an auto-generated ID.

ContentLicense: CC BY-SA 4.0

Body:
i m trying to to import data from a dict in the firebase and it looks like its loading it but instead of adding the data fields it looks like its just iterating though it cuz i can see all different values change and then it just saves the last one. how do i make it save it all?

data=dict(zip(time, counts))

for i,j in data.items():
    doc_ref = db.collection(u'data_storage').document(u'some_data')
    doc_ref.set({
     u'time' : i,
     u'counts' : j

Body:
All your writes target the same document:

doc_ref = db.collection(u'data_storage').document(u'some_data')

This loop overwrites the some_data document again and again. Here's how to create a new document for each data point:

for i, j in data.items():
    coll_ref = db.collection(u'data_storage').document(u'some_data').collection(u'data')
    coll_ref.add({
     u'time': i,
     u'counts': j})

Each new document gets an auto-generated ID.


问:
React Native how to do min/max widths
I want to style a component in my interface. The component must have a width of at least 200, but I want to let it grow with screen width to up to 600. But, sometimes people use tablets or huge phones. And I don't want the component to be able to grow with the screen forever. I want it to have a maximum width of 600.

And I know maxWidth is a thing that is, at least for now, not a part of the flexbox implementation in React Native... so, is there a reasonable way to do this today?

答:
You can use the maxWidth, maxHeight, minWidth, minHeight layout properties supported by React Native.

Document here React Native layout props.

Example:

StyleSheet.create({
  container: {
    maxWidth: '80%',   // <-- Max width is 80%
    minHeight: 20,     // <-- Min height is 20
  },
});
```

ContentLicense: CC BY-SA 3.0

Title: React Native how to do min/max widths


问:
fetching data from a database in realtime, with ajax?
I am fetching data from the following database:

I have arduino-box that send that data.

And display the data with this CSS & HTML code:

```<code>    <div class="event">
        <img src="http://dummyimage.com/80x70/f00/fff.png" alt="picture" />
        <p>Room 2</p>
        <p class="patient-name">Jon Harris</p>
        <p class="event-text">This is a pixel. A flying pixel!</p>
        <p class="event-timestamp">feb 2 2011 - 23:01</p>
    </div>

.event {
    display:block;
    background: #ececec;
    width:380px;
    padding:10px;
    margin:10px;
    overflow:hidden;
    text-align: left;
}
.event img {
    display:block;
    float:left;
    margin-right:10px;
}

.event p {
    font-weight: bold;
}

.event img + p {
    display:inline;
}

.patient-name {
    display:inline;
    color: #999999;
    font-size: 9px;
    line-height:inherit;
    padding-left: 5px;
}
.event-text{
    color: #999999;
    font-size: 12px;
    padding-left: 5px;
}
.event-timestamp{
    color: #000;
    padding-left: 5px;
    font-size: 9px;
}
</code>```

Here is my PHP code:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>DASHBOARD - Arduino 3</title>
  <link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
    <?php
    $con = mysql_connect("localhost","*****","***");
        if(!con)
        {
            die('Could not connect: ' . mysql_error());
        }

        mysql_select_db("arduino_db",$con);

        $result = mysql_query("SELECT * FROM events");
        //Start container
        echo " <div id='background_container'> ";

        while($row = mysql_fetch_array($result))
        {
            echo "<div class='event'>";
            echo "<img src='img/ev_img/red.jpg' alt='picture' />";
            echo "<p>" . $row['inneboende'] . "</p>";
            echo "<p class='patient-name'>" . "$row['overvakare']" . "</p>";
            echo "<p class='event-text'>" . "$row['handelse']" . "</p>";
            echo "<p class='event-timestamp'>" . "$row['tid']" . "</p>";
            echo "</div>";
        }

        //end container
        echo "</div>"
        mysql_close($con);

    ?>
</body>
</html>
</code>```

The arduino box is sending data to the database.. lets say every 3sec. I dont want to press F5 every 5sec to get the new data. Should I use AJAX for this? I have read some AJAX on the net, but I haven´t find any good tuts for it.

答:
Put this in a separate php file, e.g. getEvents.php:

```<code><?php
$con = mysql_connect("localhost","*****","***");
    if(!con)
    {
        die('Could not connect: ' . mysql_error());
    }

    mysql_select_db("arduino_db",$con);

    $result = mysql_query("SELECT * FROM events");

    while($row = mysql_fetch_array($result))
    {
        echo "<div class='event'>";
        echo "<img src='img/ev_img/red.jpg' alt='picture' />";
        echo "<p>" . $row['inneboende'] . "</p>";
        echo "<p class='patient-name'>" . "$row['overvakare']" . "</p>";
        echo "<p class='event-text'>" . "$row['handelse']" . "</p>";
        echo "<p class='event-timestamp'>" . "$row['tid']" . "</p>";
        echo "</div>";
    }

    mysql_close($con);
</code>```

Then, load jquery and put the following in the head of the page:

```<code><script type="text/javascript">
    $(document).ready(function() {
        $.get('getEvents.php', function (data) {
            $('#background_container').html(data);
        });
    });
</script>
</code>```

Note: This is not the exact code you should use, take a look at it and change it so it works correctly for you.

Body:
I am fetching data from the following database:

I have arduino-box that send that data.

And display the data with this CSS & HTML code:

Room 2

Jon Harris

This is a pixel. A flying pixel!

feb 2 2011 - 23:01

.event {
    display:block;
    background: #ececec;
    width:380px;
    padding:10px;
    margin:10px;
    overflow:hidden;
    text-align: left;
}
.event img {
    display:block;
    float:left;
    margin-right:10px;
}

.event p {
    font-weight: bold;
}

.event img + p {
    display:inline;
}

.patient-name {
    display:inline;
    color: #999999;
    font-size: 9px;
    line-height:inherit;
    padding-left: 5px;
}
.event-text{
    color: #999999;
    font-size: 12px;
    padding-left: 5px;
}
.event-timestamp{
    color: #000;
    padding-left: 5px;
    font-size: 9px;
}

Here is my PHP code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>DASHBOARD - Arduino 3</title>
  <link rel="stylesheet" type="text/css" href="css/style.css">

    <?php
    $con = mysql_connect("localhost","*****","***");
        if(!con)
        {
            die('Could not connect: ' . mysql_error());
        }

        mysql_select_db("arduino_db",$con);

        $result = mysql_query("SELECT * FROM events");
        //Start container
        echo "
 ";

        while($row = mysql_fetch_array($result))
        {
            echo "
";
            echo "";
            echo "
" . $row['inneboende'] . "
";
            echo "
" . "$row['overvakare']" . "
";
            echo "
" . "$row['handelse']" . "
";
            echo "
" . "$row['tid']" . "
";
            echo "
";
        }

        //end container
        echo "
"
        mysql_close($con);

    ?>

The arduino box is sending data to the database.. lets say every 3sec. I dont want to press F5 every 5sec to get the new data. Should I use AJAX for this? I have read some AJAX on the net, but I haven´t find any good tuts for it.

Body:
Put this in a separate php file, e.g. getEvents.php:

<?php
$con = mysql_connect("localhost","*****","***");
    if(!con)
    {
        die('Could not connect: ' . mysql_error());
    }

    mysql_select_db("arduino_db",$con);

    $result = mysql_query("SELECT * FROM events");

    while($row = mysql_fetch_array($result))
    {
        echo "<div class='event'>";
        echo "<img src='img/ev_img/red.jpg' alt='picture' />";
        echo "<p>" . $row['inneboende'] . "</p>";
        echo "<p class='patient-name'>" . "$row['overvakare']" . "</p>";
        echo "<p class='event-text'>" . "$row['handelse']" . "</p>";
        echo "<p class='event-timestamp'>" . "$row['tid']" . "</p>";
        echo "</div>";
    }

    mysql_close($con);

Then, load jquery and put the following in the head of the page:

<script type="text/javascript">
    $(document).ready(function() {
        $.get('getEvents.php', function (data) {
            $('#background_container').html(data);
        });
    });
</script>

Note: This is not the exact code you should use, take a look at it and change it so it works correctly for you.


问:
PySpark Cannot calculate column wise standard deviation in Koalas DataFrame
I have a Koalas DataFrame in PySpark. I want to calculate the column-wise standard deviation. I have tried doing:

```<code>df2['x_std'] = df2[['x_1',
'x_2',
'x_3',
'x_4',
'x_5',
'x_6',
'x_7',
'x_8',
'x_9',
'x_10','x_11',
'x_12']].std(axis = 1)
</code>```

I get the following error:

```<code>TypeError: 'DataFrame' object does not support item assignment
</code>```

I also doing something like:

```<code>d1 = df2[['x_1',
'x_2',
'x_3',
'x_4',
'x_5',
'x_6',
'x_7',
'x_8',
'x_9',
'x_10','x_11',
'x_12']].std(axis = 1)

df2['x_std'] = d1 # d1 is a Koalas Series that should get assigned to the new column.
</code>```

I get this error while doing so:

```<code>Cannot combine column argument because it comes from a different dataframe
</code>```

Totally new to Koalas. Can anyone give some ideas? Thanks.

答:
You can set the option "compute.ops_on_diff_frames" to True and then perform the operation.

```<code>import databricks.koalas as ks

ks.set_option("compute.ops_on_diff_frames", True)

kdf = ks.DataFrame(
    {'a': [1, 2, 3, 4, 5, 6],
     'b': [2, 1, 7, 4, 2, 3],
     'c': [3, 7, 1, 4, 6, 5],
     'd': [4, 2, 3, 4, 3, 8],},)

kdf['dev'] = kdf[['a', 'b', 'c', 'd']].std(axis=1)
print (kdf)

   a  b  c  d       dev
0  1  2  3  4  1.241909
5  6  3  5  8  2.363684
1  2  1  7  2  2.348840
3  4  4  4  4  1.788854
2  3  7  1  3  2.223378
4  5  2  6  3  1.856200
</code>```

Not sure it is good practice though as it is not allowed by default.

Body:
I have a Koalas DataFrame in PySpark. I want to calculate the column-wise standard deviation. I have tried doing:

df2['x_std'] = df2[['x_1',
'x_2',
'x_3',
'x_4',
'x_5',
'x_6',
'x_7',
'x_8',
'x_9',
'x_10','x_11',
'x_12']].std(axis = 1)

I get the following error:

TypeError: 'DataFrame' object does not support item assignment

I also doing something like:

d1 = df2[['x_1',
'x_2',
'x_3',
'x_4',
'x_5',
'x_6',
'x_7',
'x_8',
'x_9',
'x_10','x_11',
'x_12']].std(axis = 1)

df2['x_std'] = d1 # d1 is a Koalas Series that should get assigned to the new column.

I get this error while doing so:

Cannot combine column argument because it comes from a different dataframe

Totally new to Koalas. Can anyone give some ideas? Thanks.

Body:
You can set the option "compute.ops_on_diff_frames" to True and then perform the operation.

import databricks.koalas as ks

ks.set_option("compute.ops_on_diff_frames", True)

kdf = ks.DataFrame(
    {'a': [1, 2, 3, 4, 5, 6],
     'b': [2, 1, 7, 4, 2, 3],
     'c': [3, 7, 1, 4, 6, 5],
     'd': [4, 2, 3, 4, 3, 8],},)

kdf['dev'] = kdf[['a', 'b', 'c', 'd']].std(axis=1)
print (kdf)

   a  b  c  d       dev
0  1  2  3  4  1.241909
5  6  3  5  8  2.363684
1  2  1  7  2  2.348840
3  4  4  4  4  1.788854
2  3  7  1  3  2.223378
4  5  2  6  3  1.856200

Not sure it is good practice though as it is not allowed by default.


问:
AttributeError: 'datetime.datetime' object has no attribute 'write'
Im trying to convert a str to a date object using the python-dateutil library

```<code>from dateutil.parser import *

datetime_object = parse('Fri Feb 14 19:39:51 +0000 2020')
pprint("DATETIME", datetime_object )
</code>```

However i get the following error:

AttributeError: 'datetime.datetime' object has no attribute 'write'

答: pprint documentation states that the arguments must have the write method implemented.  datetime does not.  I expect that your easiest path to a solution is to use any of the available str conversions in datetime, such as the various format specifications.

Body:
Im trying to convert a str to a date object using the python-dateutil library

from dateutil.parser import *

datetime_object = parse('Fri Feb 14 19:39:51 +0000 2020')
pprint("DATETIME", datetime_object )

However i get the following error:

AttributeError: 'datetime.datetime' object has no attribute 'write'


问:
How to concatenate a user inputted string using HTML input tag
I am doing the following:

<form action="https://www.google.com/search">

   <input type="text" name="q" id="corners">

   <input type="submit" value="Google Image Search">

</form>
```

However, I want to add additional default text to the URL after the user's input like this:

https://www.google.com/search?q=searchterm&some-additional-text

How can I do this?

答:
I ended up just using the following:

        <input type="hidden" name="test" value="test" style="display: none;">
        <input type="text" name="test">

```

Body:
I am doing the following:

<form action="https://www.google.com/search">

   <input type="text" name="q" id="corners">

   <input type="submit" value="Google Image Search">

</form>

However, I want to add additional default text to the URL after the user's input like this:

https://www.google.com/search?q=searchterm&some-additional-text

How can I do this?

Body:
I ended up just using the following:

   <div>
        <input type="hidden" name="test" value="test" style="display: none;">
        <input type="text" name="test">
   </div>


问:
console.error: "react-native-maps" AirGoogleMaps dir must be added to your xCode project

console.error: "react-native-maps" AirGoogleMaps dir must be added to your xCode project

I got this error when I am trying to test the example in react-native-maps module.

Github: https://github.com/airbnb/react-native-maps/tree/master/example

It is obvious that I should add the dir the to my Xcode project but I don't know how to add them.

May I have an example of adding dir to a Xcode project?

答:
I just removed following prop in MapView component and it worked!

provider={MapView.PROVIDER_GOOGLE}


问:
Does Akamai NetStorage has a presigned URL feature
Currently, Akamai has many upload mechanisms like FTP, RFTP, NetStorage Api and Aspera.

I would like to know whether Akamai NetStorage has a presigned URL feature-- A presigned URL is a URL that you can provide to your users to grant temporary access to a specific Akamai’s directory, Using the URL, a user can either READ the object or WRITE an Object (or update an existing object)

Thanks,

答: It depends on your architecture. Netstorage is Read/Writeable - subject to correct authentication headers accompanying your "presigned" URL. Such access to NetStorage is NOT scaleable. So if you just want to give a URL to many users, then you simply need a property configured in Akamai to do what you want.</p>


问:
How to load Gmail addon without opening mail message
We need to develop the gmail addon to read the checked mail messages and  process the content.We are using the below application json:

```<code>{
 "oauthScopes": [
 "https://www.googleapis.com/auth/gmail.addons.execute",
 "https://www.googleapis.com/auth/gmail.readonly"
],
"gmail": {
 "name": "My Addon",
 "logoUrl": "https://www.gstatic.com/images/icons/material/system/2x/bookmar     k_black_24dp.png",
 "contextualTriggers": [{
  "unconditional": {},
  "onTriggerFunction": "buildAddOn"
  }],
  "primaryColor": "#4285F4",
  "secondaryColor": "#4285F4"
 }
 }
</code>```

We have tried above json to load the gmail addon without opening message.

How to fix the error we get:

Open an Email Select an email for My Gmail Add-on to recommend
  content for you.

答:
This feature has been rolled out. You can now use a homepage trigger to open your addon even when the user is not viewing an email. Check out the docs here.

To use a homepage trigger, just add this to your manifest file:

```<code> {
  // ...
  "addOns": {
    // ...
    "common": {
      // ...
      "homepageTrigger": {
        "runFunction": "myFunction",
        "enabled": true
      }
    }
  }
}
</code>```

Body:
We need to develop the gmail addon to read the checked mail messages and  process the content.We are using the below application json:

{
 "oauthScopes": [
 "https://www.googleapis.com/auth/gmail.addons.execute",
 "https://www.googleapis.com/auth/gmail.readonly"
],
"gmail": {
 "name": "My Addon",
 "logoUrl": "https://www.gstatic.com/images/icons/material/system/2x/bookmar     k_black_24dp.png",
 "contextualTriggers": [{
  "unconditional": {},
  "onTriggerFunction": "buildAddOn"
  }],
  "primaryColor": "#4285F4",
  "secondaryColor": "#4285F4"
 }
 }

We have tried above json to load the gmail addon without opening message.

How to fix the error we get:

Open an Email Select an email for My Gmail Add-on to recommend
  content for you.

Body:
This feature has been rolled out. You can now use a homepage trigger to open your addon even when the user is not viewing an email. Check out the docs here.

To use a homepage trigger, just add this to your manifest file:

 {
  // ...
  "addOns": {
    // ...
    "common": {
      // ...
      "homepageTrigger": {
        "runFunction": "myFunction",
        "enabled": true
      }
    }
  }
}


问:
Removing pages from search engine results
Hey everyone, I'm a bit new to SEO. I built a one page website that initially utilized several pages (but are now removed), and it looks as if Google has indexed those so that they show up as search results. Is there any way to remove those from the search results? Thanks.</p>

答: You can use Robots exclusion rules.  This site details it : http://www.robotstxt.org/</p>


问:
Can't read file after writing it to temp folder in .NET Core
In my scenario, I have an use case where I must received a compressed file, do some validations and then find a specific file within the archive that I'll have to handle through a third-party library. I'm having some trouble getting such library to read the file though. This is what I came up with so far:

```<code>public async Task ShapeIt(ZipArchive archive)
{
    foreach (var entry in archive.Entries)
    {
        if (Path.GetExtension(entry.FullName).Equals(".shp"))
        {
            var stream = entry.Open();
            using var ms = new MemoryStream();
            await stream.CopyToAsync(ms);
            ms.Position = 0;
            var fileName = Path.GetTempFileName();
            try
            {
                using var fileStream = File.Open(fileName, FileMode.OpenOrCreate, FileAccess.Write,
                    FileShare.ReadWrite);

                var bytes = new byte[ms.Length];
                ms.Read(bytes, 0, (int)ms.Length);
                fileStream.Write(bytes, 0, bytes.Length);
                fileStream.Flush();
                fileStream.Close();

                var featureSource = new ShapeFileFeatureSource(fileName); // Class from 3rd-party
                featureSource.Open();
                // Do my stuff with the shapefile
            }
            finally
            {
                File.Delete(fileName);
            }
        }
    }
}
</code>```

Take notice that I'm using the "old way" of copying streams as Stream.CopyTo and Stream.CopyToAsync were creating empty files, explicitly calling fileStream.Close() looks like the only way to get the bytes into the file somehow, but that's beyond my point. Regardless, after closing the stream, upon calling featureSource.Open() my application throws

```<code>"The process cannot access the file 'C:\\Users\\me\\AppData\\Local\\Temp\\tmpE926.tmp' because it is
being used by another process."
</code>```

tmpE926.tmp being different every time, obviously. Also take notice that I'm creating a file because the constructor for ShapeFileFeatureSource demands not a stream, not a byte array, but a path.

A much shorter implementation

```<code>public async Task ShapeIt(ZipArchive archive)
{
    foreach (var entry in archive.Entries)
    {
        var tempFile = Path.GetTempFileName();
        try
        {
            entry.ExtractToFile(tempFile, true);

            if (Path.GetExtension(entry.FullName).Equals(".shp"))
            {
                var featureSource = new ShapeFileFeatureSource(tempFile);
                featureSource.Open();
                var type = featureSource.GetShapeFileType();
            }
        }
        finally
        {
            File.Delete(tempFile);
        }
    }
}
</code>```

will actually amount to the same error. I honestly don't think the problem lies within this library, but rather I'm the one screwing it up somehow. Does anyone have any ideas or should I contact the vendor's (unresponsive) tech support?

Edit: Just in case, this is such library Install-Package ThinkGeo.UI.WebApi but you have to subscribe to evaluate in order to use it.

答:
I could not find package for .NET Core with such classes, so I reproduced it through .NET Framework Nuget package. My answer mostly demonstrates how to deal with streams. It would be hard to tell what is wrong with your code, without having access to library you have

```<code>using DotSpatial.Data;
using System.IO;
using System.IO.Compression;

namespace ConsoleApp12
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var fs = File.OpenRead(@"C:\Users\jjjjjjjjjjjj\Downloads\1270055001_mb_2011_vic_shape.zip"))
            using (var zipFile = new ZipArchive(fs))
            {
                foreach (var entry in zipFile.Entries)
                {
                    if (entry.FullName.EndsWith(".shp"))
                    {
                        var tempFile = Path.GetTempFileName();
                        try
                        {
                            using (var entryStream = entry.Open())
                            using (var newFileStream = File.OpenWrite(tempFile))
                            {
                                entryStream.CopyTo(newFileStream);
                            }
                            var featureSource = ShapefileFeatureSource.Open(tempFile);
                            var type = featureSource.ShapeType;
                        }
                        finally
                        {
                            File.Delete(tempFile);
                        }
                    }
                }
            }
        }
    }
}
</code>```

UPD: installed trial version of ThinkGeo library, instead of unauthorized exception it gives me FileNotFoundException with given stacktrace

```<code>at ThinkGeo.Core.ValidatorHelper.CheckFileIsExist(String pathFilename)
at ThinkGeo.Core.ShapeFileIndex.xh8=(FileAccess readWriteMode)
^^^^^^^^^^^^^^^^^^^^^^^^^ Are we supposed to have index?
at ThinkGeo.Core.ShapeFile.xh8=(FileAccess readWriteMode)
at ThinkGeo.Core.ShapeFileFeatureSource.WjE=()
at ThinkGeo.Core.ShapeFileFeatureSource.OpenCore()
at ThinkGeo.Core.FeatureSource.Open()
at ConsoleApp20.Program.Main(String[] args) in
C:\Users\jjjjjjjjjjjj\source\repos\ConsoleApp20\ConsoleApp20\Program.cs:line 45
</code>```

ShapeFileIndex ? So I thought I should dig into this way

```<code>var featureSource = new ShapeFileFeatureSource(tempFile);
featureSource.RequireIndex = false; // no luck
featureSource.Open();
</code>```

I tried to find any reference to the idx file it wants, it has property IndexFilePathName, but unfortunately, I am out of luck. (Also tried different folder, so it is not 'Temp' folder issue)

Body:
In my scenario, I have an use case where I must received a compressed file, do some validations and then find a specific file within the archive that I'll have to handle through a third-party library. I'm having some trouble getting such library to read the file though. This is what I came up with so far:

public async Task ShapeIt(ZipArchive archive)
{
    foreach (var entry in archive.Entries)
    {
        if (Path.GetExtension(entry.FullName).Equals(".shp"))
        {
            var stream = entry.Open();
            using var ms = new MemoryStream();
            await stream.CopyToAsync(ms);
            ms.Position = 0;
            var fileName = Path.GetTempFileName();
            try
            {
                using var fileStream = File.Open(fileName, FileMode.OpenOrCreate, FileAccess.Write,
                    FileShare.ReadWrite);

                var bytes = new byte[ms.Length];
                ms.Read(bytes, 0, (int)ms.Length);
                fileStream.Write(bytes, 0, bytes.Length);
                fileStream.Flush();
                fileStream.Close();

                var featureSource = new ShapeFileFeatureSource(fileName); // Class from 3rd-party
                featureSource.Open();
                // Do my stuff with the shapefile
            }
            finally
            {
                File.Delete(fileName);
            }
        }
    }
}

Take notice that I'm using the "old way" of copying streams as Stream.CopyTo and Stream.CopyToAsync were creating empty files, explicitly calling fileStream.Close() looks like the only way to get the bytes into the file somehow, but that's beyond my point. Regardless, after closing the stream, upon calling featureSource.Open() my application throws

"The process cannot access the file 'C:\\Users\\me\\AppData\\Local\\Temp\\tmpE926.tmp' because it is
being used by another process."

tmpE926.tmp being different every time, obviously. Also take notice that I'm creating a file because the constructor for ShapeFileFeatureSource demands not a stream, not a byte array, but a path.

A much shorter implementation

public async Task ShapeIt(ZipArchive archive)
{
    foreach (var entry in archive.Entries)
    {
        var tempFile = Path.GetTempFileName();
        try
        {
            entry.ExtractToFile(tempFile, true);

            if (Path.GetExtension(entry.FullName).Equals(".shp"))
            {
                var featureSource = new ShapeFileFeatureSource(tempFile);
                featureSource.Open();
                var type = featureSource.GetShapeFileType();
            }
        }
        finally
        {
            File.Delete(tempFile);
        }
    }
}

will actually amount to the same error. I honestly don't think the problem lies within this library, but rather I'm the one screwing it up somehow. Does anyone have any ideas or should I contact the vendor's (unresponsive) tech support?

Edit: Just in case, this is such library Install-Package ThinkGeo.UI.WebApi but you have to subscribe to evaluate in order to use it.

Body:
I could not find package for .NET Core with such classes, so I reproduced it through .NET Framework Nuget package. My answer mostly demonstrates how to deal with streams. It would be hard to tell what is wrong with your code, without having access to library you have

using DotSpatial.Data;
using System.IO;
using System.IO.Compression;

namespace ConsoleApp12
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var fs = File.OpenRead(@"C:\Users\jjjjjjjjjjjj\Downloads\1270055001_mb_2011_vic_shape.zip"))
            using (var zipFile = new ZipArchive(fs))
            {
                foreach (var entry in zipFile.Entries)
                {
                    if (entry.FullName.EndsWith(".shp"))
                    {
                        var tempFile = Path.GetTempFileName();
                        try
                        {
                            using (var entryStream = entry.Open())
                            using (var newFileStream = File.OpenWrite(tempFile))
                            {
                                entryStream.CopyTo(newFileStream);
                            }
                            var featureSource = ShapefileFeatureSource.Open(tempFile);
                            var type = featureSource.ShapeType;
                        }
                        finally
                        {
                            File.Delete(tempFile);
                        }
                    }
                }
            }
        }
    }
}

UPD: installed trial version of ThinkGeo library, instead of unauthorized exception it gives me FileNotFoundException with given stacktrace

at ThinkGeo.Core.ValidatorHelper.CheckFileIsExist(String pathFilename)
at ThinkGeo.Core.ShapeFileIndex.xh8=(FileAccess readWriteMode)
^^^^^^^^^^^^^^^^^^^^^^^^^ Are we supposed to have index?
at ThinkGeo.Core.ShapeFile.xh8=(FileAccess readWriteMode)
at ThinkGeo.Core.ShapeFileFeatureSource.WjE=()
at ThinkGeo.Core.ShapeFileFeatureSource.OpenCore()
at ThinkGeo.Core.FeatureSource.Open()
at ConsoleApp20.Program.Main(String[] args) in
C:\Users\jjjjjjjjjjjj\source\repos\ConsoleApp20\ConsoleApp20\Program.cs:line 45

ShapeFileIndex ? So I thought I should dig into this way

var featureSource = new ShapeFileFeatureSource(tempFile);
featureSource.RequireIndex = false; // no luck
featureSource.Open();

I tried to find any reference to the idx file it wants, it has property IndexFilePathName, but unfortunately, I am out of luck. (Also tried different folder, so it is not 'Temp' folder issue)


问:
How to display Border Radius on Outlook
I have an Email Template which is working fine for all Gmail, Yahoo etc. But in Outlook it is not working. Can anyone please help me how to make it visible on Outlook.

Hello

 ${mail_script:notification_logo}

You Project(${URI_REF}) has been submitted and is being reviewed by ${u_project_manager}.

Title

${short_description}

Submitted by
Approver
Department

${submitter}
${u_project_manager}
${department}

Thank you,
IT Service Desk

```

答:
Only Outlook on IOS devices supports border-radius.

The Windows version out Outlook does not support border-radius since it uses Microsoft Word as its processor.

see camapaign monitor:
https://www.campaignmonitor.com/css/box-model/border-bottom/

Title: How to display Border Radius on Outlook


问:
Error message in Jupyter as "UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 3"
I am getting following error.

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 3

答:
Try calling read_csv with encoding='latin1', encoding='iso-8859-1' or encoding='cp1252'

Source : here


问:
How to manually set the attribute 'name' when Serializing
it seems to me that the answer is quite simple, but I could not manage to find an it, how do I change the name attribute when serialising using DRF? Check the circle in the image, I just got it from the DRF website in the Metadata section.

答:
As specified on the documentation on metadata [drf-doc]. You probably use the SimpleMetadata class [GitHub]. Here we see that the options are determined with:

```<code>    def determine_metadata(self, request, view):
        metadata = OrderedDict()
        <b>metadata['name'] = view.get_view_name()</b>
        metadata['description'] = view.get_view_description()
        metadata['renders'] = [renderer.media_type for renderer in view.renderer_classes]
        metadata['parses'] = [parser.media_type for parser in view.parser_classes]
        if hasattr(view, 'get_serializer'):
            actions = self.determine_actions(request, view)
            if actions:
                metadata['actions'] = actions
        return metadata</code>```

The get_view_name of a APIView [GitHub] is implemented as:

```<code>    def get_view_name(self):
        """
        Return the view name, as used in OPTIONS responses and in the
        browsable API.
        """
        func = <b>self.settings.VIEW_NAME_FUNCTION</b>
        return func(self)</code>```

The settings will thus by default determine the name of the function that calculates the view. This is specified by the VIEW_NAME_FUNCTION setting [drf-doc] that defaults to 'rest_framework.views.get_view_name'.

If we inspect the source code of this get_view_name function [GitHub], we see:

```<code>def get_view_name(view):
    """
    Given a view instance, return a textual name to represent the view.
    This name is used in the browsable API, and in OPTIONS responses.
    This function is the default for the `VIEW_NAME_FUNCTION` setting.
    """
    # Name may be set by some Views, such as a ViewSet.
    name = <b>getattr(view, 'name', None)</b>
    if name is not None:
        return <b>name</b>

    name = view.__class__.__name__
    name = formatting.remove_trailing_string(name, 'View')
    name = formatting.remove_trailing_string(name, 'ViewSet')
    name = formatting.camelcase_to_spaces(name)

    # Suffix may be set by some Views, such as a ViewSet.
    suffix = getattr(view, 'suffix', None)
    if suffix:
        name += ' ' + suffix

    return name</code>```

If your view thus contains a .name attribute, it will use that as the name. You thus can implement your APIView as:

```<code>class SomeAPIView(APIView):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        <b>self.name = 'Another name than To Do List'</b></code>```

If there is no name attribute, it will thus take the name of the view, try to get rid fo the View or ViewSet suffix, convert the camelcase to spaces, and optionally add a suffix (like 'List' for an ListAPIView).

Body:
As specified on the documentation on metadata [drf-doc]. You probably use the SimpleMetadata class [GitHub]. Here we see that the options are determined with:

    def determine_metadata(self, request, view):
        metadata = OrderedDict()
        metadata['name'] = view.get_view_name()
        metadata['description'] = view.get_view_description()
        metadata['renders'] = [renderer.media_type for renderer in view.renderer_classes]
        metadata['parses'] = [parser.media_type for parser in view.parser_classes]
        if hasattr(view, 'get_serializer'):
            actions = self.determine_actions(request, view)
            if actions:
                metadata['actions'] = actions
        return metadata

The get_view_name of a APIView [GitHub] is implemented as:

    def get_view_name(self):
        """
        Return the view name, as used in OPTIONS responses and in the
        browsable API.
        """
        func = self.settings.VIEW_NAME_FUNCTION
        return func(self)

The settings will thus by default determine the name of the function that calculates the view. This is specified by the VIEW_NAME_FUNCTION setting [drf-doc] that defaults to 'rest_framework.views.get_view_name'.

If we inspect the source code of this get_view_name function [GitHub], we see:

def get_view_name(view):
    """
    Given a view instance, return a textual name to represent the view.
    This name is used in the browsable API, and in OPTIONS responses.
    This function is the default for the `VIEW_NAME_FUNCTION` setting.
    """
    # Name may be set by some Views, such as a ViewSet.
    name = getattr(view, 'name', None)
    if name is not None:
        return name

    name = view.__class__.__name__
    name = formatting.remove_trailing_string(name, 'View')
    name = formatting.remove_trailing_string(name, 'ViewSet')
    name = formatting.camelcase_to_spaces(name)

    # Suffix may be set by some Views, such as a ViewSet.
    suffix = getattr(view, 'suffix', None)
    if suffix:
        name += ' ' + suffix

    return name

If your view thus contains a .name attribute, it will use that as the name. You thus can implement your APIView as:

class SomeAPIView(APIView):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.name = 'Another name than To Do List'

If there is no name attribute, it will thus take the name of the view, try to get rid fo the View or ViewSet suffix, convert the camelcase to spaces, and optionally add a suffix (like 'List' for an ListAPIView).


问:
ASP.NET Identity change password
I need ability to change password for user by admin. So, admin should not enter a current password of user, he should have ability to set a new password. I look at ChangePasswordAsync method, but this method requires to enter old password. So, this method is not appropriate for this task. Therefore I have made it by the following way:

```<code>    [HttpPost]
    public async Task<ActionResult> ChangePassword(ViewModels.Admin.ChangePasswordViewModel model)
    {
        var userManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        var result = await userManager.RemovePasswordAsync(model.UserId);
        if (result.Succeeded)
        {
            result = await userManager.AddPasswordAsync(model.UserId, model.Password);
            if (result.Succeeded)
            {
                return RedirectToAction("UserList");
            }
            else
            {
                ModelState.AddModelError("", result.Errors.FirstOrDefault());
            }
        }
        else
        {
            ModelState.AddModelError("", result.Errors.FirstOrDefault());
        }
        return View(model);
    }
</code>```

it works, but theoretically we can receive error on AddPasswordAsync method. So, old password will be removed but new is not set. It's not good. Any way to do it in "one transaction"?
PS. I seen ResetPasswordAsync method with reset token, seems, it's more safe (because can't be unstable situation with user) but in any case, it does by 2 actions.

答:
```<code>public async Task<ActionResult> ResetUserPassword(string id, string Password)
{
    //     Find User
    var user = await context.Users.Where(x => x.Id == id).SingleOrDefaultAsync();
    if (user == null)
    {
        return RedirectToAction("UserList");
    }
    await UserManager.RemovePasswordAsync(id);
    //     Add a user password only if one does not already exist
    await UserManager.AddPasswordAsync(id, Password);
    return RedirectToAction("UserDetail", new { id = id });
}
</code>```

Title: ASP.NET Identity change password

Body:
I need ability to change password for user by admin. So, admin should not enter a current password of user, he should have ability to set a new password. I look at ChangePasswordAsync method, but this method requires to enter old password. So, this method is not appropriate for this task. Therefore I have made it by the following way:

    [HttpPost]
    public async Task<ActionResult> ChangePassword(ViewModels.Admin.ChangePasswordViewModel model)
    {
        var userManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        var result = await userManager.RemovePasswordAsync(model.UserId);
        if (result.Succeeded)
        {
            result = await userManager.AddPasswordAsync(model.UserId, model.Password);
            if (result.Succeeded)
            {
                return RedirectToAction("UserList");
            }
            else
            {
                ModelState.AddModelError("", result.Errors.FirstOrDefault());
            }
        }
        else
        {
            ModelState.AddModelError("", result.Errors.FirstOrDefault());
        }
        return View(model);
    }

it works, but theoretically we can receive error on AddPasswordAsync method. So, old password will be removed but new is not set. It's not good. Any way to do it in "one transaction"?
PS. I seen ResetPasswordAsync method with reset token, seems, it's more safe (because can't be unstable situation with user) but in any case, it does by 2 actions.


问:
How to pass env variables to nuxt in production?
nuxt.config.js

```<code>modules: [
    '@nuxtjs/dotenv'
  ],
</code>```

server/index.js

```<code>const express = require('express')
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')
const app = express()
const host = process.env.HOST || '0.0.0.0'
const port = 8080
app.set('port', port)
// Import and Set Nuxt.js options
let config = require('../nuxt.config.js')
config.dev = !(process.env.NODE_ENV === 'production')

const Storage = require('@google-cloud/storage')
const dotenv = require('dotenv')

async function getEnv() {
  if (config.dev) {
    dotenv.config({ path: '.env' })
    console.log('Environment local .env file loaded.')
    console.log(process.env.LOCALE)

    return
  }

  try {

    const bucketName = 'env-var'

    const dotEnvSourcePath = `.env`
    const dotEnvDestinationPath = `/tmp/${dotEnvSourcePath}`
    const storage = new Storage({})

    await storage
      .bucket(bucketName)
      .file(dotEnvSourcePath)

      .download({ destination: dotEnvDestinationPath })
    console.log(
      `gs://${bucketName}/${dotEnvSourcePath} downloaded to ${dotEnvDestinationPath}.`
    )

    dotenv.config({ path: dotEnvDestinationPath })

  } catch (err) {
    console.error('ERROR:', err)
  }
}

async function afterEnvProcess() {
  // Init Nuxt.js
  const nuxt = new Nuxt(config)

  // Build only in dev mode
  if (config.dev) {
    const builder = new Builder(nuxt)
    await builder.build()
  }

  // Give nuxt middleware to express
  app.use(nuxt.render)

  // Listen the server
  app.listen(port, host)
  consola.ready({
    message: `Server listening on http://${host}:${port}`,
    badge: true
  })
  const fs = require('fs')

  const dotEnvExists = fs.existsSync('.env')
}

getEnv()
  .then(r => afterEnvProcess())
  .catch(e => console.log(e))
</code>```

I get the values for process.env.<variable> as undefined when running the app in production. When running in development, I get the values correctly. It seems the env variables are not getting passed to the nuxt env property.

EDIT 1:
I can see the correct values in google cloud logs when I console log the env variables with process.env. but at the same time those console log statements show undefined in the browser console

答:
I've created a function that can update module settings from the /server/index.js even in production.

This is only designed to work with the array-style module config syntax. Like this

```<code>['@nuxtjs/google-gtag', { ... }]
</code>```

nuxt.config.js

```<code>// Import and Set Nuxt.js options
const config = require('../nuxt.config.js')
config.dev = process.env.NODE_ENV !== 'production'

function updateConfigModuleSettings(name, settings) {
  const i = config.modules.findIndex(m => Array.isArray(m) && m[0] === name)
  if (i > -1) {
    const oldSettings = config.modules[i][1]
    config.modules[i][1] = {
      ...oldSettings,
      ...settings
    }
  } else {
    throw new RangeError(`Nuxt module named '${name}' could not be found`)
  }
}

// call the function as many times as you like with your module settings overrides
updateConfigModuleSettings('@nuxtjs/google-gtag', {
  id: process.env.GOOGLE_ANALYTICS_ID,
  debug: process.env.NODE_ENV === 'development', // enable to track in dev mode
})

async function start () {
  // this will take the overridden config
  const nuxt = new Nuxt(config)

  // ...
}
start()
</code>```

Body:
nuxt.config.js

modules: [
    '@nuxtjs/dotenv'
  ],

server/index.js

const express = require('express')
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')
const app = express()
const host = process.env.HOST || '0.0.0.0'
const port = 8080
app.set('port', port)
// Import and Set Nuxt.js options
let config = require('../nuxt.config.js')
config.dev = !(process.env.NODE_ENV === 'production')

const Storage = require('@google-cloud/storage')
const dotenv = require('dotenv')

async function getEnv() {
  if (config.dev) {
    dotenv.config({ path: '.env' })
    console.log('Environment local .env file loaded.')
    console.log(process.env.LOCALE)

    return
  }

  try {

    const bucketName = 'env-var'

    const dotEnvSourcePath = `.env`
    const dotEnvDestinationPath = `/tmp/${dotEnvSourcePath}`
    const storage = new Storage({})

    await storage
      .bucket(bucketName)
      .file(dotEnvSourcePath)

      .download({ destination: dotEnvDestinationPath })
    console.log(
      `gs://${bucketName}/${dotEnvSourcePath} downloaded to ${dotEnvDestinationPath}.`
    )

    dotenv.config({ path: dotEnvDestinationPath })

  } catch (err) {
    console.error('ERROR:', err)
  }
}

async function afterEnvProcess() {
  // Init Nuxt.js
  const nuxt = new Nuxt(config)

  // Build only in dev mode
  if (config.dev) {
    const builder = new Builder(nuxt)
    await builder.build()
  }

  // Give nuxt middleware to express
  app.use(nuxt.render)

  // Listen the server
  app.listen(port, host)
  consola.ready({
    message: `Server listening on http://${host}:${port}`,
    badge: true
  })
  const fs = require('fs')

  const dotEnvExists = fs.existsSync('.env')
}

getEnv()
  .then(r => afterEnvProcess())
  .catch(e => console.log(e))

I get the values for process.env.<variable> as undefined when running the app in production. When running in development, I get the values correctly. It seems the env variables are not getting passed to the nuxt env property.

EDIT 1:
I can see the correct values in google cloud logs when I console log the env variables with process.env. but at the same time those console log statements show undefined in the browser console

Body:
I've created a function that can update module settings from the /server/index.js even in production.

This is only designed to work with the array-style module config syntax. Like this

['@nuxtjs/google-gtag', { ... }]

nuxt.config.js

// Import and Set Nuxt.js options
const config = require('../nuxt.config.js')
config.dev = process.env.NODE_ENV !== 'production'

function updateConfigModuleSettings(name, settings) {
  const i = config.modules.findIndex(m => Array.isArray(m) && m[0] === name)
  if (i > -1) {
    const oldSettings = config.modules[i][1]
    config.modules[i][1] = {
      ...oldSettings,
      ...settings
    }
  } else {
    throw new RangeError(`Nuxt module named '${name}' could not be found`)
  }
}

// call the function as many times as you like with your module settings overrides
updateConfigModuleSettings('@nuxtjs/google-gtag', {
  id: process.env.GOOGLE_ANALYTICS_ID,
  debug: process.env.NODE_ENV === 'development', // enable to track in dev mode
})

async function start () {
  // this will take the overridden config
  const nuxt = new Nuxt(config)

  // ...
}
start()


问:
Preventing a
 from wrapping inside of a table
I have a table with two columns. One has some property names and the other has descriptions, including pre tags. I need the pre tags to not wrap and instead scroll to see overflow. I also need the first column to be sized based on the largest property name. I can't get the two to play nicely with each other.

For example I can get the first column to size based on the content but the pre won't scroll:

.main-content {
  max-width: 800px;
  border: 1px solid red;
}
pre {
  overflow: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main-content">
  <table border="0" class="config">
    <thead>
      <tr>
        <th>Property</th>
        <th>Description</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td class="config-name">name</td>
        <td class="config-description">

          <p>Foo bar talking about some random things related to our code here in the paragraph:</p>
          ```// some really long code section here that should have its own scroll bar (and not wrap) some really long code section here that should have its own scroll bar (and not wrap)```
     </td>
    </tr>
    </tbody>
  </table>
</div></code>```

I can also get the pre to scroll but then I can't get the first column to resize:

.main-content {
  max-width: 800px;
  border: 1px solid red;
}
table {
  table-layout: fixed;
  width: 100%;
}
th:first-of-type {
  width: 15%; /* Faking it here - the size of the first td/th should be based on the largest */
}
pre {
  overflow: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main-content">
  <table border="0" class="config">
    <thead>
      <tr>
        <th>Property</th>
        <th>Description</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td class="config-name">name</td>
        <td class="config-description">

          <p>Foo bar talking about some random things related to our code here in the paragraph:</p>
          ```// some really long code section here that should have its own scroll bar (and not wrap) some really long code section here that should have its own scroll bar (and not wrap)```
     </td>
    </tr>
    </tbody>
  </table>
</div></code>```

Any ideas how I can get both working while retaining a table layout? I know how to do it with other methods like grid and flexbox, that's not what I'm asking about.

答:
The only way I can see to do this is to wrap your ```</code> in a <code><div></code> with <code>overflow: auto</code> and set the cell to <code>display: grid</code></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.main-content {
  max-width: 800px;
  border: 1px solid red;
}

table {
  table-layout: auto;
  width: 100%;
}

.config-name {
  white-space: nowrap;
}

.config-description {
  display: grid;
}

.config-description div {
  overflow: auto;
}</code>```

        Property
        Description

        name

Foo bar talking about some random things related to our code here in the paragraph:

            ```// some really long code section here that should have its own scroll bar (and not wrap) some really long code section here that should have its own scroll bar (and not wrap)```

        longer property name

Just another description, this one without a ```</p>
        </td>
      </tr>
    </tbody>
  </table>
</div></code>```

Title: Preventing a <pre> from wrapping inside of a table

Body:
I have a table with two columns. One has some property names and the other has descriptions, including pre tags. I need the pre tags to not wrap and instead scroll to see overflow. I also need the first column to be sized based on the largest property name. I can't get the two to play nicely with each other.

For example I can get the first column to size based on the content but the pre won't scroll:

.main-content {
  max-width: 800px;
  border: 1px solid red;
}
pre {
  overflow: auto;
}

        Property
        Description

        name

Foo bar talking about some random things related to our code here in the paragraph:

// some really long code section here that should have its own scroll bar (and not wrap) some really long code section here that should have its own scroll bar (and not wrap)

I can also get the pre to scroll but then I can't get the first column to resize:

.main-content {
  max-width: 800px;
  border: 1px solid red;
}
table {
  table-layout: fixed;
  width: 100%;
}
th:first-of-type {
  width: 15%; /* Faking it here - the size of the first td/th should be based on the largest */
}
pre {
  overflow: auto;
}

        Property
        Description

        name

Foo bar talking about some random things related to our code here in the paragraph:

// some really long code section here that should have its own scroll bar (and not wrap) some really long code section here that should have its own scroll bar (and not wrap)

Any ideas how I can get both working while retaining a table layout? I know how to do it with other methods like grid and flexbox, that's not what I'm asking about.

Body:
The only way I can see to do this is to wrap your <pre> in a <div> with overflow: auto and set the cell to display: grid

.main-content {
  max-width: 800px;
  border: 1px solid red;
}

table {
  table-layout: auto;
  width: 100%;
}

.config-name {
  white-space: nowrap;
}

.config-description {
  display: grid;
}

.config-description div {
  overflow: auto;
}

<div class="main-content">
  <table border="0" class="config">
    <thead>
      <tr>
        <th>Property</th>
        <th>Description</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td class="config-name">name</td>
        <td class="config-description">

          <p>Foo bar talking about some random things related to our code here in the paragraph:</p>
          <div>
            <pre>// some really long code section here that should have its own scroll bar (and not wrap) some really long code section here that should have its own scroll bar (and not wrap)</pre>
          </div>
        </td>
      </tr>
      <tr>
        <td class="config-name">longer&nbsp;property&nbsp;name</td>
        <td class="config-description">

          <p>Just another description, this one without a &lt;pre&gt;</p>
        </td>
      </tr>
    </tbody>
  </table>
</div>


问:
Grab data from multiple columns and sort by row in Google sheets
I'm trying to sort a google form response sheet with multiple duplicate responses into one set of responses, but still having it associated with the info in the first column. Here is a sheet with the basics of what I want to do.</p>

答:
use:

```<code>=QUERY({A:C; A2:A, D2:E; A2:A, F2:G}, "where Col2 is not null order by Col1", 1)
</code>```

Body:
use:

=QUERY({A:C; A2:A, D2:E; A2:A, F2:G}, "where Col2 is not null order by Col1", 1)


问:
Android send log lines as an email periodically
I want to send the log lines to email in every 10 minutes.

To do that, I have used a Timer and inside of timer I send the logs via email.

However I loose some log lines between 2 emails.

For example my first email contains no lines which is normal according to my algorithm.

My second email contains log lines between 15.37 and 15.38 seconds.

My third email contains logs in between 15.44 and 15.48 time intervals.

My fourth email contains logs in between 15.55 and 15.58 time intervals.

As you can see I loose some of my logs but I could not find a way to avoid that.

Following is my code in my service class:

```<code>@Override
public void onCreate() {
    super.onCreate();

    mTimer = new Timer();

    mTimer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {

            sendLogFile();

        }
    }, 0, 1000 * 60 * 10 );

}
</code>```

Inside of sendSupport method the second parameter is sent as a content of the log lines where logs is a static string variable.

```<code>private void sendLogFile() {

    mInteractor.sendSupport("LOG FILE", "MSG"+logs, "SUBJECT"+ System.currentTimeMillis(), "",

            result -> {

                Timber.log(Log.DEBUG, "sendSupport Thread.currentThread().getName() " + Thread.currentThread().getName());

                if (result.isSuccess) {

                    Timber.d("is sent");

                    writeLogFile();

                } else {

                    Timber.d("is NOT sent");

                }
            }

    );

}

private void writeLogFile()
{

    try {

        StringBuilder logBuilder = new StringBuilder();

        process = Runtime.getRuntime().exec( "logcat -d");

        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(process.getInputStream()));

        String line;

        while ((line = bufferedReader.readLine()) != null) {
            logBuilder.append(line + "\n");
        }

        logs =  logBuilder.toString();

    } catch (IOException e) {
        e.printStackTrace();
    }
}
</code>```

As a result I could not figure out how am I going to be able to get all logs in periodically in my email.

Thanks.

答:
You cannot send an email from the device without user interaction or implementing the email function yourself that allows to do this without user interaction.

Most apps have some api endpoint to send the logs to.

Body:
I want to send the log lines to email in every 10 minutes.

To do that, I have used a Timer and inside of timer I send the logs via email.

However I loose some log lines between 2 emails.

For example my first email contains no lines which is normal according to my algorithm.

My second email contains log lines between 15.37 and 15.38 seconds.

My third email contains logs in between 15.44 and 15.48 time intervals.

My fourth email contains logs in between 15.55 and 15.58 time intervals.

As you can see I loose some of my logs but I could not find a way to avoid that.

Following is my code in my service class:

@Override
public void onCreate() {
    super.onCreate();

    mTimer = new Timer();

    mTimer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {

            sendLogFile();

        }
    }, 0, 1000 * 60 * 10 );

}

Inside of sendSupport method the second parameter is sent as a content of the log lines where logs is a static string variable.

private void sendLogFile() {

    mInteractor.sendSupport("LOG FILE", "MSG"+logs, "SUBJECT"+ System.currentTimeMillis(), "",

            result -> {

                Timber.log(Log.DEBUG, "sendSupport Thread.currentThread().getName() " + Thread.currentThread().getName());

                if (result.isSuccess) {

                    Timber.d("is sent");

                    writeLogFile();

                } else {

                    Timber.d("is NOT sent");

                }
            }

    );

}

private void writeLogFile()
{

    try {

        StringBuilder logBuilder = new StringBuilder();

        process = Runtime.getRuntime().exec( "logcat -d");

        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(process.getInputStream()));

        String line;

        while ((line = bufferedReader.readLine()) != null) {
            logBuilder.append(line + "\n");
        }

        logs =  logBuilder.toString();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

As a result I could not figure out how am I going to be able to get all logs in periodically in my email.

Thanks.


问:
Incomplete Implementation of CTAP2 (FIDO2) protocol in Chrome?
I've been investigating the implementation of CTAP2 protocol with Google Chrome (protocol between Fido Authenticator and Fido Client (e.g. Chrome)), which should be supported in Chrome since version 69.

So I dumped the chrome request to the authenticator in two cases:

1. U2F (CTAP1) with yubico demo website.

Here everything goes as expected and chrome follows the CTAP1 protocol.

2. FIDO2/Webauthn (CTAP2) with webauthn.org

And the browser has a strange behaviour:

It starts by following the CTAP2 protocol by sending a AuthenticatorGetInfoRequest

The Authenticator replies with AuthenticatorGetInfoResponse

But then Chrome switches to the CTAP1 protocol by sending a Registration Request Message (U2F_REGISTER)

Is it a problem with Chrome implementation: CTAP2 is not enabled entirely yet (it seems to be implemented in Chromium sources)?

Or is the problem coming from the authenticator: sending a response that makes Chrome switch to CTAP1?

Or something else entirely?

答:
In AuthenticatorGetInfoRequest, the authenticator must respond with a string list of the supported versions among "U2F_V2" and "FIDO_2_0". Note also in case of NFC or CCID, a "FIDO_2_0" (CTAP2) only authenticator shall anwser directly "FIDO_2_0" on the SELECT command. I don't know about HID and BLE.

So maybe your authenticator is listing "U2F_V2" in the protocol versions list in AuthenticatorGetInfoRequest.

I also imagine the Chrome code base about this was moving fast and can be partial or not strict. To my tests in early 2020, the Chrome CTAP capabilities seem now stable and compliant.


问:
How to retrieve list of all implemented versions of my api?
I'm using aspnet-api-versioning in my WebApi project and it works fine. Versions are not hardcoded, they are retrieved from the namespaces.

Now I would like to retrieve the list of already implemented versions. I want to create some endpoint (let's call it GetApiVersions) that user could call to retrieve a simple collection of existing api version numbers, e.g. [1, 2, 3].

In the code responsible for selecting a correct api version based on the retrieved request (CurrentImplementationApiVersionSelector, SelectVersion method), there is an ApiVersionModel parameter with the ImplementedApiVersions property.

The ImplementedApiVersions property seems to be exactly what I need, but I have no idea how to access it within my GetApiVersions endpoint. Is there a way to retrieve it? Or is there any other way to programmatically retrieve a list of implemented api versions?

答:
I wasn't able to access ImplementedApiVersions property. I had to come up with a workaround. I've created a service (called ApiVersionService) with a static field (List<string> ApiVersions). Service allows to register and read registered versions. As I'm using swagger, I registered all versions in SwaggerConfig.cs file:

```<code>configuration.EnableSwagger(ApiDocConfiguration.RouteTemplate, swagger =>
{
    swagger.MultipleApiVersions(
        (apiDescription, version) => apiDescription.GetGroupName() == version,
        info =>
        {
            foreach (var group in apiExplorer.ApiDescriptions)
            {
                apiVersionService.AddApiVersion(group.Name);
                // some other code
            }
        });
});
</code>```

Simple endpoint allows me to retrieve all versions:

```<code>    [HttpGet]
    [Route("versions")]
    public IHttpActionResult GetVersions()
    {
        // apiVersionService returns the data stored in ApiVersions field
        var versions = apiVersionService.GetApiVersions();
        return Ok(versions);
    }
</code>```

Body:
I wasn't able to access ImplementedApiVersions property. I had to come up with a workaround. I've created a service (called ApiVersionService) with a static field (List<string> ApiVersions). Service allows to register and read registered versions. As I'm using swagger, I registered all versions in SwaggerConfig.cs file:

configuration.EnableSwagger(ApiDocConfiguration.RouteTemplate, swagger =>
{
    swagger.MultipleApiVersions(
        (apiDescription, version) => apiDescription.GetGroupName() == version,
        info =>
        {
            foreach (var group in apiExplorer.ApiDescriptions)
            {
                apiVersionService.AddApiVersion(group.Name);
                // some other code
            }
        });
});

Simple endpoint allows me to retrieve all versions:

    [HttpGet]
    [Route("versions")]
    public IHttpActionResult GetVersions()
    {
        // apiVersionService returns the data stored in ApiVersions field
        var versions = apiVersionService.GetApiVersions();
        return Ok(versions);
    }


问:
Superscripts in WPF window title
I need to be able to superscript TM inside the title window of my page.How can i do that in XAML ?</p>

答:
Here's a link: http://en.wikipedia.org/wiki/Trademark_symbol
Short and sweet, use ALT + 0153 if you're using windows, otherwise you could just try and copy/paste '™'.

Have fun coding!

Title: Superscripts in WPF window title


问:
An empty
 tag is automatically getting inserted, how do I get rid of it?
An empty

 tag is getting inserted automatically when the page is rendered, I'm not sure, how to get rid of it. Which is adding unwanted space on the webpage.

I'm not sure how I can get rid of it. I'm trying to set the margin-bottom for the
 to 0px, even that isn't getting applied as well.

I would be really thankful to anyone who could help me with fixing this issue.

Thanks in advance!

Here is the code which renders the HTML block:
The

 tag gets generated dynamically, but not sure, how it is getting generated from the code.

```<code>{% if job_detail.type != '' and job_detail.type is not None or job_detail.age_limit != '' and job_detail.age_limit is not None %}
     <hr />
     <div class="row">
     {% if job_detail.type != '' and job_detail.type is not None %}
       <div class="col-md-6">
         <h3 class="card-title topic-title">JOB TYPE</h3>
         <p class="card-text topic-text last-child">{{ job_detail.type|linebreaks }}</p>
       </div>
     {% endif %}
     {% if job_detail.age_limit != '' and job_detail.age_limit is not None %}
       <div class="col-md-6 mt-4 mt-sm-4 mt-md-0">
         <h3 class="card-title topic-title">AGE LIMIT</h3>
         <p class="card-text topic-text last-child">{{ job_detail.age_limit|linebreaks }}</p>
       </div>
     {% endif %}
     </div>
   {% endif %}
</code>```

答:
@Shahzan, welcome here, normaly it is the best way to remove the p-tag because you don't need that.
If you have included bootstrap in your webpage you can use an css-classes like "pb-2" to fix the padding on the bottom.

I think your tool generates an p-tag.
Maybe you can tell use more about your setup.

Also you should use some better IDE, maybe some PHPStorm, Atom or Sublime.

```

Title: An empty <p> tag is automatically getting inserted, how do I get rid of it?

Body:
An empty

 tag is getting inserted automatically when the page is rendered, I'm not sure, how to get rid of it. Which is adding unwanted space on the webpage.

I'm not sure how I can get rid of it. I'm trying to set the margin-bottom for the
 to 0px, even that isn't getting applied as well.

I would be really thankful to anyone who could help me with fixing this issue.

Thanks in advance!

Here is the code which renders the HTML block:
The

 tag gets generated dynamically, but not sure, how it is getting generated from the code.

{% if job_detail.type != '' and job_detail.type is not None or job_detail.age_limit != '' and job_detail.age_limit is not None %}

     {% if job_detail.type != '' and job_detail.type is not None %}

JOB TYPE

{{ job_detail.type|linebreaks }}

     {% endif %}
     {% if job_detail.age_limit != '' and job_detail.age_limit is not None %}

AGE LIMIT

{{ job_detail.age_limit|linebreaks }}

     {% endif %}

   {% endif %}

Body:
@Shahzan, welcome here, normaly it is the best way to remove the p-tag because you don't need that.
If you have included bootstrap in your webpage you can use an css-classes like "pb-2" to fix the padding on the bottom.

I think your tool generates an p-tag.
Maybe you can tell use more about your setup.

Also you should use some better IDE, maybe some PHPStorm, Atom or Sublime.

<div class="pb-2"></div>


问:
Incrementing Timestamps
I have a Python script converting multiple csv lists into one xml document with time stamps for each row
I already have the format set as:

```<code>TS = datetime.now().isoformat(timespec='milliseconds')+ "Z"
</code>```

calling TS will give me this time stamp = 2020-02-14T14:30:59.237Z

I need to reuse this variable possibly 100k times or more in my XML document and this creates the exact same time, every time I call the variable. How can I increment the time stamp by 1 millisecond every time it is called in the script??

答:
Maybe use something like this generator?

from datetime import datetime as dt

def getTimestamp():
    timestamp = dt.timestamp(dt.now())
    while True:
        timestamp += 1
        yield dt.fromtimestamp((timestamp)/1000).isoformat(timespec='milliseconds') + "Z"

TS = getTimestamp()

for i in range(10):
    print(next(TS))
```

Title: Incrementing Timestamps

Body:
I have a Python script converting multiple csv lists into one xml document with time stamps for each row
I already have the format set as:

TS = datetime.now().isoformat(timespec='milliseconds')+ "Z"

calling TS will give me this time stamp = 2020-02-14T14:30:59.237Z

I need to reuse this variable possibly 100k times or more in my XML document and this creates the exact same time, every time I call the variable. How can I increment the time stamp by 1 millisecond every time it is called in the script??


问:
Matlab Cross correlation vs Correlation Coefficient question
I'm writing a program in C++ but using data from matlab involving Cross Correlation.
I understand that when I do a correlation on 2 sets of data it gives me a single correlation coefficient number indicating if they are related. But I'm wanting to use Cross Correlation on the data series. When I run Cross Correlation on Matlab it gives me a lot of data and when plotted the plot looks like a triangle... I understand Correlation is supposed to be somewhere between +/- 1 but the data toward the tip of the triangle doesn't go up at the same time etc. Do I have a confusion with what Cross Correlation is giving me or is the data that Cross Correlation gives me actually correlation coefficients for each point s(t),p(t) for instance? Any help with clarifying is appreciated.

Edit 1 (after Phonon's Response)

My main question is: Is the data that I get when I cross correlate 2 data series the correlation coefficient for each point. For instance, (0,10) and (0,8); Is the data I'm getting the correlation coefficient of those 2 plots at x=0 ?

答:
To be clear about several concepts.

Cross-correlation vs. cross-covariance. The main difference is that cross-covariance normalize the data by subtracting the mean.

cross-covariance vs. normalized cross-covariance. The later one is divided by the standard deviation of the the input.

normalized cross-covariance and correlation coefficient. The later one is the special case of the former one at delay=0.


问:
Modify columns with PostgreSQL (beginner)
I would like to transform a database.

I am starting from this…

```<code>    path ; cost; sexe
    42-60 ; 12; male
    42-60; 5; female
    42-61; 3.59; male
    42-62; 13.85; male
    42-62; 2.96; female
</code>```

…and would like to transform it to the following…

```<code>path; male; female
42-60 ; 12; 5;
42-61; 3.59; 0
42-62; 13.85; 2.96
</code>```

I know I have to use array_agg, but I'm not sure how to use it to accomplish this.

答:
```<code>create temporary table test as
select * from (values ('42-60', 12, 'male'),
                      ('42-60', 5, 'female'),
                      ('42-61', 3.59, 'male'),
                      ('42-61', 13.85, 'male'),
                      ('42-62', 2.96, 'female')) as t(path, cost, sex);

select path,
       sum(case sex when 'male' then cost else 0 end) as male,
       sum(case sex when 'female' then cost else 0 end) as female
from test group by path;
</code>```

Is this what you are looking for?

Body:
I would like to transform a database.

I am starting from this…

    path ; cost; sexe
    42-60 ; 12; male
    42-60; 5; female
    42-61; 3.59; male
    42-62; 13.85; male
    42-62; 2.96; female

…and would like to transform it to the following…

path; male; female
42-60 ; 12; 5;
42-61; 3.59; 0
42-62; 13.85; 2.96

I know I have to use array_agg, but I'm not sure how to use it to accomplish this.

Body:
create temporary table test as
select * from (values ('42-60', 12, 'male'),
                      ('42-60', 5, 'female'),
                      ('42-61', 3.59, 'male'),
                      ('42-61', 13.85, 'male'),
                      ('42-62', 2.96, 'female')) as t(path, cost, sex);

select path,
       sum(case sex when 'male' then cost else 0 end) as male,
       sum(case sex when 'female' then cost else 0 end) as female
from test group by path;

Is this what you are looking for?


问:
check if two integers sum to a third
Ok I'm doing this programming assignment and need a little help.

Here is the problem:

Given three ints, a b c, return true if it is possible to add two of the ints to get the third.

```<code>twoAsOne(1, 2, 3) → true
twoAsOne(3, 1, 2) → true
twoAsOne(3, 2, 2) → false
</code>```

Here's the what I have gotten so far:

```<code>public boolean twoAsOne(int a, int b, int c) {
  return a + b != c;
}
</code>```

It keeps saying it is not fully correct and I do not know where I am going wrong.

答:
// start

```<code>public boolean twoAsOne(int a, int b, int c) {

    if (a + b == c) {
        return true;
    }
    else if (a + c == b) {
        return true;
    }
    else if (b + c == a) {
        return true;
    }
    else {
        return false;
    }
}
</code>```

// end

ContentLicense: CC BY-SA 2.5

Title: check if two integers sum to a third

Body:
Ok I'm doing this programming assignment and need a little help.

Here is the problem:

Given three ints, a b c, return true if it is possible to add two of the ints to get the third.

twoAsOne(1, 2, 3) → true
twoAsOne(3, 1, 2) → true
twoAsOne(3, 2, 2) → false

Here's the what I have gotten so far:

public boolean twoAsOne(int a, int b, int c) {
  return a + b != c;
}

It keeps saying it is not fully correct and I do not know where I am going wrong.

Body:
// start

public boolean twoAsOne(int a, int b, int c) {

    if (a + b == c) {
        return true;
    }
    else if (a + c == b) {
        return true;
    }
    else if (b + c == a) {
        return true;
    }
    else {
        return false;
    }
}

// end


问:
How to remove duplicates in an array in python
I'm trying to implement a difference function, which subtracts one list from another and returns the result. Here is what i have so far:

```<code>def array_diff(a, b):
    for e in b[:]:
        for i in a:
            a.remove(i)
    return a

in1 = [1, 2, 2]
in2 = [1]
print(array_diff(in1, in2))
</code>```

I have two sample tests that i'd like to run.

```<code>Test.assert_equals(array_diff([1,2,2], [1]), [2,2], "a was [1,2,2], b was [1], expected [2,2]")
Test.assert_equals(array_diff([1,2,2], [2]), [1], "a was [1,2,2], b was [2], expected [1]")
</code>```

How would i be able to remove the same value more than once?

答:
```<code>array_diff = lambda a, b: [ i for i in a if i not in b]

array_diff(in1,[1])
 [2, 2]

array_diff(in1,[2])
 [1]
</code>```

Body:
I'm trying to implement a difference function, which subtracts one list from another and returns the result. Here is what i have so far:

def array_diff(a, b):
    for e in b[:]:
        for i in a:
            a.remove(i)
    return a

in1 = [1, 2, 2]
in2 = [1]
print(array_diff(in1, in2))

I have two sample tests that i'd like to run.

Test.assert_equals(array_diff([1,2,2], [1]), [2,2], "a was [1,2,2], b was [1], expected [2,2]")
Test.assert_equals(array_diff([1,2,2], [2]), [1], "a was [1,2,2], b was [2], expected [1]")

How would i be able to remove the same value more than once?