问:
sql missing from clause
```<code>  select m_product.name ,c_bpartner.name  from(
  select count(m_product.name)
  from m_product
  union
  select count(c_bpartner.name)
  from c_bpartner
  ) as total
</code>```

I am getting error.

Error:

missing from-clause entry for table m_product.

Im trying to get the total number of products and bpartner in a table.
Thank you for any help.

```<code> |total number of product|total number of bp|
 |     1000              |   1200           |
 |                       |                  |
</code>```

This is what I'am trying to achieve, I'am doing this using the jasper report.

答:
I think you need to give your columns an alias, so it would be:</p>

```<code>  select total.mprodName ,total.cpartName  from(
  select count(m_product.name) AS mprodName
  from m_product
  union
  select count(c_bpartner.name) AS cbpartName
  from c_bpartner
  ) as total
</code>```

Title: sql missing from clause

Body:
  select m_product.name ,c_bpartner.name  from(
  select count(m_product.name)
  from m_product
  union
  select count(c_bpartner.name)
  from c_bpartner
  ) as total

I am getting error.

Error:

missing from-clause entry for table m_product.

Im trying to get the total number of products and bpartner in a table.
Thank you for any help.

 |total number of product|total number of bp|
 |     1000              |   1200           |
 |                       |                  |

This is what I'am trying to achieve, I'am doing this using the jasper report.

Body:
I think you need to give your columns an alias, so it would be:

  select total.mprodName ,total.cpartName  from(
  select count(m_product.name) AS mprodName
  from m_product
  union
  select count(c_bpartner.name) AS cbpartName
  from c_bpartner
  ) as total


来源: stackexchange

问:
How to enable all disabled breakpoints in visual studio code
Does anyone know how to enable all the disabled breakpoints in visual studio code (v1.13). There is an option to disable breakpoints in one click. But I couldn't find any option to enable all the breakpoints. As of now I am enabling breakpoint one by one. </p>

答: You can try to install the insiders version.

ContentLicense: CC BY-SA 3.0


问:
saving operators in arrays, error
To give an idea of what I want elaborate with this code is the following:

Enter two numbers: 10 7

Choose Operator: e.g. (+, - , * and /)

What's 10 * 7?

Correct!

```<code>int[] arr = new int[5];

System.out.println("enter two numbers: ");
arr[1] = sc.nextInt();
arr[2] = sc.nextInt();

System.out.println("Choose Operator: ");
arr[3] = sc.nextInt();

int operator = arr[1]+arr[3]+arr[2];

System.out.print("what's "+operator);
int svar = sc.nextInt();

if (svar == operator)
    System.out.println("Correct!");
else
    System.out.println("Wrong - the right answer is "+operator);
</code>```

Now I'm having a problem with running some aspects within this code. It works fine to compile but each time the program asks for to "choose operator" the compiler responses with the following error:

Exception in thread "main"

java.util.InputMismatchException   at

java.util.Scanner.throwFor(Unknown

Source)    at

java.util.Scanner.next(Unknown

Source)    at

java.util.Scanner.nextInt(Unknown

Source)    at

java.util.Scanner.nextInt(Unknown

Source)

at test1.main(test1.java:13)

I wonder how I'm going to deal with this one. But the goal would be to "save" the desired operator, and then put it together with arr[1] and arr[2] (shown in int operator) to "sort of" create this whole mathematical operation. But the error occurs when I choose one particular operator.

I would appreciate some help with this one. Thank you!

答:
You're calling nextInt, which tries to read an integer.

Since you aren't entering an integer, you're getting an error.

To implement your idea, you would need an Operator interface with an int execute(int x, iny y) method, and a separate class for each operator.

You would then read a character from sc and find the corresponding Operator implementation for that character.  (perhaps using a Map<String, Operator>)

ContentLicense: CC BY-SA 2.5

Title: saving operators in arrays, error

Body:
To give an idea of what I want elaborate with this code is the following:

Enter two numbers: 10 7

Choose Operator: e.g. (+, - , * and /)

What's 10 * 7?

Correct!

int[] arr = new int[5];

System.out.println("enter two numbers: ");
arr[1] = sc.nextInt();
arr[2] = sc.nextInt();

System.out.println("Choose Operator: ");
arr[3] = sc.nextInt();

int operator = arr[1]+arr[3]+arr[2];

System.out.print("what's "+operator);
int svar = sc.nextInt();

if (svar == operator)
    System.out.println("Correct!");
else
    System.out.println("Wrong - the right answer is "+operator);

Now I'm having a problem with running some aspects within this code. It works fine to compile but each time the program asks for to "choose operator" the compiler responses with the following error:

Exception in thread "main"

java.util.InputMismatchException   at

java.util.Scanner.throwFor(Unknown

Source)    at

java.util.Scanner.next(Unknown

Source)    at

java.util.Scanner.nextInt(Unknown

Source)    at

java.util.Scanner.nextInt(Unknown

Source)

at test1.main(test1.java:13)

I wonder how I'm going to deal with this one. But the goal would be to "save" the desired operator, and then put it together with arr[1] and arr[2] (shown in int operator) to "sort of" create this whole mathematical operation. But the error occurs when I choose one particular operator.

I would appreciate some help with this one. Thank you!


问:
Generating PDF in windows forms using XML reader
My windows form contains a textbox in which we need to enter html tags,One button to generate PDF.
And we need to load the textbox content into XML Reader and process each element of XML recursively then we need to generate a PDF file.
The PDF file must contain the data i.e;
for example if I entered  tag in the text box in the pdf file it must display a table.
I am very new to Windows forms and XML also can any one help me to complete this task</p>

答:
```<code>PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\MySamplePDF.pdf", FileMode.Create));
</code>```

<p>Changed this code by using a savefile dialog box </p>

```<code> SaveFileDialog svg = new SaveFileDialog();
            svg.ShowDialog();

                      PdfWriter.GetInstance(document, new FileStream(svg.FileName + ".pdf", FileMode.Create));
</code>```

Body:
PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\MySamplePDF.pdf", FileMode.Create));

Changed this code by using a savefile dialog box

 SaveFileDialog svg = new SaveFileDialog();
            svg.ShowDialog();

                      PdfWriter.GetInstance(document, new FileStream(svg.FileName + ".pdf", FileMode.Create));


问:
Getting AspNetUsers to join to custom tables
I am trying to authorize a specific user to see only his own company-data. I have created a custom field in ApplicationUser called CompanyId and created a CompanyController (With the help of Erik Funkenbusch) as follows:

```<code>public class CompanyController : Controller
{
    private ApplicationDbContext db = new ApplicationDbContext();

    // GET: Company
    public ActionResult Index()

{
        var companies = from c in db.Companies
                        join u in db.AspNetUsers
                        on c.CompanyID equals u.Company.Id
                        where u.UserName = User.Identity.Name
                        select c;
        return View(companies);
    }
</code>```

However:db.AspNetUsers returns an 'does not contain a definition in ApplicationDbContext'-error in VS2017. What am I overlooking? My context is (still) very standard and looks as followss:

```<code>public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

    static ApplicationDbContext()
    {
        // Set the database intializer which is run once during application start
        // This seeds the database with admin user credentials and admin role
        Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

    public DbSet<Company> Companies { get; set; }
</code>```

答:
I think the problem is that the Property which contains the Users on an IdentityDbContext<T> is called Users and not AspNetUsers. See here

So you should try this:

```<code>   var companies = from c in db.Companies
                        join u in db.Users
                        on c.CompanyID equals u.Company.Id
                        where u.UserName == User.Identity.Name
                        select c;
</code>```

(Spot the part with db.Users instead of db.AspNetUsers)

Body:
I am trying to authorize a specific user to see only his own company-data. I have created a custom field in ApplicationUser called CompanyId and created a CompanyController (With the help of Erik Funkenbusch) as follows:

public class CompanyController : Controller
{
    private ApplicationDbContext db = new ApplicationDbContext();

    // GET: Company
    public ActionResult Index()

{
        var companies = from c in db.Companies
                        join u in db.AspNetUsers
                        on c.CompanyID equals u.Company.Id
                        where u.UserName = User.Identity.Name
                        select c;
        return View(companies);
    }

However:db.AspNetUsers returns an 'does not contain a definition in ApplicationDbContext'-error in VS2017. What am I overlooking? My context is (still) very standard and looks as followss:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

    static ApplicationDbContext()
    {
        // Set the database intializer which is run once during application start
        // This seeds the database with admin user credentials and admin role
        Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

    public DbSet<Company> Companies { get; set; }

Body:
I think the problem is that the Property which contains the Users on an IdentityDbContext<T> is called Users and not AspNetUsers. See here

So you should try this:

   var companies = from c in db.Companies
                        join u in db.Users
                        on c.CompanyID equals u.Company.Id
                        where u.UserName == User.Identity.Name
                        select c;

(Spot the part with db.Users instead of db.AspNetUsers)


问:
Why is my Post method not working?
Sorry in advance if this is a really stupid mistake, but I appreciate any help that can be given.

This is the code that initialise that data in the form. They are radio buttons that are populated via an SQL database.

```<code> echo "<form method='post' action='home.php'>";
$result = queryMySQL("SELECT Name FROM Quotees");
if ($result->num_rows == 0) {
    $error = "<span class='error'>No people can be found</span><br><br>";
} else {
    $numrow = $result->num_rows;
    for ($count = 1; $count <= $numrow; $count++) {
        $row = $result->fetch_array(MYSQLI_ASSOC);
        $name = stripslashes($row['Name']);
        echo '<input type="radio" name="choice" value="' . $name . '"  />' . $name;
        echo '<br>';
    }
}
</code>```

Later on in the code I try to access the value picked using the POST method, as follows:

```<code>$personPicked = stripslashes($_POST["choice"]);
if ($person === $personPicked) {
    //code
} else {
    echo "wrong answer";
}
</code>```

The error I receive is "Undefined index: choice" on the line where the POST method is called.

I submit the form using the following code out side of the php segment as HTML code

```<code><div class="confirmButton">
<form action="home.php">
    <input type="submit" value="Confirm">
</form>
</code>```

Thanks for any help you can give as to why my code isn't working/how I can go about solving the problem.

答:
The submit button is in a different form.

When you click it, you submit the form that does not include the radio buttons.

You need to put the submit button and the radio buttons in the same form.

Title: Why is my Post method not working?

Body:
Sorry in advance if this is a really stupid mistake, but I appreciate any help that can be given.

This is the code that initialise that data in the form. They are radio buttons that are populated via an SQL database.

 echo "<form method='post' action='home.php'>";
$result = queryMySQL("SELECT Name FROM Quotees");
if ($result->num_rows == 0) {
    $error = "No people can be found

";
} else {
    $numrow = $result->num_rows;
    for ($count = 1; $count <= $numrow; $count++) {
        $row = $result->fetch_array(MYSQLI_ASSOC);
        $name = stripslashes($row['Name']);
        echo '<input type="radio" name="choice" value="' . $name . '"  />' . $name;
        echo '
';
    }
}

Later on in the code I try to access the value picked using the POST method, as follows:

$personPicked = stripslashes($_POST["choice"]);
if ($person === $personPicked) {
    //code
} else {
    echo "wrong answer";
}

The error I receive is "Undefined index: choice" on the line where the POST method is called.

I submit the form using the following code out side of the php segment as HTML code

<form action="home.php">
    <input type="submit" value="Confirm">
</form>

Thanks for any help you can give as to why my code isn't working/how I can go about solving the problem.


问:
Android Firefox webextension copy to Clipboard
I am trying to copy a text from firefox android browser, fire an intent and read the system clipboard but in vain.

Does the Clipboard wherein firefox webextension copy differ from the Android system clipboard?
If so, is there any other way?

Also, what are the possible ways of transferring a large blob data from browser to the app. I am currently passing it via intent uri.

答: It seems to me that the firefox's clipboard is not different than android's. I can tell it since I use Clip Stack app and it shows text copied from firefox too. This app is open source and maybe you can find how to handle your case by having a look at its code.


答:
Cause you are missing c_bpartner table reference in FROM clause. Your query is total wired .. not sure why you need that UNION at all cause you are not using any of the column from that UNION result set. You probably would just perform a JOIN between the table like

```<code>select m_product.name ,
c_bpartner.name
from m_product
join c_bpartner on m_product.id = c_bpartner.id;
</code>```

Title: sql missing from clause

Body:
Cause you are missing c_bpartner table reference in FROM clause. Your query is total wired .. not sure why you need that UNION at all cause you are not using any of the column from that UNION result set. You probably would just perform a JOIN between the table like

select m_product.name ,
c_bpartner.name
from m_product
join c_bpartner on m_product.id = c_bpartner.id;


答:
This statement should select each product with a count of ocurrances and do the same for bpartner.</p>

```<code>      SELECT m_product.name
            ,COUNT(m_product.name)
        FROM m_product
    GROUP BY m_product.name
UNION ALL
      SELECT c_bpartner.name
            ,COUNT(c_bpartner.name)
        FROM c_bpartner
    GROUP BY c_bpartner.name
</code>```

Title: sql missing from clause

Body:
This statement should select each product with a count of ocurrances and do the same for bpartner.

      SELECT m_product.name
            ,COUNT(m_product.name)
        FROM m_product
    GROUP BY m_product.name
UNION ALL
      SELECT c_bpartner.name
            ,COUNT(c_bpartner.name)
        FROM c_bpartner
    GROUP BY c_bpartner.name


问:
WPF UserControl component grid definition issue
I have simple UserControl with two columns and in first column I have DataGrid:

```<code><UserControl x:Class="Caliburn_SimpleInjector_Sample.ViewModel.ShellView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             MinWidth="1100" MinHeight="400">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width=".20*" />
            <ColumnDefinition Width="5" />
            <ColumnDefinition Width=".70*" />
        </Grid.ColumnDefinitions>
        <DataGrid Grid.Row="0" Grid.Column="0" ItemsSource="{Binding Path=Tasks, Mode=OneWay}"
                  SelectedItem="{Binding SelectedTask}"
                  AutoGenerateColumns="False" IsReadOnly="True"
                  CanUserResizeRows="False" GridLinesVisibility="None"
                  SelectionUnit="FullRow"
                  RowHeaderWidth="0"
                  FontSize="14">
            <DataGrid.CellStyle>
                <Style TargetType="DataGridCell">
                    <Setter Property="BorderThickness" Value="0" />
                    <Setter Property="FocusVisualStyle" Value="{x:Null}" />
                </Style>
            </DataGrid.CellStyle>
            <DataGrid.Columns>
                <DataGridTextColumn Header="Col 1" Binding="{Binding Find}" />
                <DataGridTextColumn Header="Col 2" Binding="{Binding Action}" />
                <DataGridTextColumn Header="Col 3" Binding="{Binding Status}" />
            </DataGrid.Columns>
        </DataGrid>

        <GridSplitter Grid.Row="0" Grid.Column="1"
                      VerticalAlignment="Stretch"
                      ResizeBehavior="PreviousAndNext"
                      Width="5" Background="#FFBCBCBC" />

        <StackPanel Grid.Row="0" Grid.Column="2" Background="Red"></StackPanel>
    </Grid>
</UserControl>
</code>```

Let's take a look what we have:

Perfect! That's exactly what I need.

But! If I just try to set dynamic Width for each column inside of DataGrid, the whole template becomes broken:

```<code><DataGrid.Columns>
    <DataGridTextColumn Width="0.2*" Header="Col 1 20%" Binding="{Binding Find}" />
    <DataGridTextColumn Width="0.2*" Header="Col 2 20%" Binding="{Binding Action}" />
    <DataGridTextColumn Width="0.6*" Header="Col 3 60%" Binding="{Binding Status}" />
</DataGrid.Columns>
</code>```

And here is the result:

And also one interesting thing. If you try to start resize the window - then all becomes normal, example:
ScreenCast

Could someone assist me with this issue?

Thanks in advance.

答:
Issue is not related to Caliburn. Exact the same issue described here: Window SizeToContent issue when child UserControl has grid with Column of max Width.

I fixed my problem in the same way as proposed here: fix.

Body:
I have simple UserControl with two columns and in first column I have DataGrid:

<UserControl x:Class="Caliburn_SimpleInjector_Sample.ViewModel.ShellView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             MinWidth="1100" MinHeight="400">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width=".20*" />
            <ColumnDefinition Width="5" />
            <ColumnDefinition Width=".70*" />
        </Grid.ColumnDefinitions>
        <DataGrid Grid.Row="0" Grid.Column="0" ItemsSource="{Binding Path=Tasks, Mode=OneWay}"
                  SelectedItem="{Binding SelectedTask}"
                  AutoGenerateColumns="False" IsReadOnly="True"
                  CanUserResizeRows="False" GridLinesVisibility="None"
                  SelectionUnit="FullRow"
                  RowHeaderWidth="0"
                  FontSize="14">
            <DataGrid.CellStyle>

            </DataGrid.CellStyle>
            <DataGrid.Columns>
                <DataGridTextColumn Header="Col 1" Binding="{Binding Find}" />
                <DataGridTextColumn Header="Col 2" Binding="{Binding Action}" />
                <DataGridTextColumn Header="Col 3" Binding="{Binding Status}" />
            </DataGrid.Columns>
        </DataGrid>

        <GridSplitter Grid.Row="0" Grid.Column="1"
                      VerticalAlignment="Stretch"
                      ResizeBehavior="PreviousAndNext"
                      Width="5" Background="#FFBCBCBC" />

        <StackPanel Grid.Row="0" Grid.Column="2" Background="Red"></StackPanel>
    </Grid>
</UserControl>

Let's take a look what we have:

Perfect! That's exactly what I need.

But! If I just try to set dynamic Width for each column inside of DataGrid, the whole template becomes broken:

<DataGrid.Columns>
    <DataGridTextColumn Width="0.2*" Header="Col 1 20%" Binding="{Binding Find}" />
    <DataGridTextColumn Width="0.2*" Header="Col 2 20%" Binding="{Binding Action}" />
    <DataGridTextColumn Width="0.6*" Header="Col 3 60%" Binding="{Binding Status}" />
</DataGrid.Columns>

And here is the result:

And also one interesting thing. If you try to start resize the window - then all becomes normal, example:
ScreenCast

Could someone assist me with this issue?

Thanks in advance.


问:
Validate checkbox using JavaScript.
I would like some help with checkbox validation.

If you look in below picture, when user click the image, the checkbox becomes selected.

What I would want is if all checkbox are selected alert an simple message.

This is a code to select checkbox by clicking on an image.

```<code>        $( document ).ready(function() {

    $("#roll-<?php echo $row['id_vnr']; ?><?php echo $cut_counter; ?>").click (function(){
         var $$ = $(this)

          if( !$$.is('.checked')){
              $$.addClass('checked');

              $('#imgCheck-<?php echo $row['id_vnr']; ?><?php echo $cut_counter; ?>').prop('checked', true);

                }
            });
    });
</code>```

So I can select check box by clicking on an image. How I can alert message if all check box are selected. Soon user click last picture, the picture will disappear, the red tick box will appear and user should see alert message.

Thank you in advance.

答:
Try this way:

var checkboxes = $('[type="checkbox"]');
checkboxes.on('change', function() {
  var checked = $('[type="checkbox"]:checked');

  console.log('all:', checkboxes.length, ' / ', 'checked:', checked.length);

  if (checkboxes.length === checked.length) {
    console.log('ALL CHECKED!');
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox">1
<input type="checkbox">2
<input type="checkbox">3</code>```

Title: Validate checkbox using JavaScript.

Body:
I would like some help with checkbox validation.

If you look in below picture, when user click the image, the checkbox becomes selected.

What I would want is if all checkbox are selected alert an simple message.

This is a code to select checkbox by clicking on an image.

        $( document ).ready(function() {

    $("#roll-<?php echo $row['id_vnr']; ?><?php echo $cut_counter; ?>").click (function(){
         var $$ = $(this)

          if( !$$.is('.checked')){
              $$.addClass('checked');

              $('#imgCheck-<?php echo $row['id_vnr']; ?><?php echo $cut_counter; ?>').prop('checked', true);

                }
            });
    });

So I can select check box by clicking on an image. How I can alert message if all check box are selected. Soon user click last picture, the picture will disappear, the red tick box will appear and user should see alert message.

Thank you in advance.

Body:
Try this way:

var checkboxes = $('[type="checkbox"]');
checkboxes.on('change', function() {
  var checked = $('[type="checkbox"]:checked');

  console.log('all:', checkboxes.length, ' / ', 'checked:', checked.length);

  if (checkboxes.length === checked.length) {
    console.log('ALL CHECKED!');
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox">1
<input type="checkbox">2
<input type="checkbox">3


问:
Whether progressive web app supports offline on desktop? If no why?
I am interested in developing a progressive web app.I want to know whether it supports offline in desktop.</p>

答:
Desktop browsers support the Cache API just as mobile ones.

You can check here: https://jakearchibald.github.io/isserviceworkerready/#caches


问:
Template Parse error in HTML code
I'm getting these errors when I run my Ionic 2 HTML code :
Template parse errors: Unexpected closing tag "form" " Submit [ERROR ->]
Unexpected closing tag "ion-content"" Home Page</button> --> [ERROR ->] "

Here is my HTML code :

```<code><ion-content>
    <ion-title (click)="showAlert()">
        Sign Up
    </ion-title>
    <form #userForm = "ngForm" (ngSubmit)="onSubmit(userForm.value)">
        <div>
          <ion-label color="primary">Enter Username</ion-label>
          <ion-input type="text" required #usernameRef="ngModel"  class="form-control" placeholder="Username" ngModel></ion-input>
          <div [hidden]=" usernameRef.valid || usernameRef.pristine ">
           Please enter username
          </div>
        </div>
        <div>
          <ion-label color="primary">Enter Password</ion-label>
          <ion-input type="text" required #passRef="ngModel"  class="form-control" placeholder="Password" ngModel></ion-input>
          <div [hidden]=" passRef.valid || passRef.pristine ">
           Please enter password
          </div>
        </div>
        <div>
           <ion-label color="primary">Re-enter Password</ion-label>
          <ion-input type="text" required #repassRef="ngModel"  class="form-control" placeholder="Re-enter Password" ngModel></ion-input>
          <div [hidden]=" repassRef.valid || repassRef.pristine ">
           Please re-enter password
          </div>
        </div>
        <div>
           <ion-label color="primary">Enter Email Address</ion-label>
          <ion-input type="text" required #emailRef="ngModel"  class="form-control" placeholder="example@email.com" ngModel></ion-input>
          <div [hidden]=" emailRef.valid || emailRef.pristine ">
           Please enter email
          </div>
        </div>
        <div>
           <ion-label color="primary">Enter Phone Number</ion-label>
          <ion-input type="text" required #numRef="ngModel"  class="form-control" placeholder="+91-7022-51-074" ngModel></ion-input>
          <div [hidden]=" numRef.valid || numRef.pristine ">
           Please enter phone number
          </div>
        </div>
           <ion-label color="primary">Enter Country</ion-label>
          <ion-input type="text" required #conRef="ngModel"  class="form-control" placeholder="United States" ngModel></ion-input>
          <div [hidden]=" conRef.valid || conRef.pristine ">
           Please enter country
          </div>
        <div>
        <button type="submit">Submit</button>
    </form>
     <button ion-button (click)="goBack()">Home Page</button>
</ion-content>
</code>```

Why am I getting that error ? How do I fix it?

答:
It seems like you are missing an opening for one of your div's. Try this: </p>

```<code><div>
   <ion-label color="primary">Enter Country</ion-label>
   <ion-input type="text" required #conRef="ngModel"  class="form-control" placeholder="United States" ngModel></ion-input>
   <div [hidden]=" conRef.valid || conRef.pristine ">
        Please enter country
    </div>
 <div>
</code>```

Title: Template Parse error in HTML code

Body:
I'm getting these errors when I run my Ionic 2 HTML code :
Template parse errors: Unexpected closing tag "form" " Submit [ERROR ->]
Unexpected closing tag "ion-content"" Home Page</button> --> [ERROR ->] "

Here is my HTML code :

<ion-content>
    <ion-title (click)="showAlert()">
        Sign Up
    </ion-title>
    <form #userForm = "ngForm" (ngSubmit)="onSubmit(userForm.value)">

          <ion-label color="primary">Enter Username</ion-label>
          <ion-input type="text" required #usernameRef="ngModel"  class="form-control" placeholder="Username" ngModel></ion-input>

           Please enter username

          <ion-label color="primary">Enter Password</ion-label>
          <ion-input type="text" required #passRef="ngModel"  class="form-control" placeholder="Password" ngModel></ion-input>

           Please enter password

           <ion-label color="primary">Re-enter Password</ion-label>
          <ion-input type="text" required #repassRef="ngModel"  class="form-control" placeholder="Re-enter Password" ngModel></ion-input>

           Please re-enter password

           <ion-label color="primary">Enter Email Address</ion-label>
          <ion-input type="text" required #emailRef="ngModel"  class="form-control" placeholder="example@email.com" ngModel></ion-input>

           Please enter email

           <ion-label color="primary">Enter Phone Number</ion-label>
          <ion-input type="text" required #numRef="ngModel"  class="form-control" placeholder="+91-7022-51-074" ngModel></ion-input>

           Please enter phone number

           <ion-label color="primary">Enter Country</ion-label>
          <ion-input type="text" required #conRef="ngModel"  class="form-control" placeholder="United States" ngModel></ion-input>

           Please enter country

        <button type="submit">Submit</button>
    </form>
     <button ion-button (click)="goBack()">Home Page</button>
</ion-content>

Why am I getting that error ? How do I fix it?

Body:
It seems like you are missing an opening for one of your div's. Try this:

<div>
   <ion-label color="primary">Enter Country</ion-label>
   <ion-input type="text" required #conRef="ngModel"  class="form-control" placeholder="United States" ngModel></ion-input>
   <div [hidden]=" conRef.valid || conRef.pristine ">
        Please enter country
    </div>
 <div>


问:
Process the command without launching MainActivity, in Android
I am new to android and stuck at one point with my new screen off test application. I am trying to develop an Android application to turn off or lock the screen directly by clicking the app launcher icon of the application.

I am able to lock the screen with the functionality I want but with one problem. While i click on the screen lock icon in the launcher it takes around a second and then locks the screen (Time is taken by to MainActivity to launch).

I want that time delay to be removed and just wanted to process the command to lock phone when user tap on the app icon in the launcher. But am not able to figure it out.

Here is AndroidManifest.xml

```<code><application
    android:theme="@android:style/Theme.NoDisplay"
    android:label="@string/app_name"
    android:icon="@drawable/ic_launcher"
    android:allowBackup="true">

    <activity android:name=".MainActivity"
        android:excludeFromRecents="true"
        android:launchMode="singleTask">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver android:name="ScreenOffAdminReceiver"
        android:permission="android.permission.BIND_DEVICE_ADMIN">
        <meta-data android:name="android.app.device_admin"
            android:resource="@xml/permissions" />
        <intent-filter>
            <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
        </intent-filter>
    </receiver>

</application>
</code>```

MainActivity.java

```<code>public class MainActivity extends Activity {

    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        DevicePolicyManager deviceManger = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
        ComponentName compName = new ComponentName(this, ScreenOffAdminReceiver.class);
        if (deviceManger.isAdminActive(compName)) {
            deviceManger.lockNow();
            finish();
        } else {
            Intent intent = new Intent("android.app.action.ADD_DEVICE_ADMIN");
            intent.putExtra("android.app.extra.DEVICE_ADMIN", compName);
            intent.putExtra("android.app.extra.ADD_EXPLANATION", getString(R.string.devicePolicyManagerMsg));
            startActivityForResult(intent, 0);
        }
        Process.killProcess(Process.myPid());
    }
}
</code>```

ScreenOffAdminReceiver.java

```<code>public class ScreenOffAdminReceiver extends DeviceAdminReceiver {
    public void onDisabled(Context context, Intent intent) {
        Toast.makeText(context, R.string.deviceAdminDisabled, Toast.LENGTH_SHORT).show();
    }

    public void onEnabled(Context context, Intent intent) {
        Toast.makeText(context, R.string.deviceAdminEnabled, Toast.LENGTH_SHORT).show();
    }
}
</code>```

permissions.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-policies>
        <force-lock />
    </uses-policies>
</device-admin>
</code>```

I just want to remove the DELAY while locking the screen. Any help will be highly appreciated. Thanks

答:
I think this will help you out.</p>

```<code>public class MainActivity extends AppCompatActivity {

    DevicePolicyManager deviceManger;
    ComponentName compName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        deviceManger = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE);
        compName = new ComponentName(this, ScreenOffAdminReceiver.class);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (deviceManger.isAdminActive(compName)) {
            deviceManger.lockNow();
            finish();
        } else {
            Intent intent = new Intent("android.app.action.ADD_DEVICE_ADMIN");
            intent.putExtra("android.app.extra.DEVICE_ADMIN", compName);
            intent.putExtra("android.app.extra.ADD_EXPLANATION", "Device Policies");
            startActivityForResult(intent, 0);
        }
    }
}
</code>```

Body:
I am new to android and stuck at one point with my new screen off test application. I am trying to develop an Android application to turn off or lock the screen directly by clicking the app launcher icon of the application.

I am able to lock the screen with the functionality I want but with one problem. While i click on the screen lock icon in the launcher it takes around a second and then locks the screen (Time is taken by to MainActivity to launch).

I want that time delay to be removed and just wanted to process the command to lock phone when user tap on the app icon in the launcher. But am not able to figure it out.

Here is AndroidManifest.xml

<application
    android:theme="@android:style/Theme.NoDisplay"
    android:label="@string/app_name"
    android:icon="@drawable/ic_launcher"
    android:allowBackup="true">

    <activity android:name=".MainActivity"
        android:excludeFromRecents="true"
        android:launchMode="singleTask">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver android:name="ScreenOffAdminReceiver"
        android:permission="android.permission.BIND_DEVICE_ADMIN">
        <meta-data android:name="android.app.device_admin"
            android:resource="@xml/permissions" />
        <intent-filter>
            <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
        </intent-filter>
    </receiver>

</application>

MainActivity.java

public class MainActivity extends Activity {

    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        DevicePolicyManager deviceManger = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
        ComponentName compName = new ComponentName(this, ScreenOffAdminReceiver.class);
        if (deviceManger.isAdminActive(compName)) {
            deviceManger.lockNow();
            finish();
        } else {
            Intent intent = new Intent("android.app.action.ADD_DEVICE_ADMIN");
            intent.putExtra("android.app.extra.DEVICE_ADMIN", compName);
            intent.putExtra("android.app.extra.ADD_EXPLANATION", getString(R.string.devicePolicyManagerMsg));
            startActivityForResult(intent, 0);
        }
        Process.killProcess(Process.myPid());
    }
}

ScreenOffAdminReceiver.java

public class ScreenOffAdminReceiver extends DeviceAdminReceiver {
    public void onDisabled(Context context, Intent intent) {
        Toast.makeText(context, R.string.deviceAdminDisabled, Toast.LENGTH_SHORT).show();
    }

    public void onEnabled(Context context, Intent intent) {
        Toast.makeText(context, R.string.deviceAdminEnabled, Toast.LENGTH_SHORT).show();
    }
}

permissions.xml

<?xml version="1.0" encoding="utf-8"?>
<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-policies>
        <force-lock />
    </uses-policies>
</device-admin>

I just want to remove the DELAY while locking the screen. Any help will be highly appreciated. Thanks

Body:
I think this will help you out.

public class MainActivity extends AppCompatActivity {

    DevicePolicyManager deviceManger;
    ComponentName compName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        deviceManger = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE);
        compName = new ComponentName(this, ScreenOffAdminReceiver.class);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (deviceManger.isAdminActive(compName)) {
            deviceManger.lockNow();
            finish();
        } else {
            Intent intent = new Intent("android.app.action.ADD_DEVICE_ADMIN");
            intent.putExtra("android.app.extra.DEVICE_ADMIN", compName);
            intent.putExtra("android.app.extra.ADD_EXPLANATION", "Device Policies");
            startActivityForResult(intent, 0);
        }
    }
}


问:
Unique values of two columns for pandas dataframe
Suppose I have pandas data frame with 2 columns:

```<code>df: Col1  Col2
      1     1
      1     2
      1     2
      1     2
      3     4
      3     4
</code>```

Then I want to keep only the unique couple values (col1, col2) of these two columns and give their frequncy:

```<code>df2: Col1  Col2  Freq
      1     1     1
      1     2     3
      3     4     2
</code>```

I think to use df['Col1', 'Col2'].value_counts() but it works only for one column.
Does it exist a function to deal with many columns?

答:
You need groupby + size + Series.reset_index:

```<code>df = df.groupby(['Col1', 'Col2']).size().reset_index(name='Freq')
print (df)
   Col1  Col2  Freq
0     1     1     1
1     1     2     3
2     3     4     2
</code>```

Body:
Suppose I have pandas data frame with 2 columns:

df: Col1  Col2
      1     1
      1     2
      1     2
      1     2
      3     4
      3     4

Then I want to keep only the unique couple values (col1, col2) of these two columns and give their frequncy:

df2: Col1  Col2  Freq
      1     1     1
      1     2     3
      3     4     2

I think to use df['Col1', 'Col2'].value_counts() but it works only for one column.
Does it exist a function to deal with many columns?

Body:
You need groupby + size + Series.reset_index:

df = df.groupby(['Col1', 'Col2']).size().reset_index(name='Freq')
print (df)
   Col1  Col2  Freq
0     1     1     1
1     1     2     3
2     3     4     2

ContentLicense: CC BY-SA 4.0


问:
OpenCV Hog person detect is fooled by vertical lines?
I've been testing openCV on an RPi using Python. The video is coming from a USB grabber from a CCTV camera.

I tested it in a room with 'ideal' stick figures and it worked great, tracking and zoom automatically.

However when testing in the real world, the first test location has a corrugated roof in view and the vertical lines of the roof always get detected as a person.

I was very surprised by this as the HoG detection seemed quite robust against bushes, trees and other optically jumbled images. A series of vertical lines seems to catch it out every time.

Why might this be?

Do I need to look at trying to re-train it? I would imagine this would be quite a task!

Has anyone else found this issue?

Maybe I should try and pre-filter the vertical lines out of the image?

Having a person tracker that can't cope with fences or roofs is a bit of a limitation!

答:
Having false positives after just a single training session is common and should be expected. You should now record all these false positives and use them for hard negative training. That is, you would add these false positives in the negative training set. Once you perform a hard negative training, your model should perform much better and the number of false positives will reduce.

Understanding why the fence and other edges shows up as a false positive is a bit complicated to explain and is better explained by the many articles and the original HOG paper by Dalal and Triggs, which I would highly recommend.


问:
Reach redux state from static function
I have a React Native application where I have a class which name is Helpers. These are a set of application related static helper function. Mostly I call them like Helpers.functionName(). What is the best way to reach the redux store from this static method? I want to modify it and read it.

I have the Helpers like this:

```<code>class Helpers extends Component {
  static getState(){
    return state;
  }
}
</code>```

I tried to use the connect, but inside the getState function the this.props is undefined.

答:
One way would be to pass store as argument to each static function that requires it. Or you could make store global variable and access it as such.

I would hesitate though to describe any of those ways as best, or use any other positive adjective for that matter. Redux can be used in many ways, but I think intention was to discourage store access as global.

Also note that changing the store directly from your helper functions is a whole another level of no-no. Intention of redux is that only reducer functions change state in response to dispatched actions.

Lastly, is Helpers really a component that you are using, or just container for bunch of static functions? If later, than it is probably misleading to derive it from Component.

Title: Reach redux state from static function

Body:
I have a React Native application where I have a class which name is Helpers. These are a set of application related static helper function. Mostly I call them like Helpers.functionName(). What is the best way to reach the redux store from this static method? I want to modify it and read it.

I have the Helpers like this:

class Helpers extends Component {
  static getState(){
    return state;
  }
}

I tried to use the connect, but inside the getState function the this.props is undefined.


答:
I found the option to enable all the breakpoints by one click. I don't understand why this was not in the Debug menu.

It is in Debug window -> BREAKPOINTS -> right click to see this option. Refer picture.

 is

Title: How to enable all disabled breakpoints in visual studio code

Body: Does anyone know how to enable all the disabled breakpoints in visual studio code (v1.13). There is an option to disable breakpoints in one click. But I couldn't find any option to enable all the breakpoints. As of now I am enabling breakpoint one by one.


问:
Create an admin user programmatically in WordPress
Recently I had a client come to me to build a new website. They had also forgotten all their login details, but they did have FTP access.

How do you create an admin user programmatically in WordPress?

答:
Here is the queries to create a new admin user :

```<code>INSERT INTO wp_users (user_login, user_pass, user_nicename, user_email, user_status) VALUES ('newadmin', MD5('pass123'), 'firstname lastname', 'email@example.com', '0');

INSERT INTO wp_usermeta (umeta_id, user_id, meta_key, meta_value) VALUES (NULL, (Select max(id) FROM wp_users), 'wp_capabilities', 'a:1:{s:13:"administrator";s:1:"1";}');

INSERT INTO wp_usermeta (umeta_id, user_id, meta_key, meta_value) VALUES (NULL, (Select max(id) FROM wp_users), 'wp_user_level', '10');
</code>```

Body:
Here is the queries to create a new admin user :

INSERT INTO wp_users (user_login, user_pass, user_nicename, user_email, user_status) VALUES ('newadmin', MD5('pass123'), 'firstname lastname', 'email@example.com', '0');

INSERT INTO wp_usermeta (umeta_id, user_id, meta_key, meta_value) VALUES (NULL, (Select max(id) FROM wp_users), 'wp_capabilities', 'a:1:{s:13:"administrator";s:1:"1";}');

INSERT INTO wp_usermeta (umeta_id, user_id, meta_key, meta_value) VALUES (NULL, (Select max(id) FROM wp_users), 'wp_user_level', '10');


问:
How to convert to C# a code to calculate a Distance and Bearing from google maps api
When I'm using Google Maps on Android I create a method to take a point A and calculate if it is inside of an area of 1km to the point B :

```<code>float[] results = new float[1];
Location.distanceBetween(centerLatitude, centerLongitude, testLatitude,
testLongitude, results);
float distanceInMeters = results[0];
boolean isWithin10km = distanceInMeters < 10000;
</code>```

But I need to to this inside of my API, so I send a Location(Lat,Long) to my Server, I get a list of locations and try to make a match and them return something, the problem is, how to "unwrap" the code so I could switch to C#!

I founf the implementation of it, but it has some proper classes that I'm sure it doesn't exist in C#! here

答:
I would reccomend that you use the assembly Sysetem.Device.Location (you can download a nugetpackage if you don't have it on your machine from here).

Then you can do the following using the GeoCoordinate class:

```<code>var geo1=new GeoCoordinate(centerLatitude, centerLongitude);
var geo2=new GeoCoordinate(testLatitude, testLongitude):
var result=geo1.GetDistanceTo(geo2);
</code>```

For more information, please visit the documentation at MSDN.

Body:
When I'm using Google Maps on Android I create a method to take a point A and calculate if it is inside of an area of 1km to the point B :

float[] results = new float[1];
Location.distanceBetween(centerLatitude, centerLongitude, testLatitude,
testLongitude, results);
float distanceInMeters = results[0];
boolean isWithin10km = distanceInMeters < 10000;

But I need to to this inside of my API, so I send a Location(Lat,Long) to my Server, I get a list of locations and try to make a match and them return something, the problem is, how to "unwrap" the code so I could switch to C#!

I founf the implementation of it, but it has some proper classes that I'm sure it doesn't exist in C#! here

Body:
I would reccomend that you use the assembly Sysetem.Device.Location (you can download a nugetpackage if you don't have it on your machine from here).

Then you can do the following using the GeoCoordinate class:

var geo1=new GeoCoordinate(centerLatitude, centerLongitude);
var geo2=new GeoCoordinate(testLatitude, testLongitude):
var result=geo1.GetDistanceTo(geo2);

For more information, please visit the documentation at MSDN.


问:
Python - what is difference in os.popen and subprocess.Popen?
Python - what is difference in os.popen and subprocess.Popen?</p>

答:
The os process functionality is considered obsolete. The subprocess module was introduced in Python 2.4 as a unified, more powerful replacement for several older modules and functions related to subprocesses. They are listed here:

os.system

os.spawn*

os.popen*

popen2.*

commands.*

os.popen was deprecated in Python 2.6 (but, interestingly, it is not deprecated in Python 3, where it is implemented in terms of subprocess.Popen). There is a paragraph in the documentation on how to replace it with subprocess.Popen.

OwnerDisplayName: sam

OwnerDisplayName: Felix Dombek


问:
webpack require.ensure first parameter use
What is the use of first parameter of webpack require.ensure first parameter?

https://webpack.github.io/docs/code-splitting.html

```<code>require.ensure(dependencies, callback)
</code>```

I tried to let the first parameter filled or empty like:

```<code>require.ensure(['./module'], function() {  //filled first param

require.ensure([], function() {  //empty first param
  let module = require('./module');
  $ocLazyLoad.load([{
    name: module.default,
  }]);
});
</code>```

Both are working. So what is the use of the first parameter?

There is also a require.include function in the documentation which I do not understand the use case of this function. Can anyone explain it too?

答:
The first parameter is rarely useful. To learn why it is there and causes confusion, please see my another answer.

Comply with the spec

One use case for the first parameter could be to specify all dependencies for clarity and to comply with the spec. But that's completely optional.

Add modules to chunks to make the chunks similar

Consider you have two split points in different parts of an app. The first split point depends on module a, the second depends on modules a and b.
To eliminate the risk of downloading a twice, you could decide to place both modules into a single chunk:

```<code>// First split point
require.ensure(['b'], (require) => {
  require('a');
});
</code>```

Pull modules into parent chunks

Consider the following code splitting scenario:

```<code>require.ensure([], (require) => {
  ...
  require.ensure([], (require) => {
    require('a');
    require('b');
  });

  require.ensure([], (require) => {
    require('a');
    require('c');
  });
  ...
});
</code>```

In this case, module a will end up in both nested chunks. If at least one of the nested chunks is frequently loaded, you could decide to move a into the parent chunk:

```<code>require.ensure(['a'], (require) => {
  ...
</code>```

Add modules to chunks with require.include

Consider the previous example. There is another way to pull a into the parent chunk:

```<code>require.ensure([], (require) => {
  require.include('a');
  ...
</code>```

In this particular example, both solutions are equivalent and there is no advantage in using require.include. However, if you don't have access to the split point's code, parent chunk is an entry chunk or you use the modern import() syntax, require.include is your only choice.

It is possible to pull modules into chunks using synchronous require or import. The advantage of require.include is that it only loads modules and doesn't evaluate them. This could be useful to defer modules' evaluation if it is expensive or depends on the application state, e.g., requires polyfills to be loaded, DOM nodes to be present, etc.

Body:
What is the use of first parameter of webpack require.ensure first parameter?

https://webpack.github.io/docs/code-splitting.html

require.ensure(dependencies, callback)

I tried to let the first parameter filled or empty like:

require.ensure(['./module'], function() {  //filled first param

require.ensure([], function() {  //empty first param
  let module = require('./module');
  $ocLazyLoad.load([{
    name: module.default,
  }]);
});

Both are working. So what is the use of the first parameter?

There is also a require.include function in the documentation which I do not understand the use case of this function. Can anyone explain it too?

Body:
The first parameter is rarely useful. To learn why it is there and causes confusion, please see my another answer.

Comply with the spec

One use case for the first parameter could be to specify all dependencies for clarity and to comply with the spec. But that's completely optional.

Add modules to chunks to make the chunks similar

Consider you have two split points in different parts of an app. The first split point depends on module a, the second depends on modules a and b.
To eliminate the risk of downloading a twice, you could decide to place both modules into a single chunk:

// First split point
require.ensure(['b'], (require) => {
  require('a');
});

Pull modules into parent chunks

Consider the following code splitting scenario:

require.ensure([], (require) => {
  ...
  require.ensure([], (require) => {
    require('a');
    require('b');
  });

  require.ensure([], (require) => {
    require('a');
    require('c');
  });
  ...
});

In this case, module a will end up in both nested chunks. If at least one of the nested chunks is frequently loaded, you could decide to move a into the parent chunk:

require.ensure(['a'], (require) => {
  ...

Add modules to chunks with require.include

Consider the previous example. There is another way to pull a into the parent chunk:

require.ensure([], (require) => {
  require.include('a');
  ...

In this particular example, both solutions are equivalent and there is no advantage in using require.include. However, if you don't have access to the split point's code, parent chunk is an entry chunk or you use the modern import() syntax, require.include is your only choice.

It is possible to pull modules into chunks using synchronous require or import. The advantage of require.include is that it only loads modules and doesn't evaluate them. This could be useful to defer modules' evaluation if it is expensive or depends on the application state, e.g., requires polyfills to be loaded, DOM nodes to be present, etc.


问:
Selenium returns unknownProtocolFound error
I'm trying to download an APK file from [this GooglePlay direct link generator][1] using Firefox Webdriver, Selenium and Python.

The problem is that, when Selenium is trying to get the home page, it crashes with the following error message:

```<code>/usr/bin/python2.7 /home/ghasemi/PycharmProjects/phorcys_watcher/main.py
http://apps.evozi.com/apk-downloader/?id=com.instagram.android
Traceback (most recent call last):
  File "/home/ghasemi/PycharmProjects/phorcys_watcher/main.py", line 7, in <module>
    content = google_play_download("com.instagram.android")
  File "/home/ghasemi/PycharmProjects/phorcys_watcher/collector.py", line 20, in google_play_download
    browser.get("https://apps.evozi.com/apk-downloader/?id=" + app_page_id)
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 268, in get
    self.execute(Command.GET, {'url': url})
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 256, in execute
    self.error_handler.check_response(response)
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 194, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: Reached error page: about:neterror?e=unknownProtocolFound&u=httpss%3A//www.adnetworkperformance.com/script/java.php%3Foption%3Drotateur%26r%3D411313%26treqn%3D1025813717%26runauction%3D1%26crr%3D168ce9d76b1a6695b12e%2CwcwHrNzGnshFns2PnM3bbcwGW8xLz-mNycwuvZjurZja3MzJfMxG_9xMX4wYns7a2YxHvshBL9xe3shbjN2J7umN6umNm-mNuN2czNw723956800778f24b2db6%26rtid%3D595b6ecb8ac19%26cbrandom%3D0.7519066097934798%26cbtitle%3DAPK%2520Downloader%2520%255BLatest%255D%2520Download%2520Directly%2520%257C%2520Chrome%2520Extension%2520v3%2520%28Evozi%2520Official%29%26cbiframe%3D0%26cbWidth%3D1280%26cbHeight%3D717%26cbdescription%3DDownload%2520APKs%2520Directly%2520From%2520Google%2520Play%2520To%2520Your%2520Computer%2520With%2520APK%2520Downloader%2520Extension%2520For%2520Google%2520Chrome%26cbkeywords%3D%26cbref%3D&c=&f=regular&d=Firefox%20doesn%E2%80%99t%20know%20how%20to%20open%20this%20address%2C%20because%20one%20of%20the%20following%20protocols%20%28httpss%29%20isn%E2%80%99t%20associated%20with%20any%20program%20or%20is%20not%20allowed%20in%20this%20context.
</code>```

The exception throws on this line:
    browser.get("https://apps.evozi.com/apk-downloader/?id=com.instagram.android")

As you see above, the origin of this error is a wrong link in the page that selenium is trying to download it. I found the frame that cause this error:

```<code><iframe width="468" height="60" marginwidth="0" marginheight="0" vspace="0" hspace="0" allowtransparency="true" allowfullscreen="true" style="border: medium none; padding: 0; margin: 0;" sandbox="allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-pointer-lock allow-same-origin" id="595b6e88086f8" frameborder="0" src="httpss://www.adnetworkperformance.com/script/java.php?option=rotateur&r=411313&treqn=501505383&runauction=1&crr=fc25086f39dc3c58bbdbGJTJyVGZh9Gbud3bk1yawFmRyUSbvNmLpp3b2VmLzBHchZkMlYkMlE0MlMHc0RHa2dfe473f7c304fd8fb65&rtid=595b6e88086f8&cbrandom=0.6676681852413189&cbtitle=APK%20Downloader%20%5BLatest%5D%20Download%20Directly%20%7C%20Chrome%20Extension%20v3%20(Evozi%20Official)&cbiframe=0&cbWidth=1522&cbHeight=741&cbdescription=Download%20APKs%20Directly%20From%20Google%20Play%20To%20Your%20Computer%20With%20APK%20Downloader%20Extension%20For%20Google%20Chrome&cbkeywords=&cbref=" scrolling="no"></iframe>
</code>```

As you can see, the webpage developer put httpss instead of https wrongly (twice!).

How can I handle this problem?

Update:

My scraper:

```<code>import requests
from lxml import html
from pyvirtualdisplay import Display
from selenium import webdriver

def google_play_download(app_page_id):
    browser = webdriver.Firefox()
    browser.get("https://apps.evozi.com/apk-downloader/?id=" + app_page_id)
    browser.find_element_by_css_selector(".btn.btn-primary.btn-lg.btn-block").click()
    apk_link = browser.find_element_by_css_selector(".btn.btn-success.btn-block").get_attribute('href')
    browser.quit()
    for rnd in range(5):
        resp = requests.get(apk_link)
        if resp.headers['Content-Length'] == str(len(resp.content)):
            return resp.content

if __name__ == "__main__":
    content = google_play_download("com.instagram.android")
    f = open('./file', 'wb')
    f.write(content)
    f.close()

  [1]: https://apps.evozi.com/apk-downloader/
</code>```

答:
you were almost there...</p>

```<code>import requests
import time
from selenium import webdriver

def google_play_download(app_page_id):
    browser = webdriver.Chrome()
    browser.get("https://apps.evozi.com/apk-downloader/?id=" + app_page_id)
    browser.find_element_by_css_selector(".btn.btn-primary.btn-lg.btn-block").click()
    time.sleep(10)

    apk_link = browser.find_element_by_css_selector(".btn.btn-success.btn-block").get_attribute('href')
    browser.quit()
    for rnd in range(5):
        resp = requests.get(apk_link)
        if resp.headers['Content-Length'] == str(len(resp.content)):
            return resp.content

if __name__ == "__main__":
    content = google_play_download("com.instagram.android")
    f = open('file.apk', 'wb')
    f.write(content)
    f.close()
</code>```

Body:
I'm trying to download an APK file from [this GooglePlay direct link generator][1] using Firefox Webdriver, Selenium and Python.

The problem is that, when Selenium is trying to get the home page, it crashes with the following error message:

/usr/bin/python2.7 /home/ghasemi/PycharmProjects/phorcys_watcher/main.py
http://apps.evozi.com/apk-downloader/?id=com.instagram.android
Traceback (most recent call last):
  File "/home/ghasemi/PycharmProjects/phorcys_watcher/main.py", line 7, in <module>
    content = google_play_download("com.instagram.android")
  File "/home/ghasemi/PycharmProjects/phorcys_watcher/collector.py", line 20, in google_play_download
    browser.get("https://apps.evozi.com/apk-downloader/?id=" + app_page_id)
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 268, in get
    self.execute(Command.GET, {'url': url})
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 256, in execute
    self.error_handler.check_response(response)
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 194, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: Reached error page: about:neterror?e=unknownProtocolFound&u=httpss%3A//www.adnetworkperformance.com/script/java.php%3Foption%3Drotateur%26r%3D411313%26treqn%3D1025813717%26runauction%3D1%26crr%3D168ce9d76b1a6695b12e%2CwcwHrNzGnshFns2PnM3bbcwGW8xLz-mNycwuvZjurZja3MzJfMxG_9xMX4wYns7a2YxHvshBL9xe3shbjN2J7umN6umNm-mNuN2czNw723956800778f24b2db6%26rtid%3D595b6ecb8ac19%26cbrandom%3D0.7519066097934798%26cbtitle%3DAPK%2520Downloader%2520%255BLatest%255D%2520Download%2520Directly%2520%257C%2520Chrome%2520Extension%2520v3%2520%28Evozi%2520Official%29%26cbiframe%3D0%26cbWidth%3D1280%26cbHeight%3D717%26cbdescription%3DDownload%2520APKs%2520Directly%2520From%2520Google%2520Play%2520To%2520Your%2520Computer%2520With%2520APK%2520Downloader%2520Extension%2520For%2520Google%2520Chrome%26cbkeywords%3D%26cbref%3D&c=&f=regular&d=Firefox%20doesn%E2%80%99t%20know%20how%20to%20open%20this%20address%2C%20because%20one%20of%20the%20following%20protocols%20%28httpss%29%20isn%E2%80%99t%20associated%20with%20any%20program%20or%20is%20not%20allowed%20in%20this%20context.

The exception throws on this line:
    browser.get("https://apps.evozi.com/apk-downloader/?id=com.instagram.android")

As you see above, the origin of this error is a wrong link in the page that selenium is trying to download it. I found the frame that cause this error:

<iframe width="468" height="60" marginwidth="0" marginheight="0" vspace="0" hspace="0" allowtransparency="true" allowfullscreen="true" style="border: medium none; padding: 0; margin: 0;" sandbox="allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-pointer-lock allow-same-origin" id="595b6e88086f8" frameborder="0" src="httpss://www.adnetworkperformance.com/script/java.php?option=rotateur&r=411313&treqn=501505383&runauction=1&crr=fc25086f39dc3c58bbdbGJTJyVGZh9Gbud3bk1yawFmRyUSbvNmLpp3b2VmLzBHchZkMlYkMlE0MlMHc0RHa2dfe473f7c304fd8fb65&rtid=595b6e88086f8&cbrandom=0.6676681852413189&cbtitle=APK%20Downloader%20%5BLatest%5D%20Download%20Directly%20%7C%20Chrome%20Extension%20v3%20(Evozi%20Official)&cbiframe=0&cbWidth=1522&cbHeight=741&cbdescription=Download%20APKs%20Directly%20From%20Google%20Play%20To%20Your%20Computer%20With%20APK%20Downloader%20Extension%20For%20Google%20Chrome&cbkeywords=&cbref=" scrolling="no">

As you can see, the webpage developer put httpss instead of https wrongly (twice!).

How can I handle this problem?

Update:

My scraper:

import requests
from lxml import html
from pyvirtualdisplay import Display
from selenium import webdriver

def google_play_download(app_page_id):
    browser = webdriver.Firefox()
    browser.get("https://apps.evozi.com/apk-downloader/?id=" + app_page_id)
    browser.find_element_by_css_selector(".btn.btn-primary.btn-lg.btn-block").click()
    apk_link = browser.find_element_by_css_selector(".btn.btn-success.btn-block").get_attribute('href')
    browser.quit()
    for rnd in range(5):
        resp = requests.get(apk_link)
        if resp.headers['Content-Length'] == str(len(resp.content)):
            return resp.content

if __name__ == "__main__":
    content = google_play_download("com.instagram.android")
    f = open('./file', 'wb')
    f.write(content)
    f.close()

  [1]: https://apps.evozi.com/apk-downloader/

Body:
you were almost there...

import requests
import time
from selenium import webdriver

def google_play_download(app_page_id):
    browser = webdriver.Chrome()
    browser.get("https://apps.evozi.com/apk-downloader/?id=" + app_page_id)
    browser.find_element_by_css_selector(".btn.btn-primary.btn-lg.btn-block").click()
    time.sleep(10)

    apk_link = browser.find_element_by_css_selector(".btn.btn-success.btn-block").get_attribute('href')
    browser.quit()
    for rnd in range(5):
        resp = requests.get(apk_link)
        if resp.headers['Content-Length'] == str(len(resp.content)):
            return resp.content

if __name__ == "__main__":
    content = google_play_download("com.instagram.android")
    f = open('file.apk', 'wb')
    f.write(content)
    f.close()


问:
Select the maximum/minimum from n previous rows in a DataFrame
I'm using pandas in Python and I have an issue to select some data. I have DataFrame with float values, and I would like to create a column which contains the maximum (or minimum) of the n previous rows of a column, and set to 0 for the n first rows, here's an example of the result I would like to have:

```<code>df_test = pd.DataFrame({'a':[2,7,2,0,-1, 19, -52, 2]})
df_test['result_i_want_with_n=3'] = [0, 0, 0, 7, 7, 2, 19, 19]
print(df_test)
    a   result_i_want_with_n=3
0   2   0
1   7   0
2   2   0
3   0   7
4   -1  7
5   19  2
6   -52 19
7   2   19
</code>```

I managed to get this result using a while, but I would like to program it in a more "pandas" way to gain computation speed.

Thanks

答:
Rolling is your friend here. You need to shift by one row in order to get your exact result, otherwise your first value will be in the third row.</p>

```<code>df_test.rolling(window=3).max().shift(1).fillna(0)

0     0.0
1     0.0
2     0.0
3     7.0
4     7.0
5     2.0
6    19.0
7    19.0
</code>```

Body:
I'm using pandas in Python and I have an issue to select some data. I have DataFrame with float values, and I would like to create a column which contains the maximum (or minimum) of the n previous rows of a column, and set to 0 for the n first rows, here's an example of the result I would like to have:

df_test = pd.DataFrame({'a':[2,7,2,0,-1, 19, -52, 2]})
df_test['result_i_want_with_n=3'] = [0, 0, 0, 7, 7, 2, 19, 19]
print(df_test)
    a   result_i_want_with_n=3
0   2   0
1   7   0
2   2   0
3   0   7
4   -1  7
5   19  2
6   -52 19
7   2   19

I managed to get this result using a while, but I would like to program it in a more "pandas" way to gain computation speed.

Thanks

Body:
Rolling is your friend here. You need to shift by one row in order to get your exact result, otherwise your first value will be in the third row.

df_test.rolling(window=3).max().shift(1).fillna(0)

0     0.0
1     0.0
2     0.0
3     7.0
4     7.0
5     2.0
6    19.0
7    19.0


问:
What are the ordering guarantees of AIDL "oneway" remote calls?
AIDL methods and interfaces marked with the "oneway" keyword are asynchronous Binder calls for remote processes, and it is said that the ordering of the calls is not guaranteed. On the other hand, the last comment of Dianne Hackborn (author of Binder) in this thread (
https://groups.google.com/forum/#!topic/android-developers/FFY-hg2Jx0M) says:

"ordering of delivery is tied to the target object (so you can receive calls on different
  interfaces out of order)"

Which seems to suggest, that calls to the same interface keep their order.

Can anyone clarify this?

答: AIDL calls are synchronous by default which means the client will be in waiting state until method returns but in case we use "oneway" keyword,the method call is asynchronous i.e it returns immediately and client will receive callback later.Hence,the ordering is not defined for callbacks.</p>


问:
Error : BinderProxy@45d459c0 is not valid; is your activity running?
What is this error... i haven't found any discussion on this error in the stackoverflow community Detailed :-</p>

```<code>10-18 23:53:11.613: ERROR/AndroidRuntime(3197): Uncaught handler: thread main exiting due to uncaught exception
10-18 23:53:11.658: ERROR/AndroidRuntime(3197): android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@45d459c0 is not valid; is your activity running?
10-18 23:53:11.658: ERROR/AndroidRuntime(3197):     at android.view.ViewRoot.setView(ViewRoot.java:468)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197):     at android.view.Window$LocalWindowManager.addView(Window.java:424)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197):     at android.app.Dialog.show(Dialog.java:239)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197):     at com.vishal.contacte.Locationlistener$MyLocationListener.onLocationChanged(Locationlistener.java:86)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197):     at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:179)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197):     at android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:112)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197):     at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:128)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197):     at android.os.Handler.dispatchMessage(Handler.java:99)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197):     at android.os.Looper.loop(Looper.java:123)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197):     at android.app.ActivityThread.main(ActivityThread.java:4363)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197):     at java.lang.reflect.Method.invokeNative(Native Method)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197):     at java.lang.reflect.Method.invoke(Method.java:521)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:862)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197):     at dalvik.system.NativeStart.main(Native Method)
</code>```

答:
I faced the same problem and used the code proposed by DiscDev above with minor changes as follows:</p>

```<code>if (!MainActivity.this.isFinishing()){
    alertDialog.show();
}
</code>```

Body:
What is this error... i haven't found any discussion on this error in the stackoverflow community Detailed :-

10-18 23:53:11.613: ERROR/AndroidRuntime(3197): Uncaught handler: thread main exiting due to uncaught exception
10-18 23:53:11.658: ERROR/AndroidRuntime(3197): android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@45d459c0 is not valid; is your activity running?
10-18 23:53:11.658: ERROR/AndroidRuntime(3197):     at android.view.ViewRoot.setView(ViewRoot.java:468)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197):     at android.view.Window$LocalWindowManager.addView(Window.java:424)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197):     at android.app.Dialog.show(Dialog.java:239)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197):     at com.vishal.contacte.Locationlistener$MyLocationListener.onLocationChanged(Locationlistener.java:86)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197):     at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:179)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197):     at android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:112)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197):     at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:128)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197):     at android.os.Handler.dispatchMessage(Handler.java:99)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197):     at android.os.Looper.loop(Looper.java:123)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197):     at android.app.ActivityThread.main(ActivityThread.java:4363)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197):     at java.lang.reflect.Method.invokeNative(Native Method)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197):     at java.lang.reflect.Method.invoke(Method.java:521)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:862)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197):     at dalvik.system.NativeStart.main(Native Method)

Body:
I faced the same problem and used the code proposed by DiscDev above with minor changes as follows:

if (!MainActivity.this.isFinishing()){
    alertDialog.show();
}


问:
EJB 3.0 Interface class extending Serializable throwing cannot marshal EJB parameters
One of my POJO class is implementing an interface which extends Serializable

My doubt is, As we cant include serialVersionUID in interface class can it result in Cannot Marshal EJB parameters Exception?

答:
You can not pass ,,an interface" as parameter of java method. You can only pass an instance of some class, that implements such interface. That class will be marked as Serializable due to abstraction hierarchy.  The Serializable interface is a marker interface, and your implementation class will be serializable even if it does not declare the serialVersionUid attribute(However, it is strongly recommended that you do declare the serialVersionUID).

So to answer your question: as long as the particular instance you pass to your EJB method is marked as serializable it will be fine.


问:
Using C# to get the Public Key from my cert for Java
Without BounceyCastle.

I have my cert, and the GetPublicKey() value is not what the Java side of the house needs.

The cert if an X509Certificate2 object, using DSA encryption. Created using makecert

Convert.ToBase64String(cert.GetPublicKey()) returns

```<code>AoGAeaKLPS4ktxULg3YQL0ePphF08tKsddZtv3SDERa8b8go5h3AxmWjuDd8y9dIzZFe8KDjY9Lg
JU4JOA27snO3fCsPAVkmJ0O2pbxn+wzT7oij2FOLcCAjnFNNsoaWrtMv+I4XXl18DyDQLFkZiPx9
2UyuDzoQTGxgCrPccQPjUgY=
</code>```

Convert.ToBase64String(cert.RawData) returns

```<code>MIICxjCCAoagAwIBAgIQbdIpaaU9rZdA+wJKA+mUfDAJBgcqhkjOOAQDMBYxFDASBgNVBAMTC0RT
QSBSb290IENBMB4XDTEzMDExMDE3MTAzNVoXDTM5MTIzMTIzNTk1OVowFDESMBAGA1UEAxMJVXNl
ciBOYW1lMIIBtzCCASwGByqGSM44BAEwggEfAoGBALWn4Iyvn7LFkV9ULoZtwJ8J1c+ibsbhjPiw
+xUgRW2LAZV2/Lv89W1jCprNkf87tN/ogMT/1VSIOo7ff/tqVRTWPVJ1ZMrR9VOnF2k/Sorg8Cmr
sAClsSWrACKIwK2XKJGWTU4oMLxvYcu85+yQ4nWLofgA/+WARrJ/rk2aUSZ3AhUAlqPLNh6JZkpD
G/OXKzhsZFUiDrkCgYEAoICjHltWOgN8/2uyAaMTNrBuJfi/HM9AWe5B8m9HDfl1K6Qx2Ni6tbYP
uFtvHdGnoqqn46l7eY+xjpi5GEydvkPtAQKmTDGcSh6vtnTeNV15Hafg5pXUKw1OisIr/bpx/KIk
cgCtSo6qC5IhDzeZXnfJYcE+8U+O6hEr5dwByN4DgYQAAoGAeaKLPS4ktxULg3YQL0ePphF08tKs
ddZtv3SDERa8b8go5h3AxmWjuDd8y9dIzZFe8KDjY9LgJU4JOA27snO3fCsPAVkmJ0O2pbxn+wzT
7oij2FOLcCAjnFNNsoaWrtMv+I4XXl18DyDQLFkZiPx92UyuDzoQTGxgCrPccQPjUgajWTBXMAwG
A1UdEwEB/wQCMAAwRwYDVR0BBEAwPoAQmhMLkJ/cPXGitvGMB81tZaEYMBYxFDASBgNVBAMTC0RT
QSBSb290IENBghDCpMJ75zgZokJVlZmNq/LTMAkGByqGSM44BAMDLwAwLAIUYUALM9WhgwzRMj1y
MSdoparmYvICFFxLgFr2ow3NGTkqWvHIXtjO9R0G
</code>```

However, when my Java counterpart gets the public key, using the same cert file, gets

```<code>$ cat david-509.cer | openssl x509 -pubkey
-----BEGIN PUBLIC KEY-----
MIIBtzCCASwGByqGSM44BAEwggEfAoGBALWn4Iyvn7LFkV9ULoZtwJ8J1c+ibsbh
jPiw+xUgRW2LAZV2/Lv89W1jCprNkf87tN/ogMT/1VSIOo7ff/tqVRTWPVJ1ZMrR
9VOnF2k/Sorg8CmrsAClsSWrACKIwK2XKJGWTU4oMLxvYcu85+yQ4nWLofgA/+WA
RrJ/rk2aUSZ3AhUAlqPLNh6JZkpDG/OXKzhsZFUiDrkCgYEAoICjHltWOgN8/2uy
AaMTNrBuJfi/HM9AWe5B8m9HDfl1K6Qx2Ni6tbYPuFtvHdGnoqqn46l7eY+xjpi5
GEydvkPtAQKmTDGcSh6vtnTeNV15Hafg5pXUKw1OisIr/bpx/KIkcgCtSo6qC5Ih
DzeZXnfJYcE+8U+O6hEr5dwByN4DgYQAAoGAeaKLPS4ktxULg3YQL0ePphF08tKs
ddZtv3SDERa8b8go5h3AxmWjuDd8y9dIzZFe8KDjY9LgJU4JOA27snO3fCsPAVkm
J0O2pbxn+wzT7oij2FOLcCAjnFNNsoaWrtMv+I4XXl18DyDQLFkZiPx92UyuDzoQ
TGxgCrPccQPjUgY=
-----END PUBLIC KEY-----
</code>```

And thus my problem. How do I get this value from my cert?

Thanks!

答:
You should use cert.PublicKey.EncodedKeyValue instead of cert.GetPublicKey().

EncodedKeyValue provides ASN1 encoded value, not raw key data as GetPublicKey().

So you can use this code

```<code>void ExportPublicKey(X509Certificate2 cert, string filePath)
{
    byte[] encodedPublicKey = cert.PublicKey.EncodedKeyValue.RawData;
    File.WriteAllLines(filePath, new[] {
        "-----BEGIN PUBLIC KEY-----",
        Convert.ToBase64String(encodedPublicKey, Base64FormattingOptions.InsertLineBreaks),
        "-----END PUBLIC KEY-----",
    });
}
</code>```

Body:
Without BounceyCastle.

I have my cert, and the GetPublicKey() value is not what the Java side of the house needs.

The cert if an X509Certificate2 object, using DSA encryption. Created using makecert

Convert.ToBase64String(cert.GetPublicKey()) returns

AoGAeaKLPS4ktxULg3YQL0ePphF08tKsddZtv3SDERa8b8go5h3AxmWjuDd8y9dIzZFe8KDjY9Lg
JU4JOA27snO3fCsPAVkmJ0O2pbxn+wzT7oij2FOLcCAjnFNNsoaWrtMv+I4XXl18DyDQLFkZiPx9
2UyuDzoQTGxgCrPccQPjUgY=

Convert.ToBase64String(cert.RawData) returns

MIICxjCCAoagAwIBAgIQbdIpaaU9rZdA+wJKA+mUfDAJBgcqhkjOOAQDMBYxFDASBgNVBAMTC0RT
QSBSb290IENBMB4XDTEzMDExMDE3MTAzNVoXDTM5MTIzMTIzNTk1OVowFDESMBAGA1UEAxMJVXNl
ciBOYW1lMIIBtzCCASwGByqGSM44BAEwggEfAoGBALWn4Iyvn7LFkV9ULoZtwJ8J1c+ibsbhjPiw
+xUgRW2LAZV2/Lv89W1jCprNkf87tN/ogMT/1VSIOo7ff/tqVRTWPVJ1ZMrR9VOnF2k/Sorg8Cmr
sAClsSWrACKIwK2XKJGWTU4oMLxvYcu85+yQ4nWLofgA/+WARrJ/rk2aUSZ3AhUAlqPLNh6JZkpD
G/OXKzhsZFUiDrkCgYEAoICjHltWOgN8/2uyAaMTNrBuJfi/HM9AWe5B8m9HDfl1K6Qx2Ni6tbYP
uFtvHdGnoqqn46l7eY+xjpi5GEydvkPtAQKmTDGcSh6vtnTeNV15Hafg5pXUKw1OisIr/bpx/KIk
cgCtSo6qC5IhDzeZXnfJYcE+8U+O6hEr5dwByN4DgYQAAoGAeaKLPS4ktxULg3YQL0ePphF08tKs
ddZtv3SDERa8b8go5h3AxmWjuDd8y9dIzZFe8KDjY9LgJU4JOA27snO3fCsPAVkmJ0O2pbxn+wzT
7oij2FOLcCAjnFNNsoaWrtMv+I4XXl18DyDQLFkZiPx92UyuDzoQTGxgCrPccQPjUgajWTBXMAwG
A1UdEwEB/wQCMAAwRwYDVR0BBEAwPoAQmhMLkJ/cPXGitvGMB81tZaEYMBYxFDASBgNVBAMTC0RT
QSBSb290IENBghDCpMJ75zgZokJVlZmNq/LTMAkGByqGSM44BAMDLwAwLAIUYUALM9WhgwzRMj1y
MSdoparmYvICFFxLgFr2ow3NGTkqWvHIXtjO9R0G

However, when my Java counterpart gets the public key, using the same cert file, gets

$ cat david-509.cer | openssl x509 -pubkey
-----BEGIN PUBLIC KEY-----
MIIBtzCCASwGByqGSM44BAEwggEfAoGBALWn4Iyvn7LFkV9ULoZtwJ8J1c+ibsbh
jPiw+xUgRW2LAZV2/Lv89W1jCprNkf87tN/ogMT/1VSIOo7ff/tqVRTWPVJ1ZMrR
9VOnF2k/Sorg8CmrsAClsSWrACKIwK2XKJGWTU4oMLxvYcu85+yQ4nWLofgA/+WA
RrJ/rk2aUSZ3AhUAlqPLNh6JZkpDG/OXKzhsZFUiDrkCgYEAoICjHltWOgN8/2uy
AaMTNrBuJfi/HM9AWe5B8m9HDfl1K6Qx2Ni6tbYPuFtvHdGnoqqn46l7eY+xjpi5
GEydvkPtAQKmTDGcSh6vtnTeNV15Hafg5pXUKw1OisIr/bpx/KIkcgCtSo6qC5Ih
DzeZXnfJYcE+8U+O6hEr5dwByN4DgYQAAoGAeaKLPS4ktxULg3YQL0ePphF08tKs
ddZtv3SDERa8b8go5h3AxmWjuDd8y9dIzZFe8KDjY9LgJU4JOA27snO3fCsPAVkm
J0O2pbxn+wzT7oij2FOLcCAjnFNNsoaWrtMv+I4XXl18DyDQLFkZiPx92UyuDzoQ
TGxgCrPccQPjUgY=
-----END PUBLIC KEY-----

And thus my problem. How do I get this value from my cert?

Thanks!

Body:
You should use cert.PublicKey.EncodedKeyValue instead of cert.GetPublicKey().

EncodedKeyValue provides ASN1 encoded value, not raw key data as GetPublicKey().

So you can use this code

void ExportPublicKey(X509Certificate2 cert, string filePath)
{
    byte[] encodedPublicKey = cert.PublicKey.EncodedKeyValue.RawData;
    File.WriteAllLines(filePath, new[] {
        "-----BEGIN PUBLIC KEY-----",
        Convert.ToBase64String(encodedPublicKey, Base64FormattingOptions.InsertLineBreaks),
        "-----END PUBLIC KEY-----",
    });
}


问:
How to close ng-bootstrap modal
bootstrap in my angular 2 project. I have two buttons in my modal as well. Each button have a callback function as well. How can I implement modal close or call modal close from the button? Went through the document but, felt quiet hard to understand.

The following is my button config:

```<code>private _modalConfig: any = {
        title: 'Are you sure you want to delete this Lesson?',
        button: [{
            text: 'Delete',
            class: 'btn-delete',
            callback: ()=>{
                            console.log(event);
                            alert('this is Delete');
                          }
        },
        {
            text: 'Cancel',
            class: 'btn-cancel',
            callback: ()=>{
                            event.preventDefault();
                            alert('this is Cancel');
                          }
        }]
    }
</code>```

答:
If you are using ModalDirective, of ng2-bootstrap, then the proper method is

.hide(), which allows to manually close the modal.

Title: How to close ng-bootstrap modal

Body:
bootstrap in my angular 2 project. I have two buttons in my modal as well. Each button have a callback function as well. How can I implement modal close or call modal close from the button? Went through the document but, felt quiet hard to understand.

The following is my button config:

private _modalConfig: any = {
        title: 'Are you sure you want to delete this Lesson?',
        button: [{
            text: 'Delete',
            class: 'btn-delete',
            callback: ()=>{
                            console.log(event);
                            alert('this is Delete');
                          }
        },
        {
            text: 'Cancel',
            class: 'btn-cancel',
            callback: ()=>{
                            event.preventDefault();
                            alert('this is Cancel');
                          }
        }]
    }


问:
Pandas — match last identical row and compute difference
With a DataFrame like the following:

```<code>         timestamp    value
0       2012-01-01      3.0
1       2012-01-05      3.0
2       2012-01-06      6.0
3       2012-01-09      3.0
4       2012-01-31      1.0
5       2012-02-09      3.0
6       2012-02-11      1.0
7       2012-02-13      3.0
8       2012-02-15      2.0
9       2012-02-18      5.0
</code>```

What would be an elegant and efficient way to add a time_since_last_identical column, so that the previous example would result in:

```<code>         timestamp    value   time_since_last_identical
0       2012-01-01      3.0                         NaT
1       2012-01-05      3.0                      5 days
2       2012-01-06      6.0                         NaT
3       2012-01-09      3.0                      4 days
4       2012-01-31      1.0                         NaT
5       2012-02-09      3.0                     31 days
6       2012-02-11      1.0                     10 days
7       2012-02-13      3.0                      4 days
8       2012-02-15      2.0                         NaT
9       2012-02-18      5.0                         NaT
</code>```

The important part of the problem is not necessarily the usage of time delays. Any solution that matches one particular row with the previous row of identical value, and computes something out of those two rows (here, a difference) will be valid.

Note: not interested in apply or loop-based approaches.

Body:
With a DataFrame like the following:

         timestamp    value
0       2012-01-01      3.0
1       2012-01-05      3.0
2       2012-01-06      6.0
3       2012-01-09      3.0
4       2012-01-31      1.0
5       2012-02-09      3.0
6       2012-02-11      1.0
7       2012-02-13      3.0
8       2012-02-15      2.0
9       2012-02-18      5.0

What would be an elegant and efficient way to add a time_since_last_identical column, so that the previous example would result in:

         timestamp    value   time_since_last_identical
0       2012-01-01      3.0                         NaT
1       2012-01-05      3.0                      5 days
2       2012-01-06      6.0                         NaT
3       2012-01-09      3.0                      4 days
4       2012-01-31      1.0                         NaT
5       2012-02-09      3.0                     31 days
6       2012-02-11      1.0                     10 days
7       2012-02-13      3.0                      4 days
8       2012-02-15      2.0                         NaT
9       2012-02-18      5.0                         NaT

The important part of the problem is not necessarily the usage of time delays. Any solution that matches one particular row with the previous row of identical value, and computes something out of those two rows (here, a difference) will be valid.

Note: not interested in apply or loop-based approaches.

Body:
A simple, clean and elegant groupby will do the trick:

df['time_since_last_identical'] = df.groupby('value').diff()

Gives:

   timestamp  value  time_since_last_identical
0 2012-01-01    3.0                        NaT
1 2012-01-05    3.0                     4 days
2 2012-01-06    6.0                        NaT
3 2012-01-09    3.0                     4 days
4 2012-01-31    1.0                        NaT
5 2012-02-09    3.0                    31 days
6 2012-02-11    1.0                    11 days
7 2012-02-13    3.0                     4 days
8 2012-02-15    2.0                        NaT
9 2012-02-18    5.0                        NaT


问:
How to slide down div AND its contents after scrolling
(read carefully twitchy trigger finger downvoters)

I am trying to get a div AND its contents to slide down after scrolling to a certain point. I have looked extensively, but I have only been able to locate how to slide down the div, however its contents are static. In other words, the div slides down to reveal its contents, but its contents do NOT slide.

Here is the JsFiddle is used...

http://jsfiddle.net/BinaryMuse/Ehney/1/

CSS...

```<code>body {
    height: 10000px;
}

.fixedDiv {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
}

header {
    height: 300px;
    border: 1px solid black;
}
</code>```

JAVASCRIPT

```<code>// Get the headers position from the top of the page, plus its own height
var startY = 500;

$(window).scroll(function(){
    checkY();
});

function checkY(){
    if( $(window).scrollTop() > startY ){
        $('.fixedDiv').slideDown();
    }else{
        $('.fixedDiv').slideUp();
    }
}

// Do this on load just in case the user starts half way down the page
checkY();
</code>```

As you can see, the content of the div does not move. Only the div itself. I need the content to MOVE down WITH the div, NOT to only be revealed by a moving div.

答:
You can use class and transition to change the position of the div to make it look like its coming down

See working example:

// Get the headers position from the top of the page, plus its own height
var startY = 500;

$(window).scroll(function() {
  checkY();
});

function checkY() {
  if ($(window).scrollTop() > startY) {
    $('.fixedDiv').addClass("slide");
  } else {
    $('.fixedDiv').removeClass("slide");
  }
}

// Do this on load just in case the user starts half way down the page
checkY();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  height: 10000px;
}

.fixedDiv {
  visibility: hidden;
  position: fixed;
  top: -10px;
  left: -0;
  transition: all .5s;
}

.slide {
  visibility: visible;
  top: 0;
}

header {
  height: 300px;
  border: 1px solid black;
}</code>```

Here is a fixed div.

Here is the header! It is kinda tall to demonstrate...```

Body:
(read carefully twitchy trigger finger downvoters)

I am trying to get a div AND its contents to slide down after scrolling to a certain point. I have looked extensively, but I have only been able to locate how to slide down the div, however its contents are static. In other words, the div slides down to reveal its contents, but its contents do NOT slide.

Here is the JsFiddle is used...

http://jsfiddle.net/BinaryMuse/Ehney/1/

CSS...

body {
    height: 10000px;
}

.fixedDiv {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
}

header {
    height: 300px;
    border: 1px solid black;
}

JAVASCRIPT

// Get the headers position from the top of the page, plus its own height
var startY = 500;

$(window).scroll(function(){
    checkY();
});

function checkY(){
    if( $(window).scrollTop() > startY ){
        $('.fixedDiv').slideDown();
    }else{
        $('.fixedDiv').slideUp();
    }
}

// Do this on load just in case the user starts half way down the page
checkY();

As you can see, the content of the div does not move. Only the div itself. I need the content to MOVE down WITH the div, NOT to only be revealed by a moving div.

Body:
You can use class and transition to change the position of the div to make it look like its coming down

See working example:

// Get the headers position from the top of the page, plus its own height
var startY = 500;

$(window).scroll(function() {
  checkY();
});

function checkY() {
  if ($(window).scrollTop() > startY) {
    $('.fixedDiv').addClass("slide");
  } else {
    $('.fixedDiv').removeClass("slide");
  }
}

// Do this on load just in case the user starts half way down the page
checkY();

body {
  height: 10000px;
}

.fixedDiv {
  visibility: hidden;
  position: fixed;
  top: -10px;
  left: -0;
  transition: all .5s;
}

.slide {
  visibility: visible;
  top: 0;
}

header {
  height: 300px;
  border: 1px solid black;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class='fixedDiv'>Here is a fixed div.</div>
<header>Here is the header! It is kinda tall to demonstrate...</header>


问:
Identify empty string in Perl
There is probably an easy solution to this, but I can't figure it out. I am looking to:

take a CSV file into an array

loop through the array and split fields into variables

if the array field is empty then set the variable to "N/A"

Note: It is only setting the $variable to "N/A" that I cannot get working.

For example:

```<code>foreach $var (@list) {

($name,$date,$size, etc...)=split(/,\"/,$var);

}
</code>```

How would I set $date to "N/A" if the field in the array is empty?

so to produce:

```<code>$name = Jim
$date = N/A
$size = small
</code>```

I hope this makes sense and is easy to fix.
-Thanks

答:
As far as your third bullet point and the actual question: to check for emptiness:

For empty string, you can either do the above-mentioned eq "", or you can check the string length: $var = "N/A" unless length($var);;

For an undefined of empty string, in Perl 5.10 you can use the "defined-or" (//) operator to do the short version: $var = "N/A" unless length($var // '');

In Perl before 5.10 where "defined-or" is not available, you will either have to spell out the defined check: $var = "N/A" unless defined $var && length($var);

... or, you can just stop caring about undefined warnings by turning them off (h/t brian d foy):

```<code>no warnings 'uninitialized';
$_ = "N/A" unless length($_) foreach ($name,$date,$size, etc...);
use warnings 'uninitialized'; # Always turn back on.
</code>```

However, please note that you also should consider a different approach to the first two bullet points. Implementing your own CSV parser which is 100% correct is not trivial - for example, your sample code will break if any of the fields contain a double quote.

Instead, you should always use one of the standard Perl CSV parsers, such as Text::CSV_XS.

Title: Identify empty string in Perl

Body:
There is probably an easy solution to this, but I can't figure it out. I am looking to:

take a CSV file into an array

loop through the array and split fields into variables

if the array field is empty then set the variable to "N/A"

Note: It is only setting the $variable to "N/A" that I cannot get working.

For example:

foreach $var (@list) {

($name,$date,$size, etc...)=split(/,\"/,$var);

}

How would I set $date to "N/A" if the field in the array is empty?

so to produce:

$name = Jim
$date = N/A
$size = small

I hope this makes sense and is easy to fix.
-Thanks

Body:
As far as your third bullet point and the actual question: to check for emptiness:

For empty string, you can either do the above-mentioned eq "", or you can check the string length: $var = "N/A" unless length($var);;

For an undefined of empty string, in Perl 5.10 you can use the "defined-or" (//) operator to do the short version: $var = "N/A" unless length($var // '');

In Perl before 5.10 where "defined-or" is not available, you will either have to spell out the defined check: $var = "N/A" unless defined $var && length($var);

... or, you can just stop caring about undefined warnings by turning them off (h/t brian d foy):

no warnings 'uninitialized';
$_ = "N/A" unless length($_) foreach ($name,$date,$size, etc...);
use warnings 'uninitialized'; # Always turn back on.

However, please note that you also should consider a different approach to the first two bullet points. Implementing your own CSV parser which is 100% correct is not trivial - for example, your sample code will break if any of the fields contain a double quote.

Instead, you should always use one of the standard Perl CSV parsers, such as Text::CSV_XS.


问:
HTML5 show download button in firefox for embedded audio, video
As seen in new Google Chrome updates, we can see the download button for embedded audio/video in HTML pages. I want to show the same in Firefox & edge browsers.
How can I achieve this? </p>

答:
you can't have the same exact thing unless you create it yourself and disable the download button for Chrome so it'd look consistent in all browsers.

      .download{
height: 45px;
 width: 45px;
 position: relative;
 top: -30px;
 left:-55px;
      }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<video width="400" controls>
  <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
  <source src="https://www.w3schools.com/html/mov_bbb.ogg" type="video/ogg">
</video>
<img class="download" src='https://cdn1.iconfinder.com/data/icons/hawcons/32/698392-icon-129-cloud-download-128.png'/>.
</div></code>```

Body:
you can't have the same exact thing unless you create it yourself and disable the download button for Chrome so it'd look consistent in all browsers.

      .download{
height: 45px;
 width: 45px;
 position: relative;
 top: -30px;
 left:-55px;
      }

<div class="container">
<video width="400" controls>
  <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
  <source src="https://www.w3schools.com/html/mov_bbb.ogg" type="video/ogg">
</video>
<a href="https://www.w3schools.com/html/mov_bbb.mp4" target="_blank" download><img class="download" src='https://cdn1.iconfinder.com/data/icons/hawcons/32/698392-icon-129-cloud-download-128.png'/></a>.
</div>


问:
Document Generation with template in Enterprise Architect with an Add-In C#
I am working on an Enterprise Architect Add-In in C# in Visual Studio Express 2013 to make documentations for a single element/elements in a package. I made a template in EA with the help of the Document Generator, where i want to write some of the element's properties on the output. Example:

```<code>package >
element >
Name: {Element.Name}... more attributes of the element
< element
< package
</code>```

The problem is that when i use my Add-In to generate the document the output will be like this:

package >

Name: Random TestName

< package

between package > < package is blank, and as default the document should not contain these fields in the output, how can i make it disappear? I tried to fill between the package fields with something like {Pkg.Version}, but i only get this text in the output, not the value of it. In the Document Template Designer under Sections window if i check "Element" box it checks the "Package" box too, but if i try to uncheck the "Package" it unchecks the "Element" too - any suggestions how can i make it work?
My Add-In works like this:

```<code>EA.Element element = repository.GetTreeSelectedObject();
int elementID = element.ElementID;
EA.DocumentGenerator docGen = repository.CreateDocumentGenerator();
docGen.NewDocument("");
docGen.InsertTemplate("RandomTemp");
docGen.DocumentElement(elementID, 2, "RandomTemp"); // gets the element by ID
docGen.SaveDocument("DOCUMENT.pdf", EA.DocumentType.dtPDF);
</code>```

+: that would work for me either if i can reach somehow the package properties of the element too.

Thanks in advance.

Tamas

答:
docGen.insertTemplate prints out your template as is, without filling in the fields. Remove that line of code and it should be fine

The document will generate the report following your template just fine with the following line of code you put: docGen.DocumentElement(elementID, 2, "RandomTemp");

Body:
I am working on an Enterprise Architect Add-In in C# in Visual Studio Express 2013 to make documentations for a single element/elements in a package. I made a template in EA with the help of the Document Generator, where i want to write some of the element's properties on the output. Example:

package >
element >
Name: {Element.Name}... more attributes of the element
< element
< package

The problem is that when i use my Add-In to generate the document the output will be like this:

package >

Name: Random TestName

< package

between package > < package is blank, and as default the document should not contain these fields in the output, how can i make it disappear? I tried to fill between the package fields with something like {Pkg.Version}, but i only get this text in the output, not the value of it. In the Document Template Designer under Sections window if i check "Element" box it checks the "Package" box too, but if i try to uncheck the "Package" it unchecks the "Element" too - any suggestions how can i make it work?
My Add-In works like this:

EA.Element element = repository.GetTreeSelectedObject();
int elementID = element.ElementID;
EA.DocumentGenerator docGen = repository.CreateDocumentGenerator();
docGen.NewDocument("");
docGen.InsertTemplate("RandomTemp");
docGen.DocumentElement(elementID, 2, "RandomTemp"); // gets the element by ID
docGen.SaveDocument("DOCUMENT.pdf", EA.DocumentType.dtPDF);

+: that would work for me either if i can reach somehow the package properties of the element too.

Thanks in advance.

Tamas


问:
How to convert QueryPerformanceCounter to Unix nanoseconds (epoch)
I am using QueryPerformanceCounter windows syscall in order to get high-precision timestamp.

I need to convert it to unix epoch (in nanoseconds) as I am going to pass the value to an API that needs it in this format

Could anybody help me understanding how to accomplish this?

答:
QueryPerformanceCounter does not return a timestamp with a fixed offset to the current time (as in UTC, or, the time shown by a wall clock), so you cannot convert it to UNIX time.

However, time differences measured using QueryPerformanceCounter can be converted to nanoseconds (or any time unit) by dividing by the result of QueryPerformanceFrequency (to get seconds) and multiplying by, e.g., 10^9 to get nanoseconds.