问:
Prevent refresh from reloading data without redirecting to new page
I have a single page comment php web page that writes comments to a file. But on refresh it keeps reposting last comments. How do code it to only write to the file only if submit button pressed. Thank you.</p>

```<code><?php
    /*if($_POST)*/
    if(isset($_POST['submit_btn'])) {
        $name = $_POST['name'];
        $comment = $_POST['comment'];
        $handle = fopen("comments.php", "a");

        fwrite($handle, "<div><b><i>" . $name . "</b></i> update:<br>" . $comment . "<br></div><br>" );
        fclose($handle);
    }
?>

<!DOCTYPE html>
<html>
    <head>
        <title>Rolling Log</title>
        <meta charset="uft-8">
    </head>
    <style>
        body {
          background-color: grey;
        }

        #top,#bottom {
          margin: 0 auto;
          width: 50%;
          padding: 5px;
        }

        div {
          border: 1px solid black;
          background-color: white;
        }
    </style>

    <body>
        <div id="top">
            <h1>Post a change mgmt comment</h1>

            <form action="" method="POST">
                Name: <br /> <input type="text" name="name"> <br />
                Comment: <br /> <textarea rows="5" cols="70" name="comment"></textarea> <br /><br />
                <input type="submit" name="submit_btn" value="Post comment">
            </form>
        </div>
        <br>

        <div id="bottom">
            <h1>Other CM Comments</h1>
            <?php include "comments.php"; ?>
        </div>
    </body>
</html>
</code>```

答:
Use the header refresh function : header("Refresh:0");

This is because when you send a request to the same page, the headers won't change (and will keep the current request to add data in your file) if you don't force them with the header function.

```<code> /*if($_POST)*/
    if(isset($_POST['submit_btn']))
    {
        $name = $_POST['name'];
        $comment = $_POST['comment'];
        $handle = fopen("comments.php", "a");
        fwrite($handle, "<div><b><i>" . $name . "</b></i> update:<br>" . $comment . "<br></div><br>" );
        fclose($handle);
        header("Refresh:0");
    }
</code>```

Body:
I have a single page comment php web page that writes comments to a file. But on refresh it keeps reposting last comments. How do code it to only write to the file only if submit button pressed. Thank you.

<?php
    /*if($_POST)*/
    if(isset($_POST['submit_btn'])) {
        $name = $_POST['name'];
        $comment = $_POST['comment'];
        $handle = fopen("comments.php", "a");

        fwrite($handle, "
" . $name . " update:
" . $comment . "

" );
        fclose($handle);
    }
?>

<!DOCTYPE html>

        <title>Rolling Log</title>
        <meta charset="uft-8">

Post a change mgmt comment

            <form action="" method="POST">
                Name:
 <input type="text" name="name">

                Comment:
 <textarea rows="5" cols="70" name="comment"></textarea>

                <input type="submit" name="submit_btn" value="Post comment">
            </form>

Other CM Comments

            <?php include "comments.php"; ?>

Body:
Use the header refresh function : header("Refresh:0");

This is because when you send a request to the same page, the headers won't change (and will keep the current request to add data in your file) if you don't force them with the header function.

 /*if($_POST)*/
    if(isset($_POST['submit_btn']))
    {
        $name = $_POST['name'];
        $comment = $_POST['comment'];
        $handle = fopen("comments.php", "a");
        fwrite($handle, "<div><b><i>" . $name . "</b></i> update:<br>" . $comment . "<br></div><br>" );
        fclose($handle);
        header("Refresh:0");
    }


来源: stackexchange

问:
Is the memory space of a .NET process secure when compiled in release mode?
Is the memory space of a .NET process secure when the binary was compiled in release mode?

Let's say I generate some random string and it is long lived (not GC'd).

Could someone with access to the OS and the process dump the process's memory and retrieve my randomly generated string - could they perhaps still connect the debugger, interrupt execution and dump some data I would rather not leak out?

Assuming the above is true, is there a compilation flag one can use to safeguard against what I've described?

答: Yes your strings are retrievable and no there is no magic switch. What's the use case?</p>

ContentLicense: CC BY-SA 4.0


问:
C++ / GoogleTest - How to run Setup for each test in a link directory
I am trying to capture the stdout at the start of each individual test, and if the test fails, only then print the stdout. I need this to run for each TEST and TEST_F in a directory so I am looking if I can apply a global test fixture if possible to the main.

I can apply a global environment but this runs at the setup and tear down of the test runner. And I can get this working by adding the code to each of my many standard test fixtures but I was hoping for a global solution rather than changing each fixture.

struct dummyFixture : public ::testing::Test
{
    // --- Need to apply this globally ---
    void SetUp()
    {
        backup = std::cout.rdbuf();
        std::cout.rdbuf(testingSink.rdbuf());
    }
    void TearDown()
    {
        std::cout.rdbuf(backup);
        if (::testing::Test::HasFailure())
            std::cout << testingSink.str() << std::endl;
        testingSink.str(std::string());
    }
    private:
        std::stringstream testingSink;
        std::streambuf *backup;
};

TEST(dummyTest, test_pass)
{
    // should not print log to console
    std::cout << "DUMMY TEST" << std::endl;
    EXPECT_TRUE(true);
}
TEST_F(dummyFixture, test_fail)
{
    // should print log to console
    std::cout << "DUMMY TEST FIXTURE" << std::endl;
    EXPECT_TRUE(false);
}

int main(int argc, char **argv)
{
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
```

答:
Since you don't want to modify any of the text fixtures and you want to run this just like the SetUp() & TearDown() of the test fixture, you can try with below approach.

```<code>class Logger
{
 Logger()
    {
        backup = std::cout.rdbuf();
        std::cout.rdbuf(testingSink.rdbuf());
    }
    ~Logger()
    {
        std::cout.rdbuf(backup);
        if (::testing::Test::HasFailure())
            std::cout << testingSink.str() << std::endl;
        testingSink.str(std::string());
    }
    private:
        std::stringstream testingSink;
        std::streambuf *backup;
};
</code>```

You can now derive all of your test classes(deriving from ::testing::test) from this Logger class.

```<code>struct dummyFixture : public ::testing::Test, **public Logger**
{
};
</code>```

GTest also has methods CaptureStdout() & GetCapturedStdout() to get the captured stdout string, you can use them as well.

This will make sure that you achieve what you are trying to do with minimal code changes.

Body:
Since you don't want to modify any of the text fixtures and you want to run this just like the SetUp() & TearDown() of the test fixture, you can try with below approach.

class Logger
{
 Logger()
    {
        backup = std::cout.rdbuf();
        std::cout.rdbuf(testingSink.rdbuf());
    }
    ~Logger()
    {
        std::cout.rdbuf(backup);
        if (::testing::Test::HasFailure())
            std::cout << testingSink.str() << std::endl;
        testingSink.str(std::string());
    }
    private:
        std::stringstream testingSink;
        std::streambuf *backup;
};

You can now derive all of your test classes(deriving from ::testing::test) from this Logger class.

struct dummyFixture : public ::testing::Test, **public Logger**
{
};

GTest also has methods CaptureStdout() & GetCapturedStdout() to get the captured stdout string, you can use them as well.

This will make sure that you achieve what you are trying to do with minimal code changes.


问:
How can I do to execute some functions using Django?
Hello I have a Django project but I can't achieve to execute some functions. I precise I have a file in my app by the name of file2.py and I tried this :

```<code>import file2
</code>```

And I got this :

```<code>No module named 'file2'
</code>```

Could you help me please ?

Thank you.

答:
If you have this file in the same directory, you can access it's functions like this:
from .file2 import function

The dot is important, since it clarifies the path to the file

For example: you have defined some foo_form in your forms.py and you want to use it in your views.py, which is in the same directory as forms.py, your views.py should look like this:

from .forms import foo_form

def foo(request):

    form = foo_form()
```

If the file you want to import is in different directory though, you may want to check this question: Importing files from different folder

Body:
Hello I have a Django project but I can't achieve to execute some functions. I precise I have a file in my app by the name of file2.py and I tried this :

import file2

And I got this :

No module named 'file2'

Could you help me please ?

Thank you.

Body:
If you have this file in the same directory, you can access it's functions like this:
from .file2 import function

The dot is important, since it clarifies the path to the file

For example: you have defined some foo_form in your forms.py and you want to use it in your views.py, which is in the same directory as forms.py, your views.py should look like this:

from .forms import foo_form

def foo(request):

    form = foo_form()

If the file you want to import is in different directory though, you may want to check this question: Importing files from different folder


问:
Loop through rows and assign value based on condition
I have dates for each row in my dataframe and want to assign a value to a new column based on a condition of the date.

Normally if I assign a value to a new column, I would do something like this:

```<code>def get_mean(df):
   return df.assign(
     grouped_mean = lambda df: df.groupby('group')['X']
       .transform(lambda df: df.mean())
   )
</code>```

No I am looking for a solution like that, since the solution I have now is very slow and not beautiful.

Is there a better way than my current solution and use assign?

I currently came up with this solution:

```<code>def set_season(df):
    df = df.copy()
    for i in df.index:
        if (df.loc[i, 'Date'] >= pd.Timestamp('2008-08-30')) & (df.loc[i, 'Date'] <= pd.Timestamp('2009-05-31')):
            df.at[i, 'season'] = '08-09'
        elif  (df.loc[i, 'Date'] >= pd.Timestamp('2009-08-22')) & (df.loc[i, 'Date'] <= pd.Timestamp('2010-05-16')):
            df.at[i, 'season'] = '09-10'
        elif  (df.loc[i, 'Date'] >= pd.Timestamp('2010-08-28')) & (df.loc[i, 'Date'] <= pd.Timestamp('2011-05-22')):
            df.at[i, 'season'] = '10-11'

    return df
</code>```

答:
Use .apply() method, if the new column 'season' depends only on one column:

```<code>def your_function(date):
    """
    takes a date a returns a string season
    """
    # code your function here

df['season'] = df['Date'].apply(your_function)
</code>```

if your new column 'season' depends on multiple other columns, use axis = 1:

```<code>def your_function(row):
    """
    takes a row from your dataframe and returns a result
    """
    # code your function here
    # example if you want a sum of col1, col2, col3
    return row['col1'] + row['col2'] + row['col3']

df['season'] = df.apply(your_function, axis = 1)
</code>```

Body:
I have dates for each row in my dataframe and want to assign a value to a new column based on a condition of the date.

Normally if I assign a value to a new column, I would do something like this:

def get_mean(df):
   return df.assign(
     grouped_mean = lambda df: df.groupby('group')['X']
       .transform(lambda df: df.mean())
   )

No I am looking for a solution like that, since the solution I have now is very slow and not beautiful.

Is there a better way than my current solution and use assign?

I currently came up with this solution:

def set_season(df):
    df = df.copy()
    for i in df.index:
        if (df.loc[i, 'Date'] >= pd.Timestamp('2008-08-30')) & (df.loc[i, 'Date'] <= pd.Timestamp('2009-05-31')):
            df.at[i, 'season'] = '08-09'
        elif  (df.loc[i, 'Date'] >= pd.Timestamp('2009-08-22')) & (df.loc[i, 'Date'] <= pd.Timestamp('2010-05-16')):
            df.at[i, 'season'] = '09-10'
        elif  (df.loc[i, 'Date'] >= pd.Timestamp('2010-08-28')) & (df.loc[i, 'Date'] <= pd.Timestamp('2011-05-22')):
            df.at[i, 'season'] = '10-11'

    return df

Body:
Use .apply() method, if the new column 'season' depends only on one column:

def your_function(date):
    """
    takes a date a returns a string season
    """
    # code your function here

df['season'] = df['Date'].apply(your_function)

if your new column 'season' depends on multiple other columns, use axis = 1:

def your_function(row):
    """
    takes a row from your dataframe and returns a result
    """
    # code your function here
    # example if you want a sum of col1, col2, col3
    return row['col1'] + row['col2'] + row['col3']

df['season'] = df.apply(your_function, axis = 1)


问:
How to have a different .gitignore for each branch (or an alternative solution)?
I have the following setup:

origin/master                               origin/my-branch

-----------------              ----------------------

test.txt

       |                                           |

       |                                           |

       |                                           |

local/master                   local/my-branch

-----------------              ----------------------

test.txt                       test.txt

The idea is that I need to have different test.txt files on each branch, consider them like config files. test.txt needs to be however, on origin/master, in case someone else wants to clone the project, to have a default working config.
 I want to have my test.txt file (modified with my own configurations) and I also don't want to push it to remote on my-branch because I would later on merge it into master, and my configurations would override the default test.txt.

How can I achieve this? I was thinking of using 2 different .gitignore for each branch, but modifying .gitignore on one branch, modifies it on the other. Also, because test.txt on local/my-branch is not committed to remote, every time I checkout to master and checkout back, the file is deleted.

答:
To solve this you need one config file which is checked in, and a second config file which is ignored. The first contains the default configuration. The second contains your local modifications which override the defaults. How you accomplish this depends on your project.

Here's a simple example in Ruby using YAML config files.

```<code>config = YAML.load_file('config.yml')
local_config = YAML.load_file('local_config.yml')
config.merge!( local_config )
</code>```

This is beneficial not just for development but for your users as well. They can keep the default config file pristine allowing it to be cleanly updated when new versions become available. Their local changes go into the local config file.

Body:
To solve this you need one config file which is checked in, and a second config file which is ignored. The first contains the default configuration. The second contains your local modifications which override the defaults. How you accomplish this depends on your project.

Here's a simple example in Ruby using YAML config files.

config = YAML.load_file('config.yml')
local_config = YAML.load_file('local_config.yml')
config.merge!( local_config )

This is beneficial not just for development but for your users as well. They can keep the default config file pristine allowing it to be cleanly updated when new versions become available. Their local changes go into the local config file.


问:
Problem adding values stored as variables to a java list
I am going to create a list that I want to add elements to.  I have obtained the elements from clients via them completing 3 dialogue boxes indicating their preferences for a new car, and now I want to add these entries to the list.

I have declared my instance variables and here is the constructor for my list:

```<code> public Car(String aMaker, String aModel, int aYearBuilt);
    {
        super();
        this.maker = aMaker;
        this.model = aModel;
        this.year = aYearBuilt;
    }
</code>```

I have successfully put the return from my first client's dialogue boxes into 3 variables, created thus:

```<code> String inputMaker;
 String inputModel;
 int inputYear;
</code>```

(I remembered to use Integer.parseInt to convert the dialogue input string to an int).

Now I want to put the values in a list:

```<code>List<Car> newCarDetails = new ArrayList<Car>();
</code>```

This is where I start to go wrong:

```<code> newCarDetails.add(new Car(inputMaker, inputModel, inputYear));
    return newCarDetails;
</code>```

Only I have clearly underestimated the task, because it doesn't work.  I just get a hashCode back.  Any help greatly appreciated.

答:
Your code looks fine to me. You're adding the new Car to a List<Car> that you've previously created. If by "hash code" you mean that when you do System.out.println(newCarDetails) you get some output like <java.util.List<0x123456>> that's just what happens when you try to print any class that doesn't have a toString() method. A lot of the Collections framework classes don't.

If you want to pretty-print it, try the technique here.

ContentLicense: CC BY-SA 3.0

Body:
I am going to create a list that I want to add elements to.  I have obtained the elements from clients via them completing 3 dialogue boxes indicating their preferences for a new car, and now I want to add these entries to the list.

I have declared my instance variables and here is the constructor for my list:

 public Car(String aMaker, String aModel, int aYearBuilt);
    {
        super();
        this.maker = aMaker;
        this.model = aModel;
        this.year = aYearBuilt;
    }

I have successfully put the return from my first client's dialogue boxes into 3 variables, created thus:

 String inputMaker;
 String inputModel;
 int inputYear;

(I remembered to use Integer.parseInt to convert the dialogue input string to an int).

Now I want to put the values in a list:

List<Car> newCarDetails = new ArrayList<Car>();

This is where I start to go wrong:

 newCarDetails.add(new Car(inputMaker, inputModel, inputYear));
    return newCarDetails;

Only I have clearly underestimated the task, because it doesn't work.  I just get a hashCode back.  Any help greatly appreciated.


问:
Detect Windows font size (100%, 125%, and 150%)
I created an application that works perfectly until the user selects 125% or 150%. It would break my application. I later found a way to find the font size by detecting the DPI.

This was working great until people with Chinese versions of Windows 7 started using my application. The entire application breaks on Chinese Windows 7. From what I can tell (I can't really test it for I only have the English version and installation the language packs does not cause the problem) Chinese characters are causing a weird DPI that breaks my application.

My current code works like this:

```<code>if (dpi.DpiX == 120) // For 125% fonts
{
    // Resize form and set default font to correct problems
}
else if (dpi.DpiX == 96) // For 100 and 150% fonts
{
    // Resize form and set default font to correct problems
}
</code>```

On English versions of Windows 7 that works great, but somehow Chinese versions skip right by this, and the form destroys itself, with controls not even showing up, font extremely large and pushing past the problem, picture boxes being moved around.

So what is a good way to detect the Windows font scale (100%, 125%, and 150%) without detecting DPI? I need something solid that will work on all Windows 7 operating systems and languages.

答:
if your on a newer version of windows I recommend reinstalling your graphics card drivers ( e.g installing a newer version) I had the same problem, my display scale was set to 100% but the font was way off.
hope this fixes your problem</p>

Body:
I created an application that works perfectly until the user selects 125% or 150%. It would break my application. I later found a way to find the font size by detecting the DPI.

This was working great until people with Chinese versions of Windows 7 started using my application. The entire application breaks on Chinese Windows 7. From what I can tell (I can't really test it for I only have the English version and installation the language packs does not cause the problem) Chinese characters are causing a weird DPI that breaks my application.

My current code works like this:

if (dpi.DpiX == 120) // For 125% fonts
{
    // Resize form and set default font to correct problems
}
else if (dpi.DpiX == 96) // For 100 and 150% fonts
{
    // Resize form and set default font to correct problems
}

On English versions of Windows 7 that works great, but somehow Chinese versions skip right by this, and the form destroys itself, with controls not even showing up, font extremely large and pushing past the problem, picture boxes being moved around.

So what is a good way to detect the Windows font scale (100%, 125%, and 150%) without detecting DPI? I need something solid that will work on all Windows 7 operating systems and languages.


问:
Checkbox value is always empty even if i check it
I made a button to delete files from a database, to delete a file you need to check a checkbox and then click a button. somewhy when i click the button and write the checkbox value to the html it always says false...

ASPX:

<asp:GridView HorizontalAlign="Center" ID="GridView1" runat="server" class="" AutoGenerateColumns="False" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Horizontal" DataKeyNames="ID">
    <Columns>
        <asp:TemplateField HeaderText="Name">< ItemTemplate >
                            < asp:LinkButton ID = "LinkButton2" runat="server" OnClick="OpenDocument" Text='<%# Eval("File_Name") %>'></asp:LinkButton>
                        </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Delete?">< ItemTemplate >
                            < asp:CheckBox ID = "CheckBox1" runat="server" />
                        </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
<asp:Button runat="server" Text="Update" ID="Update" class="button" OnClick="UpdateTable" Style="font-size: 20px" />
```

<p>Code Behind:</p>

<pre class="lang-cs prettyprint-override"><code>protected void UpdateTable(object sender, EventArgs e)
{
    foreach (GridViewRow item in GridView1.Rows)
    {
        CheckBox chk = (CheckBox)item.FindControl("CheckBox1");
        if (chk != null)
        {
            //This is being written and always false
            Response.Write(chk.Checked);
            if (chk.Checked)
            {
               //Delete the item. (never being executed)
            }
        }
    }
}
</code>```

I expected chk.Checked to be True since i've clicked it...

答:
If you are binding your grid in Page_Load, Make sure you are not binding your grid outside of if(!IsPostBack){}. Otherwise you'll loose the checkboxes on each postback and so losing the status of checkboxes.</p>

```<code>protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
    {
       //Bind Your Grid Here
    }
}
</code>```

Body:
I made a button to delete files from a database, to delete a file you need to check a checkbox and then click a button. somewhy when i click the button and write the checkbox value to the html it always says false...

ASPX:

<asp:GridView HorizontalAlign="Center" ID="GridView1" runat="server" class="" AutoGenerateColumns="False" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Horizontal" DataKeyNames="ID">
    <Columns>
        <asp:TemplateField HeaderText="Name">< ItemTemplate >
                            < asp:LinkButton ID = "LinkButton2" runat="server" OnClick="OpenDocument" Text='<%# Eval("File_Name") %>'></asp:LinkButton>
                        </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Delete?">< ItemTemplate >
                            < asp:CheckBox ID = "CheckBox1" runat="server" />
                        </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
<asp:Button runat="server" Text="Update" ID="Update" class="button" OnClick="UpdateTable" Style="font-size: 20px" />

Code Behind:

protected void UpdateTable(object sender, EventArgs e)
{
    foreach (GridViewRow item in GridView1.Rows)
    {
        CheckBox chk = (CheckBox)item.FindControl("CheckBox1");
        if (chk != null)
        {
            //This is being written and always false
            Response.Write(chk.Checked);
            if (chk.Checked)
            {
               //Delete the item. (never being executed)
            }
        }
    }
}

I expected chk.Checked to be True since i've clicked it...

Body:
If you are binding your grid in Page_Load, Make sure you are not binding your grid outside of if(!IsPostBack){}. Otherwise you'll loose the checkboxes on each postback and so losing the status of checkboxes.

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
    {
       //Bind Your Grid Here
    }
}


问:
Incompatible types firebase database and database reference
Screenshot of the code

I've tried to use FireBaseDatabase to store data and I've import the FirebaseDatabase function, but it keep saying that it's an incompactible types

```<code>Required: com.google.firebase.database.FirebaseDatabase
Found: com.google.firebase.database.DatabaseReference
</code>```

I'm really confuse that where is the mistake?

答:
You haven't import the DatabaseReference. You have used private FirebaseDatabase UsersRef which cause the error, use this :

private DatabaseReference UsersRef;
```

<p>After that,</p>

<pre class="lang-cs prettyprint-override"><code>UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
</code>```

Body:
Screenshot of the code

I've tried to use FireBaseDatabase to store data and I've import the FirebaseDatabase function, but it keep saying that it's an incompactible types

Required: com.google.firebase.database.FirebaseDatabase
Found: com.google.firebase.database.DatabaseReference

I'm really confuse that where is the mistake?

Body:
You haven't import the DatabaseReference. You have used private FirebaseDatabase UsersRef which cause the error, use this :

private DatabaseReference UsersRef;

After that,

UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");


问:
querySelectorAll() match all h1's except from a div
I want to match all h1's on the document except from a div containing other h1's, currently i can do querySelectorAll('h1:not(.demo)) to get all h1's with except h1's with demo class.

But how can i do querySelectorAll('h1:not(div#demo)) or similar thing?

Below is a sample html

First

Second

Third

Fourth

```

答:
You can quite select the child headings from the divs with >h1

let h1 = document.querySelectorAll('div:not(#demo)>h1');

console.log(h1);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div><h1>First</h1> <h1>Second</h1></div>
<div id="demo"><h1 class="demo">Third (demo)</h1></div>
<div><h1>Fourth</h1></div></code>```

Body:
You can quite select the child headings from the divs with >h1

let h1 = document.querySelectorAll('div:not(#demo)>h1');

console.log(h1);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div><h1>First</h1> <h1>Second</h1></div>
<div id="demo"><h1 class="demo">Third (demo)</h1></div>
<div><h1>Fourth</h1></div>


问:
Finding minimal jump zero crossings in numpy
For a data analysis task, I want to find zero crossings in a numpy array, coming from a convolution with first a sobel-like kernel, and then a mexican hat kernel. Zero crossings allow me to detect edges in the data.

Unfortunately, the data is somewhat noisy and I only want to find zero crossings with a minimal jump size, 20 in the follwing example:

```<code>import numpy as np
arr = np.array([12, 15, 9, 8, -1, 1, -12, -10, 10])
</code>```

Should result in

```<code>>>>array([1, 3, 7])
</code>```

or

```<code>>>>array([3, 7])
</code>```

Where 3 is the index of -1, just before the middle of the first jump and 7 is the index of -10

I have tried a modification of the following code (source: Efficiently detect sign-changes in python)

```<code>zero_crossings = np.where(np.diff(np.sign(np.trunc(arr/10))))[0]
</code>```

Which correctly ignores small jumps, but puts the zero-crossings at [1,5,7]

What would be an efficient way of doing this?

The definition of minimal jump is not strict, but results should be along the lines of my question.

Edit: For Clarification

```<code>arr = np.array([12, 15, 9, 8, -1, 1, -12, -10, 10])
arr_floored = np.trunc(arr/10)
>>>>np.array([10, 10, 0, 0, 0, 0, -10, -10, 10])
sgn = np.sign(arr_floored)
>>>>array([ 1,  1,  0,  0,  0,  0, -1, -1,  1])
dsgn = np.diff(sgn)
>>>>array([ 0, -1,  0,  0,  0, -1,  0,  2])
np.where(dsgn)
>>>>(array([1, 5, 7], dtype=int64),)
</code>```

Further edgecases:

```<code>arr = [10,9,8,7,6,5,4,3,2,1,0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10]
</code>```

Should result in

```<code>>>> np.array([10])
</code>```

Also just noticed: The problem might be ill-posed(in a mathematical sense). I will clarify it later today.

答:
Here's a solution that gives the midpoint of crossings involving a noise threshold to filter potentially multiple fluctuations around zero applied across multiple data points.  It give the correct answers for the two examples you supplied.
However, I've made a couple of assumptions:

You didn't define precisely what range of data points to consider to determine the midpoint of the crossing, but I've used your sample code as a basis - it was detecting crossings where ABS(start | end) >= 10 hence I've used the minimum range where this condition holds.

NB: This does not detect a transition from +15 to -6.

EDIT: Actually it's not always the minimum range, but the code should be enough for you to get started and adjust as needed.

I've assumed that it is ok to also use pandas (to track the indexes of data points of interest).  You could probably avoid pandas if essential.

import numpy as np
import pandas as pd
arr = np.array([12, 15, 9, 8, -1, 1, -12, -10, 10])
sgn = pd.Series(np.sign(np.trunc(arr/10)))
trailingEdge = sgn[sgn!=0].diff()
edgeIndex = np.array(trailingEdge[trailingEdge!=0].index)
edgeIndex[:-1] + np.diff(edgeIndex) / 2

gives:

array([3., 7.])

and

arr = [10,9,8,7,6,5,4,3,2,1,0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10]

gives:

array([10.])

Body:
For a data analysis task, I want to find zero crossings in a numpy array, coming from a convolution with first a sobel-like kernel, and then a mexican hat kernel. Zero crossings allow me to detect edges in the data.

Unfortunately, the data is somewhat noisy and I only want to find zero crossings with a minimal jump size, 20 in the follwing example:

import numpy as np
arr = np.array([12, 15, 9, 8, -1, 1, -12, -10, 10])

Should result in

>>>array([1, 3, 7])

or

>>>array([3, 7])

Where 3 is the index of -1, just before the middle of the first jump and 7 is the index of -10

I have tried a modification of the following code (source: Efficiently detect sign-changes in python)

zero_crossings = np.where(np.diff(np.sign(np.trunc(arr/10))))[0]

Which correctly ignores small jumps, but puts the zero-crossings at [1,5,7]

What would be an efficient way of doing this?

The definition of minimal jump is not strict, but results should be along the lines of my question.

Edit: For Clarification

arr = np.array([12, 15, 9, 8, -1, 1, -12, -10, 10])
arr_floored = np.trunc(arr/10)
>>>>np.array([10, 10, 0, 0, 0, 0, -10, -10, 10])
sgn = np.sign(arr_floored)
>>>>array([ 1,  1,  0,  0,  0,  0, -1, -1,  1])
dsgn = np.diff(sgn)
>>>>array([ 0, -1,  0,  0,  0, -1,  0,  2])
np.where(dsgn)
>>>>(array([1, 5, 7], dtype=int64),)

Further edgecases:

arr = [10,9,8,7,6,5,4,3,2,1,0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10]

Should result in

>>> np.array([10])

Also just noticed: The problem might be ill-posed(in a mathematical sense). I will clarify it later today.


问:
msbuild unable to find files in my Assets folder
I am trying to build my first uwp application. I am new to c# as well. I am using visual studio build tools 2019. I think I have done everything right but when I run msbuild, I get the following error:

```<code>"C:\Projects\C\UapHello\uaphello.csproj" (default target) (1) ->
</code>```

(_ValidateAppxPackage target) ->
  Package.appxmanifest(41,9): error APPX0703: Manifest references file 'Assets\Square150x150Logo.png' which is not part
 of the payload. [C:\Projects\C\UapHello\uaphello.csproj]
  Package.appxmanifest(42,9): error APPX0703: Manifest references file 'Assets\Square44x44Logo.png' which is not part o
f the payload. [C:\Projects\C\UapHello\uaphello.csproj]
  Package.appxmanifest(27,6): error APPX0703: Manifest references file 'StoreLogo.png' which is not part of the payload
. [C:\Projects\C\UapHello\uaphello.csproj]
  Package.appxmanifest(45,27): error APPX0703: Manifest references file 'Assets\SplashScreen.png' which is not part of
the payload. [C:\Projects\C\UapHello\uaphello.csproj]

I am pretty sure these files exist in said folder.
I am including my csproj and appmanifest:

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

<Package
  xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
  xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
  xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
  xmlns:uap5="http://schemas.microsoft.com/appx/manifest/uap/windows10/5"
  xmlns:desktop4="http://schemas.microsoft.com/appx/manifest/desktop/windows10/4"
  xmlns:iot2="http://schemas.microsoft.com/appx/manifest/iot/windows10/2"
  IgnorableNamespaces="uap mp uap5 iot2 desktop4">

  <Identity
    Name="IggyMakesThings"
    Publisher="CN=IggyMakesThings, O=IggyMakesThings, L=Redmond, S=Washington, C=US"
    Version="1.0.0.0" />

  <mp:PhoneIdentity PhoneProductId="11a54d62-0d60-4e17-820d-1fa537715b3a" PhonePublisherId="00000000-0000-0000-0000-000000000000"/>

    <Dependencies>
    <TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.17763.0" MaxVersionTested="10.0.17763.0" />
  </Dependencies>

  <Properties>
    <DisplayName>uaphello</DisplayName>
    <PublisherDisplayName>IggyMakesThings</PublisherDisplayName>
    <Logo>StoreLogo.png</Logo>
  </Properties>

  <Resources>
    <Resource Language="x-generate"/>
  </Resources>

  <Applications>
    <Application Id="App"
      Executable="uaphello.exe"
      EntryPoint="UAPHello.App">
      <uap:VisualElements
        DisplayName="UAPSample"
        Square150x150Logo="Assets\Square150x150Logo.png"
        Square44x44Logo="Assets\Square44x44Logo.png"
        Description="UAP C# Sample"
        BackgroundColor="#000000">
        <uap:SplashScreen Image="Assets\SplashScreen.png" />
        <uap:DefaultTile>
          <uap:ShowNameOnTiles>
            <uap:ShowOn Tile="square150x150Logo" />
          </uap:ShowNameOnTiles>
        </uap:DefaultTile>
      </uap:VisualElements>
    </Application>
  </Applications>

</Package>
</code>```

And csproj:

```<code><?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />

  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">Win32</Platform>
    <ProjectGuid>{$guid1$}</ProjectGuid>
    <OutputType>AppContainerExe</OutputType>
    <RootNamespace>uaphello</RootNamespace>
    <DefaultLanguage>en-US</DefaultLanguage>
    <TargetPlatformIdentifier>UAP</TargetPlatformIdentifier>
    <TargetPlatformVersion>10.0.17763.0</TargetPlatformVersion>
    <TargetPlatformMinVersion>10.0.17763.0</TargetPlatformMinVersion>
    <EnableDotNetNativeCompatibleProfile>true</EnableDotNetNativeCompatibleProfile>
  </PropertyGroup>

  <PropertyGroup>
    <OutputPath>bin\$(Platform)\$(Configuration)\</OutputPath>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
    <PlatformTarget>x64</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
    <NoWarn>;2008</NoWarn>
    <DebugType>full</DebugType>
    <UseVSHostingProcess>false</UseVSHostingProcess>
    <ErrorReport>prompt</ErrorReport>
    <Prefer32Bit>true</Prefer32Bit>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
    <PlatformTarget>x64</PlatformTarget>
    <DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
    <Optimize>true</Optimize>
    <NoWarn>;2008</NoWarn>
    <DebugType>pdbonly</DebugType>
    <UseVSHostingProcess>false</UseVSHostingProcess>
    <ErrorReport>prompt</ErrorReport>
    <Prefer32Bit>true</Prefer32Bit>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|Win32'">
    <PlatformTarget>x86</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
    <NoWarn>;2008</NoWarn>
    <DebugType>full</DebugType>
    <UseVSHostingProcess>false</UseVSHostingProcess>
    <ErrorReport>prompt</ErrorReport>
    <Prefer32Bit>true</Prefer32Bit>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|Win32'">
    <PlatformTarget>x86</PlatformTarget>
    <DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
    <Optimize>true</Optimize>
    <NoWarn>;2008</NoWarn>
    <DebugType>pdbonly</DebugType>
    <UseVSHostingProcess>false</UseVSHostingProcess>
    <ErrorReport>prompt</ErrorReport>
    <Prefer32Bit>true</Prefer32Bit>
  </PropertyGroup>

  <ItemGroup>
    <Compile Include="Program.cs" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.NETCore.UniversalWindowsPlatform" Version="6.2.8" />
  </ItemGroup>

  <ItemGroup>
   <AppxManifest Include="Package.appxmanifest">
     <SubType>Designer</SubType>
   </AppxManifest>
  </ItemGroup>

   <Import Project="$(MSBuildExtensionsPath)\Microsoft\WindowsXaml\v$(VisualStudioVersion)\Microsoft.Windows.UI.Xaml.CSharp.targets" />

</Project>
</code>```

Please help

答:
I think something missing in your .csproj file caused this issue.

Steps to reproduce same issue:

1.Create a new Blank App(Universal Windows)

2.In VS, for those .png resources:Exclude from the project

3.Copy the solution to build server where only has build tools

4.Restore the nuget packages and build the project with command like:

```<code>msbuild path/xxx.csproj(or xxx.sln) /p:Platform=X64 /p:AppxBundle=Always
</code>```

5.Get the error below:

You can follow my simple steps to locate the cause of the issue.

In my opinion:

You might do some similar operation like mine. Maybe Exclude from Project, maybe delete the ItemGroup content in xx.csproj file, or what.

The result is deleting the ItemGroup for those .png files in xx.csproj. If you create a new Blank App(UWP), and check its content of .csproj file you would see:

```<code><ItemGroup>
    <Content Include="Properties\Default.rd.xml" />
    <Content Include="Assets\LockScreenLogo.scale-200.png" />
    <Content Include="Assets\SplashScreen.scale-200.png" />
    <Content Include="Assets\Square150x150Logo.scale-200.png" />
    <Content Include="Assets\Square44x44Logo.scale-200.png" />
    <Content Include="Assets\Square44x44Logo.targetsize-24_altform-unplated.png" />
    <Content Include="Assets\StoreLogo.png" />
    <Content Include="Assets\Wide310x150Logo.scale-200.png" />
  </ItemGroup>
</code>```

But these content is missing in your .csproj file.

These four files which are used in your appmanifest are indeed in your asserts folder.

But without the content ref in .csproj file, the build process can't find them properly.Square150x150Logo.png,Square44x44Logo.png,StoreLogo.png,SplashScreen.png

As a workaround:

So you can edit your xx.csproj file, and add the ItemGroup into it.
But I'm not certainly sure it will work. Since after my checking your .csproj file. Maybe the .png files are not the only things you excluded or removed!!

I'm not sure how many changes you've made to the project, so if above not helps, just create a new project and copy your core code into the new project.

Body:
I am trying to build my first uwp application. I am new to c# as well. I am using visual studio build tools 2019. I think I have done everything right but when I run msbuild, I get the following error:

"C:\Projects\C\UapHello\uaphello.csproj" (default target) (1) ->

(_ValidateAppxPackage target) ->
  Package.appxmanifest(41,9): error APPX0703: Manifest references file 'Assets\Square150x150Logo.png' which is not part
 of the payload. [C:\Projects\C\UapHello\uaphello.csproj]
  Package.appxmanifest(42,9): error APPX0703: Manifest references file 'Assets\Square44x44Logo.png' which is not part o
f the payload. [C:\Projects\C\UapHello\uaphello.csproj]
  Package.appxmanifest(27,6): error APPX0703: Manifest references file 'StoreLogo.png' which is not part of the payload
. [C:\Projects\C\UapHello\uaphello.csproj]
  Package.appxmanifest(45,27): error APPX0703: Manifest references file 'Assets\SplashScreen.png' which is not part of
the payload. [C:\Projects\C\UapHello\uaphello.csproj]

I am pretty sure these files exist in said folder.
I am including my csproj and appmanifest:

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

<Package
  xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
  xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
  xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
  xmlns:uap5="http://schemas.microsoft.com/appx/manifest/uap/windows10/5"
  xmlns:desktop4="http://schemas.microsoft.com/appx/manifest/desktop/windows10/4"
  xmlns:iot2="http://schemas.microsoft.com/appx/manifest/iot/windows10/2"
  IgnorableNamespaces="uap mp uap5 iot2 desktop4">

  <Identity
    Name="IggyMakesThings"
    Publisher="CN=IggyMakesThings, O=IggyMakesThings, L=Redmond, S=Washington, C=US"
    Version="1.0.0.0" />

  <mp:PhoneIdentity PhoneProductId="11a54d62-0d60-4e17-820d-1fa537715b3a" PhonePublisherId="00000000-0000-0000-0000-000000000000"/>

    <Dependencies>
    <TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.17763.0" MaxVersionTested="10.0.17763.0" />
  </Dependencies>

  <Properties>
    <DisplayName>uaphello</DisplayName>
    <PublisherDisplayName>IggyMakesThings</PublisherDisplayName>
    <Logo>StoreLogo.png</Logo>
  </Properties>

  <Resources>
    <Resource Language="x-generate"/>
  </Resources>

  <Applications>
    <Application Id="App"
      Executable="uaphello.exe"
      EntryPoint="UAPHello.App">
      <uap:VisualElements
        DisplayName="UAPSample"
        Square150x150Logo="Assets\Square150x150Logo.png"
        Square44x44Logo="Assets\Square44x44Logo.png"
        Description="UAP C# Sample"
        BackgroundColor="#000000">
        <uap:SplashScreen Image="Assets\SplashScreen.png" />
        <uap:DefaultTile>
          <uap:ShowNameOnTiles>
            <uap:ShowOn Tile="square150x150Logo" />
          </uap:ShowNameOnTiles>
        </uap:DefaultTile>
      </uap:VisualElements>
    </Application>
  </Applications>

</Package>

And csproj:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />

  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">Win32</Platform>
    <ProjectGuid>{$guid1$}</ProjectGuid>
    <OutputType>AppContainerExe</OutputType>
    <RootNamespace>uaphello</RootNamespace>
    <DefaultLanguage>en-US</DefaultLanguage>
    <TargetPlatformIdentifier>UAP</TargetPlatformIdentifier>
    <TargetPlatformVersion>10.0.17763.0</TargetPlatformVersion>
    <TargetPlatformMinVersion>10.0.17763.0</TargetPlatformMinVersion>
    <EnableDotNetNativeCompatibleProfile>true</EnableDotNetNativeCompatibleProfile>
  </PropertyGroup>

  <PropertyGroup>
    <OutputPath>bin\$(Platform)\$(Configuration)\</OutputPath>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
    <PlatformTarget>x64</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
    <NoWarn>;2008</NoWarn>
    <DebugType>full</DebugType>
    <UseVSHostingProcess>false</UseVSHostingProcess>
    <ErrorReport>prompt</ErrorReport>
    <Prefer32Bit>true</Prefer32Bit>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
    <PlatformTarget>x64</PlatformTarget>
    <DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
    <Optimize>true</Optimize>
    <NoWarn>;2008</NoWarn>
    <DebugType>pdbonly</DebugType>
    <UseVSHostingProcess>false</UseVSHostingProcess>
    <ErrorReport>prompt</ErrorReport>
    <Prefer32Bit>true</Prefer32Bit>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|Win32'">
    <PlatformTarget>x86</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
    <NoWarn>;2008</NoWarn>
    <DebugType>full</DebugType>
    <UseVSHostingProcess>false</UseVSHostingProcess>
    <ErrorReport>prompt</ErrorReport>
    <Prefer32Bit>true</Prefer32Bit>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|Win32'">
    <PlatformTarget>x86</PlatformTarget>
    <DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
    <Optimize>true</Optimize>
    <NoWarn>;2008</NoWarn>
    <DebugType>pdbonly</DebugType>
    <UseVSHostingProcess>false</UseVSHostingProcess>
    <ErrorReport>prompt</ErrorReport>
    <Prefer32Bit>true</Prefer32Bit>
  </PropertyGroup>

  <ItemGroup>
    <Compile Include="Program.cs" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.NETCore.UniversalWindowsPlatform" Version="6.2.8" />
  </ItemGroup>

  <ItemGroup>
   <AppxManifest Include="Package.appxmanifest">
     <SubType>Designer</SubType>
   </AppxManifest>
  </ItemGroup>

   <Import Project="$(MSBuildExtensionsPath)\Microsoft\WindowsXaml\v$(VisualStudioVersion)\Microsoft.Windows.UI.Xaml.CSharp.targets" />

</Project>

Please help

Body:
I think something missing in your .csproj file caused this issue.

Steps to reproduce same issue:

1.Create a new Blank App(Universal Windows)

2.In VS, for those .png resources:Exclude from the project

3.Copy the solution to build server where only has build tools

4.Restore the nuget packages and build the project with command like:

msbuild path/xxx.csproj(or xxx.sln) /p:Platform=X64 /p:AppxBundle=Always

5.Get the error below:

You can follow my simple steps to locate the cause of the issue.

In my opinion:

You might do some similar operation like mine. Maybe Exclude from Project, maybe delete the ItemGroup content in xx.csproj file, or what.

The result is deleting the ItemGroup for those .png files in xx.csproj. If you create a new Blank App(UWP), and check its content of .csproj file you would see:

<ItemGroup>
    <Content Include="Properties\Default.rd.xml" />
    <Content Include="Assets\LockScreenLogo.scale-200.png" />
    <Content Include="Assets\SplashScreen.scale-200.png" />
    <Content Include="Assets\Square150x150Logo.scale-200.png" />
    <Content Include="Assets\Square44x44Logo.scale-200.png" />
    <Content Include="Assets\Square44x44Logo.targetsize-24_altform-unplated.png" />
    <Content Include="Assets\StoreLogo.png" />
    <Content Include="Assets\Wide310x150Logo.scale-200.png" />
  </ItemGroup>

But these content is missing in your .csproj file.

These four files which are used in your appmanifest are indeed in your asserts folder.

But without the content ref in .csproj file, the build process can't find them properly.Square150x150Logo.png,Square44x44Logo.png,StoreLogo.png,SplashScreen.png

As a workaround:

So you can edit your xx.csproj file, and add the ItemGroup into it.
But I'm not certainly sure it will work. Since after my checking your .csproj file. Maybe the .png files are not the only things you excluded or removed!!

I'm not sure how many changes you've made to the project, so if above not helps, just create a new project and copy your core code into the new project.


答:
either this will work

```<code> document.querySelectorAll('div:not(#demo) h1')
</code>```

or this

```<code>document.querySelectorAll('h1:not(.demo)')
</code>```

if you want to target all h1 where don't have a class attribute you can do this way

```<code>document.querySelectorAll('h1:not([class])')
</code>```

read more about  :not

Title: querySelectorAll() match all h1's except from a div

Body:
I want to match all h1's on the document except from a div containing other h1's, currently i can do querySelectorAll('h1:not(.demo)) to get all h1's with except h1's with demo class.

But how can i do querySelectorAll('h1:not(div#demo)) or similar thing?

Below is a sample html

First

Second

Third

Fourth

Body:
either this will work

 document.querySelectorAll('div:not(#demo) h1')

or this

document.querySelectorAll('h1:not(.demo)')

if you want to target all h1 where don't have a class attribute you can do this way

document.querySelectorAll('h1:not([class])')

read more about  :not


问:
How to convert a string into an integer without white spaces?
I am trying to multiply complex numbers that is inputted by a user. Some example inputs would be :

Enter a complex number in the form ai + b: 2i + 8

Enter a complex number in the form ai + b: 11  i + 2

Enter a complex number in the form ai + b: 1i+6

I want these all to be valid inputs but am not sure how to make sure that scanf() ignores spaces and the characters so that I can just extract the integers.  I am trying to do this by having scanf() accepting the input as three strings with the first string containing ai, the second string containing the '+', and the third string containing b.  However, my code trying to turn my first string (with ai) into an integer (just a without 'i') is not successful.

```<code>int inta(char* ai){
  int i;
  int origa;
  int max;
  int a = 0;
  for(i = 0; i<strlen(ai); i++){
    if(ai[i] != "i" && ai[i] != ' ')
      continue;
    else
      break;
  }
  if(i > 1)
    for(max = i; max > 0; max--){
      origa = atoi(ai[max])*pow(10, max);
      a = origa + a;
    }
  else
    a = atoi(ai[0]);
  return a;
}
</code>```

答:
UPDATE

Ok , Try these two functions to remove spaces from any string.

```<code>
    char* erase(char*str, int index)
    {
        int i = index;
        while (str[i] != '\0')
        {
            str[i] = str[i + 1];
            i++;
        }
        return str;
    }
    char* remove_spaces(char* str)
    {
        int i = 0;
        while (str[i] != '\0')
        {
            if (str[i] == ' ' || str[i] == '\t' || str[i] == '\n')
            {
                erase(str, i);
                i--;
            }
            i++;

        }
        return str;
    }

</code>```

Then for any character you want to convert it to int you can subtract '0' from it.

Try this code

```<code>
    int x;
    x='5'-'0'
    printf("%d",x);

</code>```

The output for this will be integer value = 5 .

For your case , the first string has (ai) so if you want to convert it to number you can just select the first char "ie: str[0]" and subtract '0' from it.

or you can use my custom function to convert any string to integer but you should check that the string contains only digits before calling this function , and also pass the address of the integer that you want it to hold the result.

for example:

```<code>
    void convert_to_int(char*str,int*result)
    {
        int i=strlen(str)-1;
        *result = 0;
        int factor = 1;
        while (i >= 0)
        {
            (*result) += (str[i]-'0') * factor;
            factor *= 10;
            i--;
        }
    }
    int main()
    {
    int x;
    convert_to_int(str,&x);
    return 0;
    }

</code>```

Body:
I am trying to multiply complex numbers that is inputted by a user. Some example inputs would be :

Enter a complex number in the form ai + b: 2i + 8

Enter a complex number in the form ai + b: 11  i + 2

Enter a complex number in the form ai + b: 1i+6

I want these all to be valid inputs but am not sure how to make sure that scanf() ignores spaces and the characters so that I can just extract the integers.  I am trying to do this by having scanf() accepting the input as three strings with the first string containing ai, the second string containing the '+', and the third string containing b.  However, my code trying to turn my first string (with ai) into an integer (just a without 'i') is not successful.

int inta(char* ai){
  int i;
  int origa;
  int max;
  int a = 0;
  for(i = 0; i<strlen(ai); i++){
    if(ai[i] != "i" && ai[i] != ' ')
      continue;
    else
      break;
  }
  if(i > 1)
    for(max = i; max > 0; max--){
      origa = atoi(ai[max])*pow(10, max);
      a = origa + a;
    }
  else
    a = atoi(ai[0]);
  return a;
}

Body:
UPDATE

Ok , Try these two functions to remove spaces from any string.

    char* erase(char*str, int index)
    {
        int i = index;
        while (str[i] != '\0')
        {
            str[i] = str[i + 1];
            i++;
        }
        return str;
    }
    char* remove_spaces(char* str)
    {
        int i = 0;
        while (str[i] != '\0')
        {
            if (str[i] == ' ' || str[i] == '\t' || str[i] == '\n')
            {
                erase(str, i);
                i--;
            }
            i++;

        }
        return str;
    }

Then for any character you want to convert it to int you can subtract '0' from it.

Try this code

    int x;
    x='5'-'0'
    printf("%d",x);

The output for this will be integer value = 5 .

For your case , the first string has (ai) so if you want to convert it to number you can just select the first char "ie: str[0]" and subtract '0' from it.

or you can use my custom function to convert any string to integer but you should check that the string contains only digits before calling this function , and also pass the address of the integer that you want it to hold the result.

for example:

    void convert_to_int(char*str,int*result)
    {
        int i=strlen(str)-1;
        *result = 0;
        int factor = 1;
        while (i >= 0)
        {
            (*result) += (str[i]-'0') * factor;
            factor *= 10;
            i--;
        }
    }
    int main()
    {
    int x;
    convert_to_int(str,&x);
    return 0;
    }


问:
Cartesian product of rows of a very big array
I have an array of size (100, 50). I need to generate an output array which represents a cartesian product of input array rows.

For simplification purposes, let's have an input array:

```<code>array([[2, 6, 5],
       [7, 3, 6]])
</code>```

As output I would like to have:

```<code>array([[2, 7],
       [2, 3],
       [2, 6],
       [6, 7],
       [6, 3],
       [6, 6],
       [5, 7],
       [5, 3],
       [5, 6]])
</code>```

Note: itertools.product doesn't work here, because of the size of the input vector. Also all another similar answers, assumes number of rows smaller than 32, what is not the case here

Body:
I have an array of size (100, 50). I need to generate an output array which represents a cartesian product of input array rows.

For simplification purposes, let's have an input array:

array([[2, 6, 5],
       [7, 3, 6]])

As output I would like to have:

array([[2, 7],
       [2, 3],
       [2, 6],
       [6, 7],
       [6, 3],
       [6, 6],
       [5, 7],
       [5, 3],
       [5, 6]])

Note: itertools.product doesn't work here, because of the size of the input vector. Also all another similar answers, assumes number of rows smaller than 32, what is not the case here

Body:
a = np.array([[2, 6, 5],[7, 3, 6]])

out = np.array(np.meshgrid(a[0], a[1])).T.reshape(-1,2)
print(out)

"""
prints
[[2 7]
 [2 3]
 [2 6]
 [6 7]
 [6 3]
 [6 6]
 [5 7]
 [5 3]
 [5 6]]
"""


问:
How to pass jwtPayload data decoded by Passport to nodejs API
I am using this passport strategy.

```<code>  passport.use(
    'onlyForRefreshToken',
    new JWTStrategy(
      {
        jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken(),
        secretOrKey: jwtSecretRider,

      },
      (jwtPayload, done) => {

        if (jwtPayload) {
          return done(null, jwtPayload);
        }
        return done(null, false);
      },
    ),
  );
</code>```

My goal is Putting 'jwtPayload' into my rest API of Nodejs that is located at other folder.

That is, I want to use jwtPayload decoded at the code below.

```<code>exports.riderRefreshToken = async (req, res) => {
    const { email } = req.body;

    const exRiderRefreshToken = await Rider.findOne({ email });
}
</code>```

And this router works by middleware of jwtstrategy.

```<code>router.post(
  '/refreshToken',
  passport.authenticate('onlyForRefreshToken', { session: false }),
  authenticationCtrl.riderRefreshToken,
);
</code>```

In conclusion, when JWT passes from jwtstrategy without problem, that Post router would work.

 And I want to use jwtPayload that is in jwtstrategy into Nodejs API as req.params or req.body.

Could you help me this problem?

答:
You need to wrap your strategy into a function that gets req and res :

```<code>const isAuthenticated: RequestHandler = (req, res, next) => {
  passport.authenticate(
    'jwt',
    { session: false, failWithError: true },
    (error, user) => {
      if (error) {
        return next(error)
      }

      //HERE PUT USER WHERE YOU WANT
      //req.data or req.user or req.userInfo
      req.user = user

      return next()
    }
  )(req, res, next)
}
</code>```

I don't recommend putting the user into req.params nor req.body since it might be confusing later on (because technically it doesn't come from those).

Body:
I am using this passport strategy.

  passport.use(
    'onlyForRefreshToken',
    new JWTStrategy(
      {
        jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken(),
        secretOrKey: jwtSecretRider,

      },
      (jwtPayload, done) => {

        if (jwtPayload) {
          return done(null, jwtPayload);
        }
        return done(null, false);
      },
    ),
  );

My goal is Putting 'jwtPayload' into my rest API of Nodejs that is located at other folder.

That is, I want to use jwtPayload decoded at the code below.

exports.riderRefreshToken = async (req, res) => {
    const { email } = req.body;

    const exRiderRefreshToken = await Rider.findOne({ email });
}

And this router works by middleware of jwtstrategy.

router.post(
  '/refreshToken',
  passport.authenticate('onlyForRefreshToken', { session: false }),
  authenticationCtrl.riderRefreshToken,
);

In conclusion, when JWT passes from jwtstrategy without problem, that Post router would work.

 And I want to use jwtPayload that is in jwtstrategy into Nodejs API as req.params or req.body.

Could you help me this problem?

Body:
You need to wrap your strategy into a function that gets req and res :

const isAuthenticated: RequestHandler = (req, res, next) => {
  passport.authenticate(
    'jwt',
    { session: false, failWithError: true },
    (error, user) => {
      if (error) {
        return next(error)
      }

      //HERE PUT USER WHERE YOU WANT
      //req.data or req.user or req.userInfo
      req.user = user

      return next()
    }
  )(req, res, next)
}

I don't recommend putting the user into req.params nor req.body since it might be confusing later on (because technically it doesn't come from those).


问:
Insert into multimap causes segfault
I am working on a project using multimaps inside of my own class, and I have run into a segfault. Here are the parts of my code relating to the issue. I would really appreciate some help. Thanks.

Here is database.h

```<code>#include <iostream>
#include <map>

using namespace std;

class database{
 public:
  database(); // start up the database
  int update(string,int); // update it
  bool is_word(string); //advises if the word is a word
  double prox_mean(string); // finds the average prox
 private:
  multimap<string,int> *data; // must be pointer
 protected:

};
</code>```

Here is the database.cpp

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

#include "database.h"

using namespace std;

// start with the constructor
database::database()
{
  data = new multimap<string,int>; // allocates new space for the database
}

int database::update(string word,int prox)
{
  // add another instance of the word to the database
  cout << "test1"<<endl;
  data->insert( pair<string,int>(word,prox));
  cout << "test2" <<endl;
  // need to be able to tell if it is a word
  bool isWord = database::is_word(word);
  // find the average proximity
  double ave = database::prox_mean(word);

  // tells the gui to updata
  // gui::update(word,ave,isWord); // not finished yet

  return 0;
}
</code>```

Here is test.cpp

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

#include "database.h" //this is my file

using namespace std;

int main()
{
  // first test the constructor
  database * data;

  data->update("trail",3);
  data->update("mix",2);
  data->update("nut",7);
  data->update("and",8);
  data->update("trail",8);
  data->update("and",3);
  data->update("candy",8);

  //  cout<< (int) data->size()<<endl;

  return 0;

}
</code>```

Thanks very much. It compiles and runs up to cout << "test1" << endl; but segfaults on the next line.

Rusty

答:
You never actually created a database object, just a pointer to nowhere (perhaps you're used to another language).

Try creating one like this database data;

And then change your -> to . to access the members.

Consider obtaining one of the books at The Definitive C++ Book Guide and List as well.

Title: Insert into multimap causes segfault

Body:
I am working on a project using multimaps inside of my own class, and I have run into a segfault. Here are the parts of my code relating to the issue. I would really appreciate some help. Thanks.

Here is database.h

#include <iostream>
#include <map>

using namespace std;

class database{
 public:
  database(); // start up the database
  int update(string,int); // update it
  bool is_word(string); //advises if the word is a word
  double prox_mean(string); // finds the average prox
 private:
  multimap<string,int> *data; // must be pointer
 protected:

};

Here is the database.cpp

#include <iostream>
#include <string>
#include <map>
#include <utility>

#include "database.h"

using namespace std;

// start with the constructor
database::database()
{
  data = new multimap<string,int>; // allocates new space for the database
}

int database::update(string word,int prox)
{
  // add another instance of the word to the database
  cout << "test1"<<endl;
  data->insert( pair<string,int>(word,prox));
  cout << "test2" <<endl;
  // need to be able to tell if it is a word
  bool isWord = database::is_word(word);
  // find the average proximity
  double ave = database::prox_mean(word);

  // tells the gui to updata
  // gui::update(word,ave,isWord); // not finished yet

  return 0;
}

Here is test.cpp

#include <iostream>
#include <string>
#include <map>

#include "database.h" //this is my file

using namespace std;

int main()
{
  // first test the constructor
  database * data;

  data->update("trail",3);
  data->update("mix",2);
  data->update("nut",7);
  data->update("and",8);
  data->update("trail",8);
  data->update("and",3);
  data->update("candy",8);

  //  cout<< (int) data->size()<<endl;

  return 0;

}

Thanks very much. It compiles and runs up to cout << "test1" << endl; but segfaults on the next line.

Rusty


问:
How to use 'this.pros.function' to call the function running in the component context?
I want to write a npm package somePackage. Now I write another codes to use this package. If the custom code write the functionA, I would use itself functionA, otherwise I will use the functionA in this package. But I failed to make the custom functionA running in the somePackage context.

```<code>class somePackage extends React.Component{
    constructor(props)
    {
        super(props);
    }

    functionA () {
        if (this.props.functionA)
            this.props.functionA.call(this);
        ...some other codes...
    }
}

class customComponent extends React.Component{
    ...
    functionA(){
        this.setState(state => ({ tags: [...this.state.tags, tag] }));
    }

    render(){
        return (<somePackage/>)
    }
}
</code>```

I hope the this.props.functionA.call(this) could make the this.props.functionA running in the somePackage context, but it actually is running in the customComponent context. This this pointer is still pointing to the customComponent.

答:
Use the arrow function syntax instead:</p>

```<code>    functionA = () => { // arrow function allows "this" to refer to the class when the function is called
        if (this.props.functionA)
            this.props.functionA.call(this);
        ...some other codes...
    }
</code>```

Body:
I want to write a npm package somePackage. Now I write another codes to use this package. If the custom code write the functionA, I would use itself functionA, otherwise I will use the functionA in this package. But I failed to make the custom functionA running in the somePackage context.

class somePackage extends React.Component{
    constructor(props)
    {
        super(props);
    }

    functionA () {
        if (this.props.functionA)
            this.props.functionA.call(this);
        ...some other codes...
    }
}

class customComponent extends React.Component{
    ...
    functionA(){
        this.setState(state => ({ tags: [...this.state.tags, tag] }));
    }

    render(){
        return (<somePackage/>)
    }
}

I hope the this.props.functionA.call(this) could make the this.props.functionA running in the somePackage context, but it actually is running in the customComponent context. This this pointer is still pointing to the customComponent.

Body:
Use the arrow function syntax instead:

    functionA = () => { // arrow function allows "this" to refer to the class when the function is called
        if (this.props.functionA)
            this.props.functionA.call(this);
        ...some other codes...
    }


问:
Regular expressions in a Bash case statement
I am using following script, which uses case statement to find the server.

```<code>    #!/bin/bash
SERVER=$1;
echo $SERVER | egrep "ws-[0-9]+\.host\.com";
case $SERVER in
ws-[0-9]+\.host\.com) echo "Web Server"
;;
db-[0-9]+\.host\.com) echo "DB server"
;;
bk-[0-9]+\.host\.com) echo "Backup server"
;;
*)echo "Unknown server"
;;
esac
</code>```

But it is not working. Regex is working with egrep but not with case. sample O/P

```<code>./test-back.sh ws-23.host.com
ws-23.host.com
Unknown server
</code>```

Any Idea ?

答:
I know this is a rather old question and my solution isn't much different from what @syjust has already provided, but I wanted to show that you can do just about anything at the matching stage in a case/esac statement.

```<code>$ cat case.sh && echo -e "#################\n" && bash case.sh ws-23.host.com
#!/bin/bash
SERVER=$1;
echo $SERVER | egrep "ws-[0-9]+\.host\.com";
case $SERVER in
  $(awk '{a=0}/ws-[0-9]*.host.com/{a=1}a' <<<${SERVER}))echo "Web Server";;
  $(awk '{a=0}/db-[0-9]*.host.com/{a=1}a' <<<${SERVER}))echo "DB Server";;
  $(awk '{a=0}/bk-[0-9]*.host.com/{a=1}a' <<<${SERVER}))echo "Backup Server";;
  *)echo "Unknown server";;
esac

#################

ws-23.host.com
Web Server

</code>```

Body:
I am using following script, which uses case statement to find the server.

    #!/bin/bash
SERVER=$1;
echo $SERVER | egrep "ws-[0-9]+\.host\.com";
case $SERVER in
ws-[0-9]+\.host\.com) echo "Web Server"
;;
db-[0-9]+\.host\.com) echo "DB server"
;;
bk-[0-9]+\.host\.com) echo "Backup server"
;;
*)echo "Unknown server"
;;
esac

But it is not working. Regex is working with egrep but not with case. sample O/P

./test-back.sh ws-23.host.com
ws-23.host.com
Unknown server

Any Idea ?

Body:
I know this is a rather old question and my solution isn't much different from what @syjust has already provided, but I wanted to show that you can do just about anything at the matching stage in a case/esac statement.

$ cat case.sh && echo -e "#################\n" && bash case.sh ws-23.host.com
#!/bin/bash
SERVER=$1;
echo $SERVER | egrep "ws-[0-9]+\.host\.com";
case $SERVER in
  $(awk '{a=0}/ws-[0-9]*.host.com/{a=1}a' <<<${SERVER}))echo "Web Server";;
  $(awk '{a=0}/db-[0-9]*.host.com/{a=1}a' <<<${SERVER}))echo "DB Server";;
  $(awk '{a=0}/bk-[0-9]*.host.com/{a=1}a' <<<${SERVER}))echo "Backup Server";;
  *)echo "Unknown server";;
esac

#################

ws-23.host.com
Web Server


问:
How to catch specific SQL exception in fluent migrator?
I'm writing migration which should remove duplicate rows, however it is possible that some of ids will be in use, so for this scenario records should be set to inactive. I have written the migration which should work :) But I'd like to know is it possible to catch the specific ForeignKeyException? I want to try to set active to 0 only if foreign key error occurs on deleting rows. The database on the sql server.

Migration

```<code>[Migration(201905311022)]
public class _201905311022_RemoveDuplicatesFromCarrierLookUp : Migration
{
    private const string row_number = "row_number";
    private const string CTE = "CTE";
    private const string LookUp_Carrier = "LookUp_Carrier";
    private const string CarrierId = "CarrierId";
    private const string Carrier = "Carrier";
    private readonly string WithCte = $@"
WITH CTE AS
(SELECT {Carrier}, {CarrierId}, ROW_NUMBER() OVER(PARTITION BY {Carrier}
ORDER BY {CarrierId}) as {row_number} FROM {LookUp_Carrier})";

    public override void Up()
    {
        try
        {
            RemoveRecordsWithSameName();
        }
        catch(Exception foreignKeyConstrain)
        {
            MakeRecordsWithSameNameInActive();
        }
    }

    private void MakeRecordsWithSameNameInActive()
    {
        Execute.Sql($@"{WithCte}
UPDATE {LookUp_Carrier}
SET Active = 0
WHERE {CarrierId} in (SELECT {CarrierId} FROM {CTE} WHERE {row_number} <> 1)");
    }

    private void RemoveRecordsWithSameName()
    {
        Execute.Sql($@"{WithCte}
  DELETE FROM {LookUp_Carrier} WHERE {CarrierId} IN (SELECT {CarrierId} FROM {CTE} WHERE {row_number} <> 1)");
    }

    public override void Down()
    {
        Console.WriteLine("Rollback for data manipulation wasn't implemented");
    }
}
</code>```

答:
You could process it something like that:     </p>

```<code>        try
        {
            RemoveRecordsWithSameName();
        }
        catch (SqlException ex)
        {
             if (ex.Errors.Count > 0) // Assume the interesting stuff is in the first error
            {
             switch (ex.Errors[0].Number)
            {
            case 547: // Foreign Key violation but you have to check number
                MakeRecordsWithSameNameInActive();
                break;
            default:
                throw new DataAccessException(ex);
            }
            }

        }
        catch(Exception ex)
        {
          //process regular exception
        }
</code>```

Body:
I'm writing migration which should remove duplicate rows, however it is possible that some of ids will be in use, so for this scenario records should be set to inactive. I have written the migration which should work :) But I'd like to know is it possible to catch the specific ForeignKeyException? I want to try to set active to 0 only if foreign key error occurs on deleting rows. The database on the sql server.

Migration

[Migration(201905311022)]
public class _201905311022_RemoveDuplicatesFromCarrierLookUp : Migration
{
    private const string row_number = "row_number";
    private const string CTE = "CTE";
    private const string LookUp_Carrier = "LookUp_Carrier";
    private const string CarrierId = "CarrierId";
    private const string Carrier = "Carrier";
    private readonly string WithCte = $@"
WITH CTE AS
(SELECT {Carrier}, {CarrierId}, ROW_NUMBER() OVER(PARTITION BY {Carrier}
ORDER BY {CarrierId}) as {row_number} FROM {LookUp_Carrier})";

    public override void Up()
    {
        try
        {
            RemoveRecordsWithSameName();
        }
        catch(Exception foreignKeyConstrain)
        {
            MakeRecordsWithSameNameInActive();
        }
    }

    private void MakeRecordsWithSameNameInActive()
    {
        Execute.Sql($@"{WithCte}
UPDATE {LookUp_Carrier}
SET Active = 0
WHERE {CarrierId} in (SELECT {CarrierId} FROM {CTE} WHERE {row_number} <> 1)");
    }

    private void RemoveRecordsWithSameName()
    {
        Execute.Sql($@"{WithCte}
  DELETE FROM {LookUp_Carrier} WHERE {CarrierId} IN (SELECT {CarrierId} FROM {CTE} WHERE {row_number} <> 1)");
    }

    public override void Down()
    {
        Console.WriteLine("Rollback for data manipulation wasn't implemented");
    }
}

Body:
You could process it something like that:

        try
        {
            RemoveRecordsWithSameName();
        }
        catch (SqlException ex)
        {
             if (ex.Errors.Count > 0) // Assume the interesting stuff is in the first error
            {
             switch (ex.Errors[0].Number)
            {
            case 547: // Foreign Key violation but you have to check number
                MakeRecordsWithSameNameInActive();
                break;
            default:
                throw new DataAccessException(ex);
            }
            }

        }
        catch(Exception ex)
        {
          //process regular exception
        }


问:
set tabbar icon color in react-native-navigation
Is there any way to dynamically set a new tab bar icon AND color?
In my app, I want the icon for the CHAT tab to be changed to red when a new message arrives.

Steps to Reproduce / Code Snippets / Screenshots

```<code>    this.props.navigator.setTabButton(
        {
                tabIndex: 2,
                screen: 'parkour.ChatListScreen',
                title: 'Chat',
                icon: iconsMap[2],
                style: { color: 'red' }
        },
</code>```

the style property does not work at all, the resulting color is yellow.

I a using react native navigation v.1.

答:
Add TabIcon component in navigationOption of createBottomTabNavigator
use redux or context api to change state of TabIconComponent.</p>

```<code> navigationOptions: ({ navigation }) => ({
  tabBarIcon: ({ tintColor }) => {// eslint-disable-line

    const { routeName } = navigation.state;
    let iconName;
    if (routeName === 'Home') iconName = 'home';
    else if (routeName === 'Notifications') iconName = 'notifications';
    else if (routeName === 'Readout') iconName = 'readout';
    else if (routeName === 'Inbox') iconName = 'messages';
    else if (routeName === 'Profile') iconName = 'profile';

    return <TabIcons iconName={iconName} tintColor={tintColor} />;
  },
  tabBarVisible: true,
}),
</code>```

Body:
Is there any way to dynamically set a new tab bar icon AND color?
In my app, I want the icon for the CHAT tab to be changed to red when a new message arrives.

Steps to Reproduce / Code Snippets / Screenshots

    this.props.navigator.setTabButton(
        {
                tabIndex: 2,
                screen: 'parkour.ChatListScreen',
                title: 'Chat',
                icon: iconsMap[2],
                style: { color: 'red' }
        },

the style property does not work at all, the resulting color is yellow.

I a using react native navigation v.1.

Body:
Add TabIcon component in navigationOption of createBottomTabNavigator
use redux or context api to change state of TabIconComponent.

 navigationOptions: ({ navigation }) => ({
  tabBarIcon: ({ tintColor }) => {// eslint-disable-line

    const { routeName } = navigation.state;
    let iconName;
    if (routeName === 'Home') iconName = 'home';
    else if (routeName === 'Notifications') iconName = 'notifications';
    else if (routeName === 'Readout') iconName = 'readout';
    else if (routeName === 'Inbox') iconName = 'messages';
    else if (routeName === 'Profile') iconName = 'profile';

    return <TabIcons iconName={iconName} tintColor={tintColor} />;
  },
  tabBarVisible: true,
}),


问:
How to stop activity from creating everytime when started from other activity?
I am trying to create a multiple activity app. having activity 1.mainactivity
2.mapsactivity. Now I have a navigation drawer i.e when user click on maps
an intent will be called to map activity. Because of this when the user starts operating in the mapsactivity and onBackpressed he again returns to mainactivity and when he again go to maps the activity starts again. Is there a solution to this problem, How can I run my activity even if navigating to other activity?

"This is a part of mainactivity having nav drawer"

```<code> public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_home) {
        } else if (id == R.id.nav_maps) {
            // Maps Activity
            Intent intent = new Intent(getApplicationContext(),AttendanceActivity.class);
            startActivity(intent);
        } else if (id == R.id.nav_rider_app) {

       }
</code>```

答:
first you should handle onBackpressed in mapsactivity. as you can see here onbackpressed will destroy your activity. you can do something like this in your mapsactivity:</p>

```<code>public void onBackPressed() {
    // TODO Auto-generated method stub
    moveTaskToBack(true);
    super.onBackPressed();
}
</code>```

Body:
I am trying to create a multiple activity app. having activity 1.mainactivity
2.mapsactivity. Now I have a navigation drawer i.e when user click on maps
an intent will be called to map activity. Because of this when the user starts operating in the mapsactivity and onBackpressed he again returns to mainactivity and when he again go to maps the activity starts again. Is there a solution to this problem, How can I run my activity even if navigating to other activity?

"This is a part of mainactivity having nav drawer"

 public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_home) {
        } else if (id == R.id.nav_maps) {
            // Maps Activity
            Intent intent = new Intent(getApplicationContext(),AttendanceActivity.class);
            startActivity(intent);
        } else if (id == R.id.nav_rider_app) {

       }

Body:
first you should handle onBackpressed in mapsactivity. as you can see here onbackpressed will destroy your activity. you can do something like this in your mapsactivity:

public void onBackPressed() {
    // TODO Auto-generated method stub
    moveTaskToBack(true);
    super.onBackPressed();
}


问:
How to get HH:MM:SS difference using milliseconds in javascript?
I have two times like one is 145:02:31 and another one is 01:00:00 and I want to calculate the difference between these two times like 144:02:31 but right now I am getting 13:02:31 which is wrong.

Please help me thank you.

答:
Here a try without any external lib.
steps ->
 1. convert the timestamp in seconds
 2. calculate diff
 3. revert second into desired format

```<code>function diff(a, b){
  const getSec = val => {
    const arr = val.split(':')
    return Number(arr[2]) + Number(arr[1])*60 + Number(arr[0])*3600
   }
  const diff =  getSec(a) - getSec(b)

  const h = parseInt(diff/3600)
  const m = parseInt((diff - h*3600)/60)
  const s = diff%60

  return`${h}:${m}:${s}`
}

diff("145:02:31", "01:00:00" ) //"144:2:31"
</code>```

Body:
Here a try without any external lib.
steps ->
 1. convert the timestamp in seconds
 2. calculate diff
 3. revert second into desired format

function diff(a, b){
  const getSec = val => {
    const arr = val.split(':')
    return Number(arr[2]) + Number(arr[1])*60 + Number(arr[0])*3600
   }
  const diff =  getSec(a) - getSec(b)

  const h = parseInt(diff/3600)
  const m = parseInt((diff - h*3600)/60)
  const s = diff%60

  return`${h}:${m}:${s}`
}

diff("145:02:31", "01:00:00" ) //"144:2:31"


问:
Is HAML a Better Tool for Experienced Ruby/Rails Developers?
One of the joys of being a new Ruby on Rails student/developer is the constant discovery of new Gems to make my life more fun or easier. Recently, I "discovered" HAML, which appears to be a fantastic tool for making ERB code even more readable than it already is. However, I wonder if it is a good idea for newer developers, like myself, to embrace a tool like HAML early on, or if it would be smarter to hold off until my expertise in plain Ruby / Rails code has matured. My worry, I suppose, is that embracing a tool like HAML too early might impede my full understanding of Ruby through the coding "shortcuts" it offers. What do you experienced coders say? </p>

答: HAML is an HTML abstraction. Aside from whitespace concerns, it doesn't change the way you write Ruby per se.</p>


问:
Adjust div width according to child element
In this fiddle: https://jsfiddle.net/7d84Laxr/1/

```<code><div class="textCenter">
    <div class="wrapper">
        <input type="text" class="inputNoBorder">
        <p style="display: inline-block;">/Some Text.</p>
    </div>
</div>
</code>```

I want to underline (border-bottom) the input and p only. But as the width of parent div is same as window width, it draws a full line.

How can I reduce wrapper div's width to only contain two elements so that border will be only below those two elements?

I prefer no JavaScript.

答:
Add display:inline-block to the parent div

.textCenter{
  text-align : center;
}

.inputNoBorder{
 border: 0px;
  display: -webkit-inline-box;
  padding: 0px;
  margin: 0rem 0.2rem;
  width: 15rem;
}

.wrapper{
  border-bottom: 1px solid;
  display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="textCenter">
 <div class="wrapper">
  <input type="text" class="inputNoBorder">
  <p style="display: inline-block;">/DENSPRI, LLC.</p>
 </div>
</div></code>```

Body:
In this fiddle: https://jsfiddle.net/7d84Laxr/1/

        <input type="text" class="inputNoBorder">

/Some Text.

I want to underline (border-bottom) the input and p only. But as the width of parent div is same as window width, it draws a full line.

How can I reduce wrapper div's width to only contain two elements so that border will be only below those two elements?

I prefer no JavaScript.

Body:
Add display:inline-block to the parent div

.textCenter{
  text-align : center;
}

.inputNoBorder{
 border: 0px;
  display: -webkit-inline-box;
  padding: 0px;
  margin: 0rem 0.2rem;
  width: 15rem;
}

.wrapper{
  border-bottom: 1px solid;
  display: inline-block;
}

<div class="textCenter">
 <div class="wrapper">
  <input type="text" class="inputNoBorder">
  <p style="display: inline-block;">/DENSPRI, LLC.</p>
 </div>
</div>


问:
Spring data rest merge patch
I am using spring data rest in my project and have question about
application/merge-patch+json request.
While application/json-patch+json request works good i have troubles with merge-patch.
For example i have nested object without repository like this

```<code>"student":{
  "id":1,
  "address":{
   "id":1,
   "street":2,
   "building":2
 }
}
</code>```

And i am sending PATCH, application/merge-patch+json to students/1
with this payload

```<code>{
  "address":{
   "street":3
  }
}
</code>```

I am getting this result

```<code>"student":{
  "id":1,
  "address":{
   "id":2,
   "street":3,
   "building":null
 }
}
</code>```

So spring data rest just created new address object instead of merging.

Java code is like this

```<code>@Entity
@Table(name = "Student")
public class Student {
    @Id
    @GeneratedValue
    private long studentId;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "addressId")
    private Address address;

    //getters and setters
}
</code>```

Address class:

```<code>@Entity
@Table(name = "Address")
public class Address {
     @Id
     @GeneratedValue
     private long addressId;
     private String street;
     private String building;

     //getters and setters
}
</code>```

Also student have rest repository and address have not

My question is how i can achieve correct behavior in merging patch requests in spring data rest?

答:
Though it is delayed response, it can be helpful to others who has same issue

In the input JSON, address id is missing.

```<code>{
  "address":{
   "id" : 1,
   "street":3
  }
}
</code>```

Title: Spring data rest merge patch

Body:
I am using spring data rest in my project and have question about
application/merge-patch+json request.
While application/json-patch+json request works good i have troubles with merge-patch.
For example i have nested object without repository like this

"student":{
  "id":1,
  "address":{
   "id":1,
   "street":2,
   "building":2
 }
}

And i am sending PATCH, application/merge-patch+json to students/1
with this payload

{
  "address":{
   "street":3
  }
}

I am getting this result

"student":{
  "id":1,
  "address":{
   "id":2,
   "street":3,
   "building":null
 }
}

So spring data rest just created new address object instead of merging.

Java code is like this

@Entity
@Table(name = "Student")
public class Student {
    @Id
    @GeneratedValue
    private long studentId;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "addressId")
    private Address address;

    //getters and setters
}

Address class:

@Entity
@Table(name = "Address")
public class Address {
     @Id
     @GeneratedValue
     private long addressId;
     private String street;
     private String building;

     //getters and setters
}

Also student have rest repository and address have not

My question is how i can achieve correct behavior in merging patch requests in spring data rest?

Body:
Though it is delayed response, it can be helpful to others who has same issue

In the input JSON, address id is missing.

{
  "address":{
   "id" : 1,
   "street":3
  }
}


问:
Angular 8: Why UNMET PEER DEPENDENCY @angular/common@8.0.0?
I upgraded to the latest Angular 8 version, and the update went fine. It is now working as before the update.

I just see weird messages when doing npm list (after npm install finishes):

```<code>UNMET PEER DEPENDENCY @angular/common@8.0.0
...
UNMET PEER DEPENDENCY @angular/compiler@8.0.0
...
UNMET PEER DEPENDENCY @angular/core@8.0.0
</code>```

Why is it the case?

I guess the packages are not missing since the app works well and they are in my package.json file:

```<code>"@angular/common": "8.0.0",
"@angular/compiler": "^8.0.0",
"@angular/core": "8.0.0",
</code>```

I have the latest node and npm:

```<code>npm -v
6.9.0
node -v
v12.3.1
</code>```

Edit 2:
npm ls output is: Git gist

Edit:
package.json is:

```<code>{
  "name": "webapp",
  "version": "0.1.0",
  "engines": {
    "node": "^12.3.1",
    "npm": "^6.9.0"
  },
  "scripts": {
    "ng": "ng",
    "test": "ng test",
    "lint": "ng lint",
    "pree2e": "webdriver-manager update",
    "e2e": "ng e2e",
    "postinstall": "ng build --prod --aot --build-optimizer --optimization",
    "compodoc": "compodoc --tsconfig compodoc-config.ts --output ./doc --theme material --name 'API documentation'"
  },
  "private": true,
  "dependencies": {
    "@angular-devkit/build-angular": "^0.800.0",
    "@angular/animations": "^8.0.0",
    "@angular/cdk": "^8.0.0",
    "@angular/cli": "^8.0.0",
    "@angular/common": "8.0.0",
    "@angular/compiler": "^8.0.0",
    "@angular/compiler-cli": "^8.0.0",
    "@angular/core": "8.0.0",
    "@angular/flex-layout": "^8.0.0-beta.26",
    "@angular/forms": "^8.0.0",
    "@angular/material": "^8.0.0",
    "@angular/platform-browser": "^8.0.0",
    "@angular/platform-browser-dynamic": "^8.0.0",
    "@angular/router": "^8.0.0",
    "@swimlane/ngx-charts": "^11.1.0",
    "acorn": "^6.1.1",
    "ag-grid-angular": "^20.0.0",
    "ag-grid-community": "^20.0.0",
    "compression": "^1.7.4",
    "core-js": "^2.6.3",
    "crypto-js": "^3.1.9-1",
    "d3": "^5.9.2",
    "d3-sankey": "^0.12.1",
    "express": "^4.17.1",
    "force-ssl-heroku": "^1.0.2",
    "hammerjs": "^2.0.8",
    "ng-recaptcha": "^4.2.1",
    "ngx-logger": "^3.3.11",
    "ngx-webstorage-service": "^4.0.1",
    "rxjs": "~6.5.2",
    "ts-node": "~8.0.2",
    "tslib": "^1.9.3",
    "typescript": "^3.4.5",
    "zone.js": "~0.9.1"
  },
  "devDependencies": {
    "@angular/language-service": "^8.0.0",
    "@types/d3": "^5.7.2",
    "@types/d3-sankey": "^0.11.0",
    "@types/jasmine": "^3.3.13",
    "@types/jasminewd2": "~2.0.6",
    "@types/selenium-webdriver": "^4.0.0",
    "codelyzer": "~4.5.0",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "^4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.5",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.2",
    "karma-mocha-reporter": "^2.2.5",
    "protractor": "^5.4.2",
    "tslint": "~5.12.1"
  }
}
</code>```

答:
```<code>npm ERR! peer dep missing: @angular/common@^6.0.0 || ^7.0.0, required by ngx-logger@3.3.13
npm ERR! peer dep missing: @angular/compiler@>=2.3.1 <8.0.0 || >7.0.0-beta <8.0.0, required by codelyzer@4.5.0
npm ERR! peer dep missing: @angular/core@>=2.3.1 <8.0.0 || >7.0.0-beta <8.0.0, required by codelyzer@4.5.0
npm ERR! peer dep missing: @angular/core@^6.0.0 || ^7.0.0, required by ng-recaptcha@4.2.1
npm ERR! peer dep missing: @angular/core@^6.0.0 || ^7.0.0, required by ngx-logger@3.3.13
</code>```

The output states that some of your 3rd party packages require lower versions of some of the angular packages (< 8.0.0).

You have to either:

Upgrade the version of those 3rd party packages to one compatible with angular@8.0.0

Downgrade your angular version to one compatible with the 3rd party requirements

Ignore the errors, assuming that the changes introduced between the mayor versions of angular dont break the 3rd party packages

Body:
I upgraded to the latest Angular 8 version, and the update went fine. It is now working as before the update.

I just see weird messages when doing npm list (after npm install finishes):

UNMET PEER DEPENDENCY @angular/common@8.0.0
...
UNMET PEER DEPENDENCY @angular/compiler@8.0.0
...
UNMET PEER DEPENDENCY @angular/core@8.0.0

Why is it the case?

I guess the packages are not missing since the app works well and they are in my package.json file:

"@angular/common": "8.0.0",
"@angular/compiler": "^8.0.0",
"@angular/core": "8.0.0",

I have the latest node and npm:

npm -v
6.9.0
node -v
v12.3.1

Edit 2:
npm ls output is: Git gist

Edit:
package.json is:

{
  "name": "webapp",
  "version": "0.1.0",
  "engines": {
    "node": "^12.3.1",
    "npm": "^6.9.0"
  },
  "scripts": {
    "ng": "ng",
    "test": "ng test",
    "lint": "ng lint",
    "pree2e": "webdriver-manager update",
    "e2e": "ng e2e",
    "postinstall": "ng build --prod --aot --build-optimizer --optimization",
    "compodoc": "compodoc --tsconfig compodoc-config.ts --output ./doc --theme material --name 'API documentation'"
  },
  "private": true,
  "dependencies": {
    "@angular-devkit/build-angular": "^0.800.0",
    "@angular/animations": "^8.0.0",
    "@angular/cdk": "^8.0.0",
    "@angular/cli": "^8.0.0",
    "@angular/common": "8.0.0",
    "@angular/compiler": "^8.0.0",
    "@angular/compiler-cli": "^8.0.0",
    "@angular/core": "8.0.0",
    "@angular/flex-layout": "^8.0.0-beta.26",
    "@angular/forms": "^8.0.0",
    "@angular/material": "^8.0.0",
    "@angular/platform-browser": "^8.0.0",
    "@angular/platform-browser-dynamic": "^8.0.0",
    "@angular/router": "^8.0.0",
    "@swimlane/ngx-charts": "^11.1.0",
    "acorn": "^6.1.1",
    "ag-grid-angular": "^20.0.0",
    "ag-grid-community": "^20.0.0",
    "compression": "^1.7.4",
    "core-js": "^2.6.3",
    "crypto-js": "^3.1.9-1",
    "d3": "^5.9.2",
    "d3-sankey": "^0.12.1",
    "express": "^4.17.1",
    "force-ssl-heroku": "^1.0.2",
    "hammerjs": "^2.0.8",
    "ng-recaptcha": "^4.2.1",
    "ngx-logger": "^3.3.11",
    "ngx-webstorage-service": "^4.0.1",
    "rxjs": "~6.5.2",
    "ts-node": "~8.0.2",
    "tslib": "^1.9.3",
    "typescript": "^3.4.5",
    "zone.js": "~0.9.1"
  },
  "devDependencies": {
    "@angular/language-service": "^8.0.0",
    "@types/d3": "^5.7.2",
    "@types/d3-sankey": "^0.11.0",
    "@types/jasmine": "^3.3.13",
    "@types/jasminewd2": "~2.0.6",
    "@types/selenium-webdriver": "^4.0.0",
    "codelyzer": "~4.5.0",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "^4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.5",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.2",
    "karma-mocha-reporter": "^2.2.5",
    "protractor": "^5.4.2",
    "tslint": "~5.12.1"
  }
}

Body:
npm ERR! peer dep missing: @angular/common@^6.0.0 || ^7.0.0, required by ngx-logger@3.3.13
npm ERR! peer dep missing: @angular/compiler@>=2.3.1 <8.0.0 || >7.0.0-beta <8.0.0, required by codelyzer@4.5.0
npm ERR! peer dep missing: @angular/core@>=2.3.1 <8.0.0 || >7.0.0-beta <8.0.0, required by codelyzer@4.5.0
npm ERR! peer dep missing: @angular/core@^6.0.0 || ^7.0.0, required by ng-recaptcha@4.2.1
npm ERR! peer dep missing: @angular/core@^6.0.0 || ^7.0.0, required by ngx-logger@3.3.13

The output states that some of your 3rd party packages require lower versions of some of the angular packages (< 8.0.0).

You have to either:

Upgrade the version of those 3rd party packages to one compatible with angular@8.0.0

Downgrade your angular version to one compatible with the 3rd party requirements

Ignore the errors, assuming that the changes introduced between the mayor versions of angular dont break the 3rd party packages