问:
Simplify long if-else chain with regex by comparing with array
```<code>for (my $j = 0; $j <100000; $j++){
    my $outcome = rand();
    for (my $k = 0; $k < @cum_sum; $k++){
        if ($cum_sum[$k] >= $outcome){
            if ($keys[$k] =~ m/\"|\/|\<|\>|\\|\`|\~|\@|\#|\$|\%|\^|\*|[0-9]/) {
                print $out "";
            }
            if ($keys[$k] =~ m/\s/){
                print $out " ";
            }
            elsif ($keys[$k] =~ m/\&/){
                print $out " and ";
            }
            elsif ($keys[$k] =~ m/\!/){
                print $out "! ";
            }
            elsif ($keys[$k] =~ m/\:/){
                print $out ": ";
            }
            elsif ($keys[$k] =~ m/\'/){
                print $out "' ";
            }
            elsif ($keys[$k] =~ m/\./){
                print $out ". ";
            }
            elsif ($keys[$k] =~ m/\;/){
                print $out "; ";
            }
            elsif ($keys[$k] =~ m/\?/){
                print $out "? ";
            }
            elsif ($keys[$k] =~ m/\,/){
                print $out ", ";
            }
            else {
                print $out "$keys[$k]";
            }
            last;
        }
    }
#   print "$outcome\n";
}
</code>```

I mostly need help with simplifying the long chain of elsif statements I have.
The logic in the outer for loops works.
@keys is an array of two character (digrams) strings.

I am trying to make the elsif statements more efficient by comparing the digrams from @key to an array of the punctuation marks @punctuation = qw(! : " ' ; ? , .)

Then, if the digram does contain one of the punctuation marks in the punctuation array, the digram gets changed to "punctuation_mark " e.g. "a!" -> "! "

The end result would be that I do not use regexes for any of @punctuation.

However, I am not sure on how to implement this change.

Thank you!

答:
So, looking at it you have two cases:

One where you replace a set of values, with 'the value and a space'.  And another where you replace with something different.

So how about creating a lookup table for each, and processing just two regexes:

```<code>#!/usr/bin/env perl.

use strict;
use warnings;
use Data::Dumper;

my %replace = (
    '"' => "",
    '/' => "",
    '&' => " and ",
);
my @add_space = ( ',', '?',  ';', '.', "'", ':', '!' );

my $search = join ( "|", map { quotemeta } keys %replace );
   $search = qr/($search)/;

my $add_space_after = join "|", map {quotemeta} @add_space;
   $add_space_after = qr/($add_space_after)/;

while ( <DATA> ) {
    s/\s/ /g;
    s/$search/$replace{$1}/;
    s/$add_space_after/$1 /;
    print;
}

__DATA__
Work:Work
cookies&milk;wordhere
why?are;you/so "sad"
</code>```

This gives us what you want I think, and - hopefully - keeps the code pretty conscise.

Of importance is the quotemeta function here, because it ensures your metachars are escaped before regexing them.

Note - the only one of your examples this doesn't handle is the \s to " ". But that's IMO probably best to write separately for clarity, as obviously youc can't quotemeta it.

Body:
for (my $j = 0; $j <100000; $j++){
    my $outcome = rand();
    for (my $k = 0; $k < @cum_sum; $k++){
        if ($cum_sum[$k] >= $outcome){
            if ($keys[$k] =~ m/\"|\/|\<|\>|\\|\`|\~|\@|\#|\$|\%|\^|\*|[0-9]/) {
                print $out "";
            }
            if ($keys[$k] =~ m/\s/){
                print $out " ";
            }
            elsif ($keys[$k] =~ m/\&/){
                print $out " and ";
            }
            elsif ($keys[$k] =~ m/\!/){
                print $out "! ";
            }
            elsif ($keys[$k] =~ m/\:/){
                print $out ": ";
            }
            elsif ($keys[$k] =~ m/\'/){
                print $out "' ";
            }
            elsif ($keys[$k] =~ m/\./){
                print $out ". ";
            }
            elsif ($keys[$k] =~ m/\;/){
                print $out "; ";
            }
            elsif ($keys[$k] =~ m/\?/){
                print $out "? ";
            }
            elsif ($keys[$k] =~ m/\,/){
                print $out ", ";
            }
            else {
                print $out "$keys[$k]";
            }
            last;
        }
    }
#   print "$outcome\n";
}

I mostly need help with simplifying the long chain of elsif statements I have.
The logic in the outer for loops works.
@keys is an array of two character (digrams) strings.

I am trying to make the elsif statements more efficient by comparing the digrams from @key to an array of the punctuation marks @punctuation = qw(! : " ' ; ? , .)

Then, if the digram does contain one of the punctuation marks in the punctuation array, the digram gets changed to "punctuation_mark " e.g. "a!" -> "! "

The end result would be that I do not use regexes for any of @punctuation.

However, I am not sure on how to implement this change.

Thank you!

Body:
So, looking at it you have two cases:

One where you replace a set of values, with 'the value and a space'.  And another where you replace with something different.

So how about creating a lookup table for each, and processing just two regexes:

#!/usr/bin/env perl.

use strict;
use warnings;
use Data::Dumper;

my %replace = (
    '"' => "",
    '/' => "",
    '&' => " and ",
);
my @add_space = ( ',', '?',  ';', '.', "'", ':', '!' );

my $search = join ( "|", map { quotemeta } keys %replace );
   $search = qr/($search)/;

my $add_space_after = join "|", map {quotemeta} @add_space;
   $add_space_after = qr/($add_space_after)/;

while ( <DATA> ) {
    s/\s/ /g;
    s/$search/$replace{$1}/;
    s/$add_space_after/$1 /;
    print;
}

__DATA__
Work:Work
cookies&milk;wordhere
why?are;you/so "sad"

This gives us what you want I think, and - hopefully - keeps the code pretty conscise.

Of importance is the quotemeta function here, because it ensures your metachars are escaped before regexing them.

Note - the only one of your examples this doesn't handle is the \s to " ". But that's IMO probably best to write separately for clarity, as obviously youc can't quotemeta it.


来源: stackexchange

问:
Vim, removing blank and commented lines in one regex
I want to remove blank and commented lined at one time. I already found the similar question regarding  removing blank lines, so for blank lines I use:

```<code>:g/^$/d
</code>```

and for commented lines:

```<code>:g/^#/d
</code>```

I'm curious is there any way to merge these regex in one? Something like

```<code>:g/^[$#]/d
</code>```

but obviously it doesn't work in vim.

答:
Expanding on kevs answer:

If anyone would also like to delete the comments in config files that are tabbed,

for example:

```<code>server {
    listen 80 default_server;
    listen [::]:80 default_server;

    # SSL configuration
    #
    # listen 443 ssl default_server;
    # listen [::]:443 ssl default_server;
    #
    # Self signed certs generated by the ssl-cert package
    # Don't use them in a production server!
    #
    # include snippets/snakeoil.conf;
    ...
</code>```

You can try this:

```<code>:g/\v^(#|$|\t#)/d
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to remove blank and commented lined at one time. I already found the similar question regarding  removing blank lines, so for blank lines I use:

:g/^$/d

and for commented lines:

:g/^#/d

I'm curious is there any way to merge these regex in one? Something like

:g/^[$#]/d

but obviously it doesn't work in vim.

Body:
Expanding on kevs answer:

If anyone would also like to delete the comments in config files that are tabbed,

for example:

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    # SSL configuration
    #
    # listen 443 ssl default_server;
    # listen [::]:443 ssl default_server;
    #
    # Self signed certs generated by the ssl-cert package
    # Don't use them in a production server!
    #
    # include snippets/snakeoil.conf;
    ...

You can try this:

:g/\v^(#|$|\t#)/d


问:
Why a struct declared by let can be changed?
In the following code, 'ptr' is a struct declared by let, but its member variable 'pointee' could be changed, Why?

    let ptr = UnsafeMutablePointer<Int>.allocate(capacity:1)
    ptr.pointee = 1

答:
A pointer is not a struct.

It's a reference type unlike a struct which is value type.

Since you declare the pointer as mutable you can change the pointee (the contents of the memory) but you cannot change the reference itself.


问:
Combine two resource key for single label .Net
For making an existing site to multilingual, I follow globalization technique, I have created 3 resource files for different content like label & header text file, grid header text file etc...
Now I have two keys in different resource files i.e Email and Message, at a third place I want to show both these keyword together i.e Email message. Do I need to create third key or I can concatenate already existing keys. Currently I am using below two codes

```<code>For showing directly on page:
HttpContext.GetGlobalResourceObject("ResourceLabelButton", "Email")

For showing as text of any control like Textbox, label:
Text ="<%$ Resources:ResourceContent, Email %>"
</code>```

I can concatenate two resource string on .cs page but it will increase timeline, so please suggest so I can only change on .aspx pages.

Thanks in advance

答:
Try with the below code

```<code><asp:Label ID="lblNameAndNos" runat="server">
<%= ""+ Resources.Resources.Name + "/" + Resources.Resources.Nos %>
</asp:Label>
</code>```

Instead of using inside Text property use the above way

Body:
For making an existing site to multilingual, I follow globalization technique, I have created 3 resource files for different content like label & header text file, grid header text file etc...
Now I have two keys in different resource files i.e Email and Message, at a third place I want to show both these keyword together i.e Email message. Do I need to create third key or I can concatenate already existing keys. Currently I am using below two codes

For showing directly on page:
HttpContext.GetGlobalResourceObject("ResourceLabelButton", "Email")

For showing as text of any control like Textbox, label:
Text ="<%$ Resources:ResourceContent, Email %>"

I can concatenate two resource string on .cs page but it will increase timeline, so please suggest so I can only change on .aspx pages.

Thanks in advance

Body:
Try with the below code

<asp:Label ID="lblNameAndNos" runat="server">
<%= ""+ Resources.Resources.Name + "/" + Resources.Resources.Nos %>
</asp:Label>

Instead of using inside Text property use the above way


问:
how to retrieve player names who never scored a century?
My Data is like this. So, I want to see the list of Players who never scored a Century in their entire career.
Sample Data

答:
Try Group By and Having Combination

```<code>SELECT
    name
FROM [Table Name]
GROUP BY
    name
HAVING
    MAX(score) < 100
</code>```

Body:
Try Group By and Having Combination

SELECT
    name
FROM [Table Name]
GROUP BY
    name
HAVING
    MAX(score) < 100


问:
In winapi, using restsdk, error
In winapi,
create a program that uses the rest sdk to communicate with the web.

It runs in the console program,
but in winapi it generates an error.

The same error occurs when using the asynchronous method.

I looked for similar problems but could not find them.

There is not enough examples of errors when using restsdk in winapi.

Please help me

```<code>#include "stdafx.h"

#include <CommCtrl.h>

#include <cpprest\http_client.h>
#include <iostream>
#include <cpprest\json.h>

#include <vector>
#include <iterator>

using namespace web;
using namespace web::http;
using namespace web::http::client;

using namespace std;

using namespace utility;
using namespace concurrency::streams;

void GetHttp2();

int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
    _In_opt_ HINSTANCE hPrevInstance,
    _In_ LPWSTR    lpCmdLine,
    _In_ int       nCmdShow);

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{

    switch (message)
    {
    case WM_CREATE:

        break;

    case WM_COMMAND:
    {
        int wmId = LOWORD(wParam);
        switch (wmId)
        {
        case IDM_ABOUT:
            DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
            break;
        case IDM_EXIT:
            DestroyWindow(hWnd);
            break;

        case IDC_ADD_BTN: // button clicked

            GetHttp2();
            break;

        default:
            return DefWindowProc(hWnd, message, wParam, lParam);
        }
    }
    break;
    case WM_PAINT:
    {
        PAINTSTRUCT ps;
        HDC hdc = BeginPaint(hWnd, &ps);
        EndPaint(hWnd, &ps);
    }
    break;
    case WM_DESTROY:
        PostQuitMessage(0);
        break;

    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    }
    return 0;
}

void GetHttp2()
{
    http_client client(U("http://en.cppreference.com/w/"));
    auto resp = client.request(U("GET")).get(); // error point, xutiliy error...
}
</code>```

In the 'xutility' file,

```<code>inline void _Container_base12::_Orphan_all() _NOEXCEPT
{   // orphan all iterators
#if _ITERATOR_DEBUG_LEVEL == 2
    if (_Myproxy != 0)
    {   // proxy allocated, drain it
        _Lockit _Lock(_LOCK_DEBUG);

        for (_Iterator_base12 **_Pnext = &_Myproxy->_Myfirstiter;
            *_Pnext != 0; *_Pnext = (*_Pnext)->_Mynextiter)  /// error point
            (*_Pnext)->_Myproxy = 0;
        _Myproxy->_Myfirstiter = 0;
    }
#endif /* _ITERATOR_DEBUG_LEVEL == 2 */
}
</code>```

Exception thrown : read access violation.
_Pnext was 0xCDCDCDD1.

Error Image Capture

答:
I'm only guessing that the object returned by request is immediately destroyed and then you call get on a destroyed object.

try storing the task returned by request as a local variable:

```<code>void GetHttp2()
{
    http_client client(U("http://en.cppreference.com/w/"));
    auto task = client.request(U("GET"));
    auto resp = task.get();
}
</code>```

Title: In winapi, using restsdk, error

Body:
In winapi,
create a program that uses the rest sdk to communicate with the web.

It runs in the console program,
but in winapi it generates an error.

The same error occurs when using the asynchronous method.

I looked for similar problems but could not find them.

There is not enough examples of errors when using restsdk in winapi.

Please help me

#include "stdafx.h"

#include <CommCtrl.h>

#include <cpprest\http_client.h>
#include <iostream>
#include <cpprest\json.h>

#include <vector>
#include <iterator>

using namespace web;
using namespace web::http;
using namespace web::http::client;

using namespace std;

using namespace utility;
using namespace concurrency::streams;

void GetHttp2();

int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
    _In_opt_ HINSTANCE hPrevInstance,
    _In_ LPWSTR    lpCmdLine,
    _In_ int       nCmdShow);

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{

    switch (message)
    {
    case WM_CREATE:

        break;

    case WM_COMMAND:
    {
        int wmId = LOWORD(wParam);
        switch (wmId)
        {
        case IDM_ABOUT:
            DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
            break;
        case IDM_EXIT:
            DestroyWindow(hWnd);
            break;

        case IDC_ADD_BTN: // button clicked

            GetHttp2();
            break;

        default:
            return DefWindowProc(hWnd, message, wParam, lParam);
        }
    }
    break;
    case WM_PAINT:
    {
        PAINTSTRUCT ps;
        HDC hdc = BeginPaint(hWnd, &ps);
        EndPaint(hWnd, &ps);
    }
    break;
    case WM_DESTROY:
        PostQuitMessage(0);
        break;

    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    }
    return 0;
}

void GetHttp2()
{
    http_client client(U("http://en.cppreference.com/w/"));
    auto resp = client.request(U("GET")).get(); // error point, xutiliy error...
}

In the 'xutility' file,

inline void _Container_base12::_Orphan_all() _NOEXCEPT
{   // orphan all iterators
#if _ITERATOR_DEBUG_LEVEL == 2
    if (_Myproxy != 0)
    {   // proxy allocated, drain it
        _Lockit _Lock(_LOCK_DEBUG);

        for (_Iterator_base12 **_Pnext = &_Myproxy->_Myfirstiter;
            *_Pnext != 0; *_Pnext = (*_Pnext)->_Mynextiter)  /// error point
            (*_Pnext)->_Myproxy = 0;
        _Myproxy->_Myfirstiter = 0;
    }
#endif /* _ITERATOR_DEBUG_LEVEL == 2 */
}

Exception thrown : read access violation.
_Pnext was 0xCDCDCDD1.

Error Image Capture

Body:
I'm only guessing that the object returned by request is immediately destroyed and then you call get on a destroyed object.

try storing the task returned by request as a local variable:

void GetHttp2()
{
    http_client client(U("http://en.cppreference.com/w/"));
    auto task = client.request(U("GET"));
    auto resp = task.get();
}


问:
React.Children.only expected to receive a single React element child error while using Ref
I have to call some methods from component B inside component A.
Here is the component B: (In the case that you need more code just request me and I will update my post)

```<code>import A  from "./A";
export default class B extends Component {
  componentDidUpdate (prevProps, prevState) {
    this.props.onRef(this);
  }

  renderContent ( ) {
    let toolbarActiveItem = Toolbar.getActiveItem();
    if (Toolbar.getActiveItem()=="XXXX") {
      this.refs.A._showModalHistory();
    } else {
      toolbarActiveItem = Toolbar.getActiveItem();
    }

    return (
      <Container>
        {(toolbarActiveItem == 'YYY') && <C navigation={this.props.navigation} cb={this.childCallback} info={this.props.navigation.state.params}/> }
      </Container>
    );
  }

  render () {
    return (
      <StyleProvider style={getTheme(Config.theme)}>
        <A ref={component => { this.A = component; }} />
        <Container ref={this.ref}>
          { this.renderNavbar(this.title) }
          { this.renderToolbar() }
          { this.renderContent() }
          { this.renderDialog() }
        </Container>
      </StyleProvider>
    );
  }
</code>```

Here is the component A:

```<code>export default class A extends Component {
  constructor(props) {
    super();
    this.subscription = 0;
    this.state = {};
    changePage = props.cb;

    this.state = {
      isModalVisibleHistory: false,
    };
  }

  _showModalHistory = () => this.setState({ isModalVisibleHistory: true });

  render() {
    return (
      <Modal isVisible={this.state.isModalVisibleHistory}>
        <View style={styles.BG}>
        <ParkHistory></ParkHistory>
        </View>
      </Modal>
    );
  }
}
</code>```

My problem is that, I need to execute this.refs.A._showModalHistory(); in component B but, I see the following error:

React.Children.only expected to receive a single React element child.

I think, I have a problem to deal with rendering multiple components and ref them. I should mention that, when I delete  { this.A = component; }} /> my code works fine but, without calling the method. Could you please help me to solve this issue?

答:
The problem is in the way you are accessing the ref. You have assigned ref to Component A. You are using the callback style to assign ref and so you need not write this.ref.A. Change it to this.A._showModalHistory();

Aslo the way you are setting ref to Container component is incorrect, you need to use callback there

```<code><Container ref={(ref)=> this.ref = ref}>
</code>```

One other thing is that the StyleProvider component expects a single child element. You should wrap your Container and A component in View

```<code>render () {
    return (
      <StyleProvider style={getTheme(Config.theme)}>
        <View>
        <A ref={component => { this.A = component; }} />
        <Container ref={(ref)=> this.ref = ref}>
          { this.renderNavbar(this.title) }
          { this.renderToolbar() }
          { this.renderContent() }
          { this.renderDialog() }
        </Container>
        </View>
      </StyleProvider>
    );
  }
</code>```

Body:
I have to call some methods from component B inside component A.
Here is the component B: (In the case that you need more code just request me and I will update my post)

import A  from "./A";
export default class B extends Component {
  componentDidUpdate (prevProps, prevState) {
    this.props.onRef(this);
  }

  renderContent ( ) {
    let toolbarActiveItem = Toolbar.getActiveItem();
    if (Toolbar.getActiveItem()=="XXXX") {
      this.refs.A._showModalHistory();
    } else {
      toolbarActiveItem = Toolbar.getActiveItem();
    }

    return (
      <Container>
        {(toolbarActiveItem == 'YYY') && <C navigation={this.props.navigation} cb={this.childCallback} info={this.props.navigation.state.params}/> }
      </Container>
    );
  }

  render () {
    return (

    );
  }

Here is the component A:

export default class A extends Component {
  constructor(props) {
    super();
    this.subscription = 0;
    this.state = {};
    changePage = props.cb;

    this.state = {
      isModalVisibleHistory: false,
    };
  }

  _showModalHistory = () => this.setState({ isModalVisibleHistory: true });

  render() {
    return (
      <Modal isVisible={this.state.isModalVisibleHistory}>
        <View style={styles.BG}>
        <ParkHistory></ParkHistory>
        </View>
      </Modal>
    );
  }
}

My problem is that, I need to execute this.refs.A._showModalHistory(); in component B but, I see the following error:

React.Children.only expected to receive a single React element child.

I think, I have a problem to deal with rendering multiple components and ref them. I should mention that, when I delete  { this.A = component; }} /> my code works fine but, without calling the method. Could you please help me to solve this issue?

Body:
The problem is in the way you are accessing the ref. You have assigned ref to Component A. You are using the callback style to assign ref and so you need not write this.ref.A. Change it to this.A._showModalHistory();

Aslo the way you are setting ref to Container component is incorrect, you need to use callback there

<Container ref={(ref)=> this.ref = ref}>

One other thing is that the StyleProvider component expects a single child element. You should wrap your Container and A component in View

render () {
    return (
      <StyleProvider style={getTheme(Config.theme)}>
        <View>
        <A ref={component => { this.A = component; }} />
        <Container ref={(ref)=> this.ref = ref}>
          { this.renderNavbar(this.title) }
          { this.renderToolbar() }
          { this.renderContent() }
          { this.renderDialog() }
        </Container>
        </View>
      </StyleProvider>
    );
  }


问:
JavaFx - Get the coordinates(x,y) of a node or control whose parent is not a Pane
I am trying to emulate a popup container that will show some hints about the proper format of address. The popup will show whenever the addressTextfield gained focus. The popup should appear under the addressTextfield. The problem is, I used combinations of VBox, HBox, and FlowPane for my layout. The default layoutX and layoutY is zero, and it seem they do not change on runtime.

My Popup Control

My AddressField and the hierarchy

What I got so far...

My Popup control stays on top. I tried binding my popup layoutXProperty() to addressTextFields's layoutXProperty()same in layoutYProperty(). I tried adding a MouseEvent.MOUSE_CLICKEDon addressTextField, added a MouseLocationProperty which will be updated on MouseEvent.MouseClicked and binded it to my popup's layoutXProperty(). But still not making it appear under the addressTextField.

My AddNewAccount Class

```<code>package com.strongandwhite.pages.dentistadnstaff;

import com.strongandwhite.customcontrols.CustomComboBox;
import com.strongandwhite.customcontrols.CustomDatePicker;
import com.strongandwhite.customcontrols.CustomPasswordField;
import com.strongandwhite.customcontrols.CustomTextField;
import com.strongandwhite.main.MainWindow;
import com.strongandwhite.models.User;
import com.strongandwhite.pages.Page;
import com.strongandwhite.rules.*;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Button;
import javafx.scene.control.DateCell;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;

import java.io.IOException;
import java.time.LocalDate;
import java.time.chrono.ChronoLocalDate;
import java.util.ArrayList;

public class AddNewAccount extends Page {
    private ArrayList<String> gender;
    private ArrayList<String> type;
    private ArrayList<String> position;
    public User user;
    private SimpleDoubleProperty mouseX;
    private SimpleDoubleProperty mouseY;

    @FXML private HBox firstNameHBox;
    private CustomTextField firstNameTextField;

    @FXML private HBox middleNameHBox;
    private CustomTextField middleNameTextField;

    @FXML private HBox lastNameHBox;
    private CustomTextField lastNameTextField;

    @FXML private HBox ageHBox;
    private CustomTextField ageTextField;

    @FXML private HBox genderHBox;
    private CustomComboBox<String> genderComboBox;

    @FXML private HBox addressHBox;
    private CustomTextField addressTextField;

    @FXML private HBox contactHBox;
    private CustomTextField contactTextField;

    @FXML private HBox nationalityHBox;
    private CustomTextField nationalityTextField;

    @FXML private HBox religionHBox;
    private CustomTextField religionTextField;

    @FXML private HBox emailAddressHBox;
    private CustomTextField emailAddressTextField;

    @FXML private HBox birthdateHBox;
    private CustomDatePicker birtdateDatePicker;

    @FXML private HBox accountIDHBox;
    private CustomTextField accountIDTextField;

    @FXML private HBox passwordHBox;
    private CustomPasswordField passwordTextField;

    @FXML private HBox confirmPasswordHBox;
    private CustomPasswordField confirmPasswordTextField;

    @FXML private HBox accountTypeHBox;
    private CustomComboBox<String> accountTypeComboBox;

    @FXML private HBox positionHBox;
    private CustomComboBox<String> positionComboBox;

    @FXML private HBox question1HBox;
    private CustomTextField question1TextField;

    @FXML private HBox question2HBox;
    private CustomTextField question2TextField;

    @FXML private HBox question3HBox;
    private CustomTextField question3TextField;

    @FXML private HBox answer1HBox;
    private CustomTextField answer1TextField;

    @FXML private HBox answer2HBox;
    private CustomTextField answer2TextField;

    @FXML private HBox answer3HBox;
    private CustomTextField answer3TextField;

    @FXML private Button clearButton;

    private AnchorPane addressInfo;
    private Pane coverPane;
    private ScrollPane scrollPane;

    public AddNewAccount(User user, MainWindow mainWindow) {
        this.user = user;

        FXMLLoader loader = new FXMLLoader(getClass().getResource("AddNewAccount.fxml"));
        loader.setController(this);
        loader.setRoot(this);
        try {
            loader.load();
        } catch (IOException e) {
            e.printStackTrace();
        }
        loadTitle("AddNewAccountTitle.fxml");

        FXMLLoader loader1 = new FXMLLoader(getClass().getResource("AddressInfo.fxml"));
        try {
            addressInfo = loader1.load();
        } catch (IOException e) {
            e.printStackTrace();
        }

        coverPane = new Pane();

        firstNameTextField = new CustomTextField(firstNameHBox, customControls);
        firstNameTextField.setRule(new NameRule("First Name"));

        middleNameTextField = new CustomTextField(middleNameHBox, customControls);
        middleNameTextField.setRule(new NameRule("Middle Name"));

        lastNameTextField = new CustomTextField(lastNameHBox, customControls);
        lastNameTextField.setRule(new NameRule("Last Name"));

        birtdateDatePicker = new CustomDatePicker(birthdateHBox, customControls);
        birtdateDatePicker.setRule(new DateRule());

        ageTextField = new CustomTextField(ageHBox, customControls);
        ageTextField.setRule(new NumbersOnlyRule());

        genderComboBox = new CustomComboBox<>(genderHBox, customControls);
        genderComboBox.setRule(new WordRule("Gender"));

        addressTextField = new CustomTextField(addressHBox, customControls);
        addressTextField.setRule(new AddressRule());

        contactTextField = new CustomTextField(contactHBox, customControls);
        contactTextField.setRule(new ContactNumberRule());

        nationalityTextField = new CustomTextField(nationalityHBox, customControls);
        nationalityTextField.setRule(new NameRule("Nationality"));

        religionTextField = new CustomTextField(religionHBox, customControls);
        religionTextField.setRule(new NameRule("Religion"));

        emailAddressTextField = new CustomTextField(emailAddressHBox, customControls);
        emailAddressTextField.setRule(new EmailAddressRule());

        accountIDTextField = new CustomTextField(accountIDHBox, customControls);
        accountIDTextField.setRule(new AccountIDRule());

        passwordTextField = new CustomPasswordField(passwordHBox, customControls);
        passwordTextField.setRule(new PasswordRule());

        confirmPasswordTextField = new CustomPasswordField(confirmPasswordHBox, customControls);
        confirmPasswordTextField.setRule(new PasswordRule());

        accountTypeComboBox = new CustomComboBox<>(accountTypeHBox, customControls);
        accountTypeComboBox.setRule(new WordRule("Account Type"));

        positionComboBox = new CustomComboBox<>(positionHBox, customControls);
        positionComboBox.setRule(new WordRule("Position"));

        question1TextField = new CustomTextField(question1HBox, customControls);
        question1TextField.setRule(new WordRule("Question"));

        question2TextField = new CustomTextField(question2HBox, customControls);
        question2TextField.setRule(new WordRule("Question"));

        question3TextField = new CustomTextField(question3HBox, customControls);
        question3TextField.setRule(new WordRule("Question"));

        answer1TextField = new CustomTextField(answer1HBox, customControls);
        answer1TextField.setRule(new WordRule("Answer"));

        answer2TextField = new CustomTextField(answer2HBox, customControls);
        answer2TextField.setRule(new WordRule("Answer"));

        answer3TextField = new CustomTextField(answer3HBox, customControls);
        answer3TextField.setRule(new WordRule("Answer"));

        clearButton.setOnAction(event -> clearPageFields());

        birtdateDatePicker.setDefaultDate(LocalDate.now().minusYears(18));
        birtdateDatePicker.setDayCellFactory(param -> new DateCell() {
            @Override
            public void updateItem(LocalDate item, boolean empty) {
                super.updateItem(item, empty);
                if(item.isBefore(ChronoLocalDate.from(LocalDate.now().minusYears(76).minusMonths(1)))||item.isAfter(ChronoLocalDate.from(LocalDate.now().minusYears(18).plusMonths(1)))) {
                    this.setDisable(true);
                }
            }
        });

        user.ageProperty().bind(birtdateDatePicker.ageProperty());
        ageTextField.textProperty().bind(user.ageProperty().asString());

        gender = new ArrayList<>();
        gender.add("Male");
        gender.add("Female");
        genderComboBox.setItems(gender);

        type = new ArrayList<>();
        type.add("Administrator");
        type.add("Standard");
        type.add("Limited");
        accountTypeComboBox.setItems(type);

        position = new ArrayList<>();
        position.add("Dentist");
        position.add("Receptionist");
        position.add("Staff");
        positionComboBox.setItems(position);

        answer1TextField.editableProperty().bind(question1TextField.textProperty().isNotEmpty());
        answer1TextField.editableProperty().addListener(event-> {
            if(question1TextField.textProperty().getValue().trim().isEmpty()) answer1TextField.clear();
        });

        answer2TextField.editableProperty().bind(question2TextField.textProperty().isNotEmpty());
        answer2TextField.editableProperty().addListener(event-> {
            if(question2TextField.textProperty().getValue().trim().isEmpty()) answer2TextField.clear();
        });

        answer3TextField.editableProperty().bind(question3TextField.textProperty().isNotEmpty());
        answer3TextField.editableProperty().addListener(event-> {
            if(question3TextField.textProperty().getValue().trim().isEmpty()) answer3TextField.clear();
        });

        mainWindow.getActivePagePane().getChildren().add(getPageTitle());

        scrollPane = (ScrollPane) mainWindow.getActivePagePane().getChildren().get(0);
        scrollPane.vvalueProperty().addListener(event-> scrollPane.requestFocus());

        addressInfo.visibleProperty().bind(addressTextField.getTextField().focusedProperty());
        coverPane.setPickOnBounds(false);
        mainWindow.getActivePagePane().getChildren().add(coverPane);
        coverPane.getChildren().add(addressInfo);
        addressInfo.layoutXProperty().bind(addressTextField.getTextField().layoutXProperty());
        addressInfo.layoutYProperty().bind(addressTextField.getTextField().layoutYProperty());
    }
}
</code>```

My CustomTextField Class

```<code>package com.strongandwhite.customcontrols;

import javafx.beans.property.BooleanProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;

import java.util.ArrayList;

public class CustomTextField extends CustomControl {
    private TextField textField;
    private Label textLabel;
    private Button clearButton;

    public CustomTextField(HBox control, ArrayList<CustomControl> customControls) {
        setContainer(control);
        textLabel = (Label) ((VBox)control.getChildren().get(0)).getChildren().get(0);
        setErrorLabel((Label) ((VBox)control.getChildren().get(0)).getChildren().get(2));
        textField = (TextField) ((StackPane)((VBox)control.getChildren().get(0)).getChildren().get(1)).getChildren().get(0);
        clearButton = (Button) ((StackPane)((VBox)control.getChildren().get(0)).getChildren().get(1)).getChildren().get(1);
        textLabel.visibleProperty().bind(textField.textProperty().isNotEmpty());
        clearButton.visibleProperty().bind(textField.textProperty().isNotEmpty().and(textField.focusedProperty()).and(textField.editableProperty()));
        clearButton.setOnAction(event -> textField.clear());
        textField.textProperty().addListener((observable, oldValue, newValue) -> executeRule(getRule(), textField.getText()));
        customControls.add(this);
    }

    public StringProperty textProperty() {
        return textField.textProperty();
    }

    public BooleanProperty editableProperty() {
        return textField.editableProperty();
    }

    public String getText() {
        return textField.getText();
    }

    public void setText(String text) {
        textField.setText(text);
    }

    public TextField getTextField() {
        return textField;
    }

    public void setTextField(TextField textField) {
        this.textField = textField;
    }

    @Override
    public void clear() {
        textField.clear();
    }
}
</code>```

Is there any way I can get the coordinates of addressTextField relative to my Form?

NOTE: My popup is added on a Pane particulary the coverPane which is above my Form and they are all under StackPane.

答:
These guys suggest you to use something like:

```<code>Bounds boundsInScene = addressTextField.localToScene(addressTextField.getBoundsInLocal());
</code>```

and then use

```<code>boundsInScene.getMinX()
boundsInScene.getMinY()
boundsInScene.getMaxX()
boundsInScene.getMaxY()
boundsInScene.getWidth()
boundsInScene.getHeight()
</code>```

to get the values of your component relative to the Scene

Body:
I am trying to emulate a popup container that will show some hints about the proper format of address. The popup will show whenever the addressTextfield gained focus. The popup should appear under the addressTextfield. The problem is, I used combinations of VBox, HBox, and FlowPane for my layout. The default layoutX and layoutY is zero, and it seem they do not change on runtime.

My Popup Control

My AddressField and the hierarchy

What I got so far...

My Popup control stays on top. I tried binding my popup layoutXProperty() to addressTextFields's layoutXProperty()same in layoutYProperty(). I tried adding a MouseEvent.MOUSE_CLICKEDon addressTextField, added a MouseLocationProperty which will be updated on MouseEvent.MouseClicked and binded it to my popup's layoutXProperty(). But still not making it appear under the addressTextField.

My AddNewAccount Class

package com.strongandwhite.pages.dentistadnstaff;

import com.strongandwhite.customcontrols.CustomComboBox;
import com.strongandwhite.customcontrols.CustomDatePicker;
import com.strongandwhite.customcontrols.CustomPasswordField;
import com.strongandwhite.customcontrols.CustomTextField;
import com.strongandwhite.main.MainWindow;
import com.strongandwhite.models.User;
import com.strongandwhite.pages.Page;
import com.strongandwhite.rules.*;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Button;
import javafx.scene.control.DateCell;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;

import java.io.IOException;
import java.time.LocalDate;
import java.time.chrono.ChronoLocalDate;
import java.util.ArrayList;

public class AddNewAccount extends Page {
    private ArrayList<String> gender;
    private ArrayList<String> type;
    private ArrayList<String> position;
    public User user;
    private SimpleDoubleProperty mouseX;
    private SimpleDoubleProperty mouseY;

    @FXML private HBox firstNameHBox;
    private CustomTextField firstNameTextField;

    @FXML private HBox middleNameHBox;
    private CustomTextField middleNameTextField;

    @FXML private HBox lastNameHBox;
    private CustomTextField lastNameTextField;

    @FXML private HBox ageHBox;
    private CustomTextField ageTextField;

    @FXML private HBox genderHBox;
    private CustomComboBox<String> genderComboBox;

    @FXML private HBox addressHBox;
    private CustomTextField addressTextField;

    @FXML private HBox contactHBox;
    private CustomTextField contactTextField;

    @FXML private HBox nationalityHBox;
    private CustomTextField nationalityTextField;

    @FXML private HBox religionHBox;
    private CustomTextField religionTextField;

    @FXML private HBox emailAddressHBox;
    private CustomTextField emailAddressTextField;

    @FXML private HBox birthdateHBox;
    private CustomDatePicker birtdateDatePicker;

    @FXML private HBox accountIDHBox;
    private CustomTextField accountIDTextField;

    @FXML private HBox passwordHBox;
    private CustomPasswordField passwordTextField;

    @FXML private HBox confirmPasswordHBox;
    private CustomPasswordField confirmPasswordTextField;

    @FXML private HBox accountTypeHBox;
    private CustomComboBox<String> accountTypeComboBox;

    @FXML private HBox positionHBox;
    private CustomComboBox<String> positionComboBox;

    @FXML private HBox question1HBox;
    private CustomTextField question1TextField;

    @FXML private HBox question2HBox;
    private CustomTextField question2TextField;

    @FXML private HBox question3HBox;
    private CustomTextField question3TextField;

    @FXML private HBox answer1HBox;
    private CustomTextField answer1TextField;

    @FXML private HBox answer2HBox;
    private CustomTextField answer2TextField;

    @FXML private HBox answer3HBox;
    private CustomTextField answer3TextField;

    @FXML private Button clearButton;

    private AnchorPane addressInfo;
    private Pane coverPane;
    private ScrollPane scrollPane;

    public AddNewAccount(User user, MainWindow mainWindow) {
        this.user = user;

        FXMLLoader loader = new FXMLLoader(getClass().getResource("AddNewAccount.fxml"));
        loader.setController(this);
        loader.setRoot(this);
        try {
            loader.load();
        } catch (IOException e) {
            e.printStackTrace();
        }
        loadTitle("AddNewAccountTitle.fxml");

        FXMLLoader loader1 = new FXMLLoader(getClass().getResource("AddressInfo.fxml"));
        try {
            addressInfo = loader1.load();
        } catch (IOException e) {
            e.printStackTrace();
        }

        coverPane = new Pane();

        firstNameTextField = new CustomTextField(firstNameHBox, customControls);
        firstNameTextField.setRule(new NameRule("First Name"));

        middleNameTextField = new CustomTextField(middleNameHBox, customControls);
        middleNameTextField.setRule(new NameRule("Middle Name"));

        lastNameTextField = new CustomTextField(lastNameHBox, customControls);
        lastNameTextField.setRule(new NameRule("Last Name"));

        birtdateDatePicker = new CustomDatePicker(birthdateHBox, customControls);
        birtdateDatePicker.setRule(new DateRule());

        ageTextField = new CustomTextField(ageHBox, customControls);
        ageTextField.setRule(new NumbersOnlyRule());

        genderComboBox = new CustomComboBox<>(genderHBox, customControls);
        genderComboBox.setRule(new WordRule("Gender"));

        addressTextField = new CustomTextField(addressHBox, customControls);
        addressTextField.setRule(new AddressRule());

        contactTextField = new CustomTextField(contactHBox, customControls);
        contactTextField.setRule(new ContactNumberRule());

        nationalityTextField = new CustomTextField(nationalityHBox, customControls);
        nationalityTextField.setRule(new NameRule("Nationality"));

        religionTextField = new CustomTextField(religionHBox, customControls);
        religionTextField.setRule(new NameRule("Religion"));

        emailAddressTextField = new CustomTextField(emailAddressHBox, customControls);
        emailAddressTextField.setRule(new EmailAddressRule());

        accountIDTextField = new CustomTextField(accountIDHBox, customControls);
        accountIDTextField.setRule(new AccountIDRule());

        passwordTextField = new CustomPasswordField(passwordHBox, customControls);
        passwordTextField.setRule(new PasswordRule());

        confirmPasswordTextField = new CustomPasswordField(confirmPasswordHBox, customControls);
        confirmPasswordTextField.setRule(new PasswordRule());

        accountTypeComboBox = new CustomComboBox<>(accountTypeHBox, customControls);
        accountTypeComboBox.setRule(new WordRule("Account Type"));

        positionComboBox = new CustomComboBox<>(positionHBox, customControls);
        positionComboBox.setRule(new WordRule("Position"));

        question1TextField = new CustomTextField(question1HBox, customControls);
        question1TextField.setRule(new WordRule("Question"));

        question2TextField = new CustomTextField(question2HBox, customControls);
        question2TextField.setRule(new WordRule("Question"));

        question3TextField = new CustomTextField(question3HBox, customControls);
        question3TextField.setRule(new WordRule("Question"));

        answer1TextField = new CustomTextField(answer1HBox, customControls);
        answer1TextField.setRule(new WordRule("Answer"));

        answer2TextField = new CustomTextField(answer2HBox, customControls);
        answer2TextField.setRule(new WordRule("Answer"));

        answer3TextField = new CustomTextField(answer3HBox, customControls);
        answer3TextField.setRule(new WordRule("Answer"));

        clearButton.setOnAction(event -> clearPageFields());

        birtdateDatePicker.setDefaultDate(LocalDate.now().minusYears(18));
        birtdateDatePicker.setDayCellFactory(param -> new DateCell() {
            @Override
            public void updateItem(LocalDate item, boolean empty) {
                super.updateItem(item, empty);
                if(item.isBefore(ChronoLocalDate.from(LocalDate.now().minusYears(76).minusMonths(1)))||item.isAfter(ChronoLocalDate.from(LocalDate.now().minusYears(18).plusMonths(1)))) {
                    this.setDisable(true);
                }
            }
        });

        user.ageProperty().bind(birtdateDatePicker.ageProperty());
        ageTextField.textProperty().bind(user.ageProperty().asString());

        gender = new ArrayList<>();
        gender.add("Male");
        gender.add("Female");
        genderComboBox.setItems(gender);

        type = new ArrayList<>();
        type.add("Administrator");
        type.add("Standard");
        type.add("Limited");
        accountTypeComboBox.setItems(type);

        position = new ArrayList<>();
        position.add("Dentist");
        position.add("Receptionist");
        position.add("Staff");
        positionComboBox.setItems(position);

        answer1TextField.editableProperty().bind(question1TextField.textProperty().isNotEmpty());
        answer1TextField.editableProperty().addListener(event-> {
            if(question1TextField.textProperty().getValue().trim().isEmpty()) answer1TextField.clear();
        });

        answer2TextField.editableProperty().bind(question2TextField.textProperty().isNotEmpty());
        answer2TextField.editableProperty().addListener(event-> {
            if(question2TextField.textProperty().getValue().trim().isEmpty()) answer2TextField.clear();
        });

        answer3TextField.editableProperty().bind(question3TextField.textProperty().isNotEmpty());
        answer3TextField.editableProperty().addListener(event-> {
            if(question3TextField.textProperty().getValue().trim().isEmpty()) answer3TextField.clear();
        });

        mainWindow.getActivePagePane().getChildren().add(getPageTitle());

        scrollPane = (ScrollPane) mainWindow.getActivePagePane().getChildren().get(0);
        scrollPane.vvalueProperty().addListener(event-> scrollPane.requestFocus());

        addressInfo.visibleProperty().bind(addressTextField.getTextField().focusedProperty());
        coverPane.setPickOnBounds(false);
        mainWindow.getActivePagePane().getChildren().add(coverPane);
        coverPane.getChildren().add(addressInfo);
        addressInfo.layoutXProperty().bind(addressTextField.getTextField().layoutXProperty());
        addressInfo.layoutYProperty().bind(addressTextField.getTextField().layoutYProperty());
    }
}

My CustomTextField Class

package com.strongandwhite.customcontrols;

import javafx.beans.property.BooleanProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;

import java.util.ArrayList;

public class CustomTextField extends CustomControl {
    private TextField textField;
    private Label textLabel;
    private Button clearButton;

    public CustomTextField(HBox control, ArrayList<CustomControl> customControls) {
        setContainer(control);
        textLabel = (Label) ((VBox)control.getChildren().get(0)).getChildren().get(0);
        setErrorLabel((Label) ((VBox)control.getChildren().get(0)).getChildren().get(2));
        textField = (TextField) ((StackPane)((VBox)control.getChildren().get(0)).getChildren().get(1)).getChildren().get(0);
        clearButton = (Button) ((StackPane)((VBox)control.getChildren().get(0)).getChildren().get(1)).getChildren().get(1);
        textLabel.visibleProperty().bind(textField.textProperty().isNotEmpty());
        clearButton.visibleProperty().bind(textField.textProperty().isNotEmpty().and(textField.focusedProperty()).and(textField.editableProperty()));
        clearButton.setOnAction(event -> textField.clear());
        textField.textProperty().addListener((observable, oldValue, newValue) -> executeRule(getRule(), textField.getText()));
        customControls.add(this);
    }

    public StringProperty textProperty() {
        return textField.textProperty();
    }

    public BooleanProperty editableProperty() {
        return textField.editableProperty();
    }

    public String getText() {
        return textField.getText();
    }

    public void setText(String text) {
        textField.setText(text);
    }

    public TextField getTextField() {
        return textField;
    }

    public void setTextField(TextField textField) {
        this.textField = textField;
    }

    @Override
    public void clear() {
        textField.clear();
    }
}

Is there any way I can get the coordinates of addressTextField relative to my Form?

NOTE: My popup is added on a Pane particulary the coverPane which is above my Form and they are all under StackPane.

Body:
These guys suggest you to use something like:

Bounds boundsInScene = addressTextField.localToScene(addressTextField.getBoundsInLocal());

and then use

boundsInScene.getMinX()
boundsInScene.getMinY()
boundsInScene.getMaxX()
boundsInScene.getMaxY()
boundsInScene.getWidth()
boundsInScene.getHeight()

to get the values of your component relative to the Scene


问:
FirefoxDriver do not launch any URL and perform any action
I have started a clear CentOS with Eclipse Neon, newest Selenium 3.7.1 and Firefox 52.4.
I'm trying to invoke any URL but Firefox starts and do nothing. I do not have any proxy.

I was trying to starts Firefox with default page like this:

```<code>FirefoxProfile fp = new FirefoxProfile();
fp.setPreference("browser.startup.homepage", URL);
fp.setPreference("startup.homepage_welcome_url", URL);
fp.setPreference("startup.homepage_welcome_url.additional", URL);
</code>```

it worked, but just page has been opened, nothing more.

It is common problem? How can i fix this?

答:
You mentioned of using Selenium 3.7.1 and Firefox 52.4.

Release Notes of GeckoDriver clearly mentions that :

Note that with geckodriver 0.19.0 the following versions are recommended: - Firefox 55.0 (and greater) - Selenium 3.5 (and greater)

So as you are using, Selenium 3.7.1 you mustn't be using below geckodriver 0.19.0. Hence your solution would be to bump up your Firefox to v56.x level.

Body:
I have started a clear CentOS with Eclipse Neon, newest Selenium 3.7.1 and Firefox 52.4.
I'm trying to invoke any URL but Firefox starts and do nothing. I do not have any proxy.

I was trying to starts Firefox with default page like this:

FirefoxProfile fp = new FirefoxProfile();
fp.setPreference("browser.startup.homepage", URL);
fp.setPreference("startup.homepage_welcome_url", URL);
fp.setPreference("startup.homepage_welcome_url.additional", URL);

it worked, but just page has been opened, nothing more.

It is common problem? How can i fix this?


问:
How to check whether input value is integer or float?
How to check whether input value is integer or float?

Suppose 312/100=3.12
Here i need check whether 3.12 is a float value or integer value, i.e., without any decimal place value.

答:
The ceil and floor methods will help you determine if the number is a whole number.

However if you want to determine if the number can be represented by an int value.

```<code>if(value == (int) value)
</code>```

or a long (64-bit integer)

```<code>if(value == (long) value)
</code>```

or can be safely represented by a float without a loss of precision

```<code>if(value == (float) value)
</code>```

BTW: don't use a 32-bit float unless you have to. In 99% of cases a 64-bit double is a better choice.

ContentLicense: CC BY-SA 4.0

Body:
The ceil and floor methods will help you determine if the number is a whole number.

However if you want to determine if the number can be represented by an int value.

if(value == (int) value)

or a long (64-bit integer)

if(value == (long) value)

or can be safely represented by a float without a loss of precision

if(value == (float) value)

BTW: don't use a 32-bit float unless you have to. In 99% of cases a 64-bit double is a better choice.

ContentLicense: CC BY-SA 2.5


问:
Android Azure Offline Sync - Not completing sync
I have an android app with Azure Mobile Services and implemented Offline Sync. The app works well but when syncing data it seems not to complete so there is always a few rows on tables which have not synced?

Anyone have any ideas what the problem might be. I believe that on the next try it would finish where it left off or am I wrong?

Thanks in advance

答:
Bruce's answer is fine but I used a slightly different method without the need to use fiddler.

I change my connection from this

```<code>mClient = new MobileServiceClient("[AZUREWEBSITE]", cntxall);
                mClient.setAndroidHttpClientFactory(new MyOkHttpClientFactory());
</code>```

To this

```<code>mClient = new MobileServiceClient("[AZUREWEBSITE]", cntxall).withFilter(
                        new ServiceFilter() {
                            @Override
                            public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request, NextServiceFilterCallback nextServiceFilter) {
                                // Get the request contents
                                String url = request.getUrl();
                                String content = request.getContent();

                                if (url != null) {
                                    Log.d("Request URL:", url);
                                }

                                if (content != null) {
                                    Log.d("Request Content:", content);
                                }

                                // Execute the next service filter in the chain
                                ListenableFuture<ServiceFilterResponse> responseFuture = nextServiceFilter.onNext(request);

                                Futures.addCallback(responseFuture, new FutureCallback<ServiceFilterResponse>() {
                                    @Override
                                    public void onFailure(Throwable e) {
                                        Log.d("Exception:", e.getMessage());
                                    }

                                    @Override
                                    public void onSuccess(ServiceFilterResponse response) {
                                        if (response != null && response.getContent() != null) {
                                            Log.d("Response Content:", response.getContent());
                                        }
                                    }
                                });

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

This is the logging method for Azure connections and shows the request in the log.

Body:
Bruce's answer is fine but I used a slightly different method without the need to use fiddler.

I change my connection from this

mClient = new MobileServiceClient("[AZUREWEBSITE]", cntxall);
                mClient.setAndroidHttpClientFactory(new MyOkHttpClientFactory());

To this

mClient = new MobileServiceClient("[AZUREWEBSITE]", cntxall).withFilter(
                        new ServiceFilter() {
                            @Override
                            public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request, NextServiceFilterCallback nextServiceFilter) {
                                // Get the request contents
                                String url = request.getUrl();
                                String content = request.getContent();

                                if (url != null) {
                                    Log.d("Request URL:", url);
                                }

                                if (content != null) {
                                    Log.d("Request Content:", content);
                                }

                                // Execute the next service filter in the chain
                                ListenableFuture<ServiceFilterResponse> responseFuture = nextServiceFilter.onNext(request);

                                Futures.addCallback(responseFuture, new FutureCallback<ServiceFilterResponse>() {
                                    @Override
                                    public void onFailure(Throwable e) {
                                        Log.d("Exception:", e.getMessage());
                                    }

                                    @Override
                                    public void onSuccess(ServiceFilterResponse response) {
                                        if (response != null && response.getContent() != null) {
                                            Log.d("Response Content:", response.getContent());
                                        }
                                    }
                                });

                                return responseFuture;
                            }
                        }
                );

This is the logging method for Azure connections and shows the request in the log.


问:
Call a class method as soon as an object it extends is created
Assume we have the following class (simplified):

```<code>class SuperConfig {
    public $mainDir;

    public function setDir() {
        $this->mainDir = "path/to/dir";
    }
}
</code>```

This class is supposed to be extended in EVERY other class in the project, and I do need the setDir() function of the parent to be executed. Obviously, I could do it like this:

```<code>class A extends SuperConfig() {
    public function __construct() {
        parent::setDir();
    }
    // ... other stuff is about to be done ...
}
</code>```

and I could access the properties in the child class like this:

```<code>class A extends SuperConfig {
    public function doSomething() {
        SuperConfig::mainDir;
    }
}
</code>```

This is a viable solution, but I got multiple hundreds of classes and doing this in every single one seems tedious. So, is there a way to do something like this:

```<code>class SuperConfig {
    public $mainDir;

    public function __extend() {
        $this->setDir();
    }

    public function setDir() {
        $this->mainDir = "path/to/dir";
    }
}
</code>```

__extend() obviously doesn't work like that, but I'm wondering is there is a trick how I could make this work.

答:
Read deceze's answer for an actual solution to your problem.

I would like to point out tho, that you should not extend every class in your project from a Config class. There are several ways how you could improve that.

1.) Create a static config class which you simply can call everywhere without the need of creation

```<code>class SuperConfig {
    protected static $mainDir = null;

    public static function setMainDir($dir) {
        self::$mainDir = $dir;
    }
}
</code>```

2.) Create a trait rather then a parenting class.

```<code>trait SuperConfig {
    protected $mainDir = null;

    public function setMainDir($dir) {
        $this->mainDir = $dir;
    }
}
</code>```

which you then can use inside your classes:

```<code>class XYZ {
    use SuperConfig;

    public function doSomething() {
        $this->setMainDir('path/to/your/dir/');
    }
}
</code>```

Note that you can do that in the constructor too (which is kinda what you want).

Im not saying those two solutions are the best, but I dont like the thought of extending all classes from a config class. Just does not make much sence. Just imagine that you can only extend from one class per time, while you can use as many traits as you wish (and also have as many static classes as you need).

Body:
Assume we have the following class (simplified):

class SuperConfig {
    public $mainDir;

    public function setDir() {
        $this->mainDir = "path/to/dir";
    }
}

This class is supposed to be extended in EVERY other class in the project, and I do need the setDir() function of the parent to be executed. Obviously, I could do it like this:

class A extends SuperConfig() {
    public function __construct() {
        parent::setDir();
    }
    // ... other stuff is about to be done ...
}

and I could access the properties in the child class like this:

class A extends SuperConfig {
    public function doSomething() {
        SuperConfig::mainDir;
    }
}

This is a viable solution, but I got multiple hundreds of classes and doing this in every single one seems tedious. So, is there a way to do something like this:

class SuperConfig {
    public $mainDir;

    public function __extend() {
        $this->setDir();
    }

    public function setDir() {
        $this->mainDir = "path/to/dir";
    }
}

__extend() obviously doesn't work like that, but I'm wondering is there is a trick how I could make this work.

Body:
Read deceze's answer for an actual solution to your problem.

I would like to point out tho, that you should not extend every class in your project from a Config class. There are several ways how you could improve that.

1.) Create a static config class which you simply can call everywhere without the need of creation

class SuperConfig {
    protected static $mainDir = null;

    public static function setMainDir($dir) {
        self::$mainDir = $dir;
    }
}

2.) Create a trait rather then a parenting class.

trait SuperConfig {
    protected $mainDir = null;

    public function setMainDir($dir) {
        $this->mainDir = $dir;
    }
}

which you then can use inside your classes:

class XYZ {
    use SuperConfig;

    public function doSomething() {
        $this->setMainDir('path/to/your/dir/');
    }
}

Note that you can do that in the constructor too (which is kinda what you want).

Im not saying those two solutions are the best, but I dont like the thought of extending all classes from a config class. Just does not make much sence. Just imagine that you can only extend from one class per time, while you can use as many traits as you wish (and also have as many static classes as you need).


问:
Bash script, case statement and sub-menus
I wish to run a script with a case statement leading to choices between other lists of choices (sort of sub-menus) between scripts :

```<code>#!/bin/bash

echo "Your choice ?"
echo "1) Foo"
echo "2) Bar"
echo "3) Stuff"
read case;

case $case in

#and this is where I would like to allow
#(here a simplified example I do not manage to code)

1) What script ?    # may I use another case statement ?
    a) Foo1;;
    b) Foo2;;
2) What script ?    # d°
    a) Bar1;;
    b) Bar2;;
    c) Bar3;;

esac
</code>```

Foo1, Foo2, Bar1, Bar2 and Bar3 being in fact bash scripts, I would like to call, eg, sh Foo1 from within the script.

How must I proceed :
May I include a case statement within a case statement (better than if statement, if the choices are numerous) ?
And how do I call a script from within another script ?

Thanks in advance for your help

ThG

答:
Yes, you can nest case statements. You should also consider using a select statement instead of all those echo and read statements.

```<code>options=("Option 1" "Option 2" "Option3" "Quit")
optionsprompt='Please enter your choice: '

sub1=("Option 1 sub 1" "Option 1 sub 2")
sub1prompt='Please enter your choice: '

PS3=$optionsprompt
select opt in "${options[@]}"
do
    case $opt in
        "Option 1")
            echo "you chose choice 1"
            PS3=$sub1prompt
            select sub1opt in "${sub1[@]}"
            do
                case $sub1opt in
                    "Option 1 sub 1")
                        echo "you chose choice 2"
                        ;;
                    "Option 1 sub 2")
                        echo "you chose choice 2"
                        ;;
                 esac
            done
            ;;
        "Option 2")
            echo "you chose choice 2"
            ;;
        "Option 2")
            echo "you chose choice 3"
            ;;
        "Quit")
            break
            ;;
        *) echo invalid option;;
    esac
done
</code>```

The first level menu would look like this:

```<code>1) Option 1
2) Option 2
3) Option3
4) Quit
Please enter your choice:
</code>```

However, that can get very hairy very quickly. It would be better to break it up into functions where the inner select/case statements are in separate functions or are abstracted so you can pass arguments to control them.

To call another script, you might want to set a variable that holds the directory. It would look something like this:

```<code>basedir=/some/path

case ...
...
    $basedir/Foo    # call the script
</code>```

Body:
I wish to run a script with a case statement leading to choices between other lists of choices (sort of sub-menus) between scripts :

#!/bin/bash

echo "Your choice ?"
echo "1) Foo"
echo "2) Bar"
echo "3) Stuff"
read case;

case $case in

#and this is where I would like to allow
#(here a simplified example I do not manage to code)

1) What script ?    # may I use another case statement ?
    a) Foo1;;
    b) Foo2;;
2) What script ?    # d°
    a) Bar1;;
    b) Bar2;;
    c) Bar3;;

esac

Foo1, Foo2, Bar1, Bar2 and Bar3 being in fact bash scripts, I would like to call, eg, sh Foo1 from within the script.

How must I proceed :
May I include a case statement within a case statement (better than if statement, if the choices are numerous) ?
And how do I call a script from within another script ?

Thanks in advance for your help

ThG

Body:
Yes, you can nest case statements. You should also consider using a select statement instead of all those echo and read statements.

options=("Option 1" "Option 2" "Option3" "Quit")
optionsprompt='Please enter your choice: '

sub1=("Option 1 sub 1" "Option 1 sub 2")
sub1prompt='Please enter your choice: '

PS3=$optionsprompt
select opt in "${options[@]}"
do
    case $opt in
        "Option 1")
            echo "you chose choice 1"
            PS3=$sub1prompt
            select sub1opt in "${sub1[@]}"
            do
                case $sub1opt in
                    "Option 1 sub 1")
                        echo "you chose choice 2"
                        ;;
                    "Option 1 sub 2")
                        echo "you chose choice 2"
                        ;;
                 esac
            done
            ;;
        "Option 2")
            echo "you chose choice 2"
            ;;
        "Option 2")
            echo "you chose choice 3"
            ;;
        "Quit")
            break
            ;;
        *) echo invalid option;;
    esac
done

The first level menu would look like this:

1) Option 1
2) Option 2
3) Option3
4) Quit
Please enter your choice:

However, that can get very hairy very quickly. It would be better to break it up into functions where the inner select/case statements are in separate functions or are abstracted so you can pass arguments to control them.

To call another script, you might want to set a variable that holds the directory. It would look something like this:

basedir=/some/path

case ...
...
    $basedir/Foo    # call the script


问:
Saving plot with high resolution image
Since, i'm a newbie to python. I was trying to save a plot using matplotlib in python with the command plt.savefig().
The problem is that the image being save is low in resolution. Unable to read data points.

I was wondering if there is a way to save such figures in a very high resolution?

答:
You can use savfig() to export to an image file with specification of the dpi:

```<code>import matplotlib.pyplot as plt
...
plt.savefig('plot_name.png', dpi = 300)
</code>```

You can choose needed dpi by yourself. I hope it will be useful for you.

Title: Saving plot with high resolution image

Body:
You can use savfig() to export to an image file with specification of the dpi:

import matplotlib.pyplot as plt
...
plt.savefig('plot_name.png', dpi = 300)

You can choose needed dpi by yourself. I hope it will be useful for you.


问:
How to draw a continuous line with mouse on JavaFX canvas?
The code below results in a JavaFX Canvas that can be drawn on with the mouse pointer but skips some points, i.e., leaves gaps if one tries to draw a continuous line. The gapping intensifies as pointer speed increases.

What causes this behaviour and what can be done to achieve a well-connected line? (N.B., I'm looking for an answer that explicitly toggles each single pixel the pointer passes over to black, not operations such as smoothing or connecting dots, etc.)

```<code>public class DrawingSample extends Application {
    public void start(Stage stage) {
        FlowPane flowPane = new FlowPane();
        Canvas canvas = new Canvas(300, 300);
        flowPane.getChildren().add(canvas);
        GraphicsContext graphicsContext = canvas.getGraphicsContext2D();

        graphicsContext.setFill(Color.WHITE);
        graphicsContext.fillRect(0, 0, 300, 300);

        canvas.setOnMouseDragged((event) -> {
            graphicsContext.setFill(Color.BLACK);
            graphicsContext.fillRect(event.getX(), event.getY(), 1, 1);
        });

        stage.setScene(new Scene(flowPane));
        stage.show();
    }

    public static void main(String[] args) {
        launch(DrawingSample.class);
    }
}
</code>```

The following figure demonstrates three lines drawn from left to right at increasing speeds as we go down.

答:
Sorry about previous message, should have asked a question in a new thread, right?

Here's a solution that works better, not creating the strange lines like in the scribbletest above.

```<code>canvas.addEventHandler(MouseEvent.MOUSE_PRESSED,
        new EventHandler<MouseEvent>(){
    @Override
    public void handle(MouseEvent event) {
        graphicsContext.beginPath();
        graphicsContext.moveTo(event.getX(), event.getY());
        graphicsContext.stroke();

    }
});

canvas.addEventHandler(MouseEvent.MOUSE_DRAGGED,
        new EventHandler<MouseEvent>(){
    @Override
    public void handle(MouseEvent event) {
        graphicsContext.lineTo(event.getX(), event.getY());
        graphicsContext.stroke();
        graphicsContext.closePath();
        graphicsContext.beginPath();
        graphicsContext.moveTo(event.getX(), event.getY());
    }
});

canvas.addEventHandler(MouseEvent.MOUSE_RELEASED,
        new EventHandler<MouseEvent>(){
    @Override
    public void handle(MouseEvent event) {
        graphicsContext.lineTo(event.getX(), event.getY());
        graphicsContext.stroke();
        graphicsContext.closePath();
    }
});
</code>```

Body:
The code below results in a JavaFX Canvas that can be drawn on with the mouse pointer but skips some points, i.e., leaves gaps if one tries to draw a continuous line. The gapping intensifies as pointer speed increases.

What causes this behaviour and what can be done to achieve a well-connected line? (N.B., I'm looking for an answer that explicitly toggles each single pixel the pointer passes over to black, not operations such as smoothing or connecting dots, etc.)

public class DrawingSample extends Application {
    public void start(Stage stage) {
        FlowPane flowPane = new FlowPane();
        Canvas canvas = new Canvas(300, 300);
        flowPane.getChildren().add(canvas);
        GraphicsContext graphicsContext = canvas.getGraphicsContext2D();

        graphicsContext.setFill(Color.WHITE);
        graphicsContext.fillRect(0, 0, 300, 300);

        canvas.setOnMouseDragged((event) -> {
            graphicsContext.setFill(Color.BLACK);
            graphicsContext.fillRect(event.getX(), event.getY(), 1, 1);
        });

        stage.setScene(new Scene(flowPane));
        stage.show();
    }

    public static void main(String[] args) {
        launch(DrawingSample.class);
    }
}

The following figure demonstrates three lines drawn from left to right at increasing speeds as we go down.

Body:
Sorry about previous message, should have asked a question in a new thread, right?

Here's a solution that works better, not creating the strange lines like in the scribbletest above.

canvas.addEventHandler(MouseEvent.MOUSE_PRESSED,
        new EventHandler<MouseEvent>(){
    @Override
    public void handle(MouseEvent event) {
        graphicsContext.beginPath();
        graphicsContext.moveTo(event.getX(), event.getY());
        graphicsContext.stroke();

    }
});

canvas.addEventHandler(MouseEvent.MOUSE_DRAGGED,
        new EventHandler<MouseEvent>(){
    @Override
    public void handle(MouseEvent event) {
        graphicsContext.lineTo(event.getX(), event.getY());
        graphicsContext.stroke();
        graphicsContext.closePath();
        graphicsContext.beginPath();
        graphicsContext.moveTo(event.getX(), event.getY());
    }
});

canvas.addEventHandler(MouseEvent.MOUSE_RELEASED,
        new EventHandler<MouseEvent>(){
    @Override
    public void handle(MouseEvent event) {
        graphicsContext.lineTo(event.getX(), event.getY());
        graphicsContext.stroke();
        graphicsContext.closePath();
    }
});


问:
Using command button to automate a different sheet
I am trying automate my excel workbook consists of 5 sheets . There is one summary page where I am including a command button which basically allows to upload a file and then fills up in specific sheets.
The error I am getting is instead of filling up the cells in specified sheets its filling up cells in the summary page i.e the page with the button. This is the code I have written so far.
      The below is an example where I am trying to direct a file with extension SIG in sheet 3

```<code>Set fd = Application.FileDialog(msoFileDialogOpen)
    With fd
   .AllowMultiSelect = True
.Filters.Clear
.Filters.Add "All files", "*.*"
.Filters.Add "ID Files", "*.ID", 1
.FilterIndex = 1
.Title = "Select SSI Identity File"
.InitialFileName = ""
  If .Show = -1 Then
  ReDim selectedPaths(.SelectedItems.Count)
    For I = 0 To .SelectedItems.Count - 1
        selectedPaths(I) = .SelectedItems(I + 1)
        Close #1

If Right$(selectedPaths(I), 3) = "SIG" Then
Sheets(3).Select
Open selectedPaths(I) For Input As #1

x = 4
        txt = Input(LOF(1), 1)

        With RegExp
       .Pattern = "\B/.*"
       .Global = True
       .IgnoreCase = False
        txt = .Replace(txt, "")
        End With

        With RegExp
       .Pattern = "S[0-9A-Z][0-9A-Z][0-9]+"
       .Global = True
    Set matches = .Execute(txt)

For Each Match In matches
        Debug.Print Match.Value
        If x Mod 30 = 0 Then
                x = x + 4
         End If
                Cells(x, 1) = Match
               x = x + 1
               Cells(x, 1) = Match
        If x Mod 30 <> 0 Then
                x = x + 1
        End If
    Next

 End With

 End If
 Next

  End If
 End With
 End Sub
</code>```

Thanks for the help !

答:
I see, you select the sheet first and then fill the cells. That is not the safest way.

Try using the full reference to the cell.

Your section

```<code>    For Each Match In matches
        Debug.Print Match.Value
        If x Mod 30 = 0 Then
                x = x + 4
         End If
                Cells(x, 1) = Match
               x = x + 1
               Cells(x, 1) = Match
        If x Mod 30 <> 0 Then
                x = x + 1
        End If
    Next
</code>```

should look like this:

```<code>    For Each Match In matches
        Debug.Print Match.Value
        If x Mod 30 = 0 Then
                x = x + 4
         End If
               ThisWorkbook.Sheets(3).Cells(x, 1) = Match
               x = x + 1
               ThisWorkbook.Sheets(3).Cells(x, 1) = Match
        If x Mod 30 <> 0 Then
                x = x + 1
        End If
    Next
</code>```

I hope this helps, I think it really is that simple.

Body:
I am trying automate my excel workbook consists of 5 sheets . There is one summary page where I am including a command button which basically allows to upload a file and then fills up in specific sheets.
The error I am getting is instead of filling up the cells in specified sheets its filling up cells in the summary page i.e the page with the button. This is the code I have written so far.
      The below is an example where I am trying to direct a file with extension SIG in sheet 3

Set fd = Application.FileDialog(msoFileDialogOpen)
    With fd
   .AllowMultiSelect = True
.Filters.Clear
.Filters.Add "All files", "*.*"
.Filters.Add "ID Files", "*.ID", 1
.FilterIndex = 1
.Title = "Select SSI Identity File"
.InitialFileName = ""
  If .Show = -1 Then
  ReDim selectedPaths(.SelectedItems.Count)
    For I = 0 To .SelectedItems.Count - 1
        selectedPaths(I) = .SelectedItems(I + 1)
        Close #1

If Right$(selectedPaths(I), 3) = "SIG" Then
Sheets(3).Select
Open selectedPaths(I) For Input As #1

x = 4
        txt = Input(LOF(1), 1)

        With RegExp
       .Pattern = "\B/.*"
       .Global = True
       .IgnoreCase = False
        txt = .Replace(txt, "")
        End With

        With RegExp
       .Pattern = "S[0-9A-Z][0-9A-Z][0-9]+"
       .Global = True
    Set matches = .Execute(txt)

For Each Match In matches
        Debug.Print Match.Value
        If x Mod 30 = 0 Then
                x = x + 4
         End If
                Cells(x, 1) = Match
               x = x + 1
               Cells(x, 1) = Match
        If x Mod 30 <> 0 Then
                x = x + 1
        End If
    Next

 End With

 End If
 Next

  End If
 End With
 End Sub

Thanks for the help !

Body:
I see, you select the sheet first and then fill the cells. That is not the safest way.

Try using the full reference to the cell.

Your section

    For Each Match In matches
        Debug.Print Match.Value
        If x Mod 30 = 0 Then
                x = x + 4
         End If
                Cells(x, 1) = Match
               x = x + 1
               Cells(x, 1) = Match
        If x Mod 30 <> 0 Then
                x = x + 1
        End If
    Next

should look like this:

    For Each Match In matches
        Debug.Print Match.Value
        If x Mod 30 = 0 Then
                x = x + 4
         End If
               ThisWorkbook.Sheets(3).Cells(x, 1) = Match
               x = x + 1
               ThisWorkbook.Sheets(3).Cells(x, 1) = Match
        If x Mod 30 <> 0 Then
                x = x + 1
        End If
    Next

I hope this helps, I think it really is that simple.


问:
Unable to automate Apache cordova app using appium
I am trying to automate the Apache cordova app using appium but not able to perform the click on floating button action.
I can launch the app, click on other tabs/buttons using appium.
I tried following code

```<code>driver.findElementByXPath("//android.widget.Button[@content-desc='closeadd']").click()
</code>```

This code not giving me error but not clicking on "+" button also.

答:
You have to switch the driver's context to NATIVE_APP before clicking the floating button. If that's not the case, then a workaround would be to TAP blindly on a particular point using coordinates. You can use percentage :

```<code>public static void tapPercentage(AppiumDriver driver, double x_percentage, double y_percentage) throws Exception {
    Dimension size = driver.manage().window().getSize();

    int xPoint = (int) (size.width * x_percentage);
    int yPoint = (int) (size.height * y_percentage);
    TouchAction touchAction = new TouchAction(driver);
    touchAction.tap(xPoint, yPoint).perform();
}
</code>```

Use trial and error method to find exact percentage values to click on your floating button.

Reference : Appium Forum

Body:
I am trying to automate the Apache cordova app using appium but not able to perform the click on floating button action.
I can launch the app, click on other tabs/buttons using appium.
I tried following code

driver.findElementByXPath("//android.widget.Button[@content-desc='closeadd']").click()

This code not giving me error but not clicking on "+" button also.

Body:
You have to switch the driver's context to NATIVE_APP before clicking the floating button. If that's not the case, then a workaround would be to TAP blindly on a particular point using coordinates. You can use percentage :

public static void tapPercentage(AppiumDriver driver, double x_percentage, double y_percentage) throws Exception {
    Dimension size = driver.manage().window().getSize();

    int xPoint = (int) (size.width * x_percentage);
    int yPoint = (int) (size.height * y_percentage);
    TouchAction touchAction = new TouchAction(driver);
    touchAction.tap(xPoint, yPoint).perform();
}

Use trial and error method to find exact percentage values to click on your floating button.

Reference : Appium Forum


问:
spinner is not showing after 2000ms
want to show the spinner after the form submission for 2000 ms for that I have implemented set timeout function but it is not going inside that function even after 2000ms.
below my code snippet of component and html

import { Component, OnInit } from '@angular/core';
import { DataService } from '../../../shared/services/data.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-dummy',
  templateUrl: './dummy.component.html',
  styleUrls: ['./dummy.component.scss']
})
export class DummyComponent implements OnInit {
  loading= false;
  users= [];
  pinId;
  name: string;
  constructor(private router: Router, private dataService: DataService) {
  }

  ngOnInit() {}

  submit(name) {
  this.loading = true;
 this.dataService.getUsers().subscribe(data => {
     this.users = data;
     console.log(this.users);
this.users.forEach(element => {
  console.log(element);
  if (element.name === this.name) {
    this.pinId = element.pinId;
    console.log(this.pinId);
setTimeout(function() {
console.log(this.pinId);
                        if (this.pinId) {
                          this.loading = false;
                          this.router.navigate(['schedule']);
                        }
                      }, 2000);
  }
});
   }, error => {
     console.log('error');
   });

}

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><mat-card>
<div class="example-container">
  <mat-form-field color="accent">
    <input matInput placeholder="Input" [(ngModel)]="name">
  </mat-form-field>
    <button mat-raised-button color="accent" (click)="submit(name)">Submit</button>
<mat-spinner *ngIf="loading"  color="accent"></mat-spinner>
</div>
</mat-card></code>```

I want to show  the spinner after the form submission for 2000 ms for that I have implemented set timeout function but it is not going inside that function even after 2000ms.

答:
In typescript function key word will not work</p>

```<code>setTimeout(()=> {
console.log(this.pinId);
                        if (this.pinId) {
                          this.loading = false;
                          this.router.navigate(['schedule']);
                        }
                      }, 2000);
</code>```

Title: spinner is not showing after 2000ms

Body:
want to show the spinner after the form submission for 2000 ms for that I have implemented set timeout function but it is not going inside that function even after 2000ms.
below my code snippet of component and html

import { Component, OnInit } from '@angular/core';
import { DataService } from '../../../shared/services/data.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-dummy',
  templateUrl: './dummy.component.html',
  styleUrls: ['./dummy.component.scss']
})
export class DummyComponent implements OnInit {
  loading= false;
  users= [];
  pinId;
  name: string;
  constructor(private router: Router, private dataService: DataService) {
  }

  ngOnInit() {}

  submit(name) {
  this.loading = true;
 this.dataService.getUsers().subscribe(data => {
     this.users = data;
     console.log(this.users);
this.users.forEach(element => {
  console.log(element);
  if (element.name === this.name) {
    this.pinId = element.pinId;
    console.log(this.pinId);
setTimeout(function() {
console.log(this.pinId);
                        if (this.pinId) {
                          this.loading = false;
                          this.router.navigate(['schedule']);
                        }
                      }, 2000);
  }
});
   }, error => {
     console.log('error');
   });

}

}

<mat-card>

  <mat-form-field color="accent">
    <input matInput placeholder="Input" [(ngModel)]="name">
  </mat-form-field>
    <button mat-raised-button color="accent" (click)="submit(name)">Submit</button>
<mat-spinner *ngIf="loading"  color="accent"></mat-spinner>

</mat-card>

I want to show  the spinner after the form submission for 2000 ms for that I have implemented set timeout function but it is not going inside that function even after 2000ms.

Body:
In typescript function key word will not work

setTimeout(()=> {
console.log(this.pinId);
                        if (this.pinId) {
                          this.loading = false;
                          this.router.navigate(['schedule']);
                        }
                      }, 2000);


问:
JavaScript: Changing innerHtml to a radio button value
in our html we have a document with a radio button and a value.

This Code opens a popup:

```<code><tr>
      <td><input id="vname" name="vname"></td>
      <td>Cell</td>
      <td id="eins"><button id="a1" class="button button-block"/ onclick="popup1()" name="button1">Eintragen</button></td>
    </tr>

function popup1(){
    a1.name = "b1"
    window.open('schadensausmass.html', "popup", "width=700,height=600");
    alert("t")
    }
</code>```

This is the separate Html File (popup):

```<code><form name="myForm">
    <td><input type="radio" id = "radio1" name= "gleich" value="2"></td>
    <td><input type="radio" id = "radio2" name= "gleich" value="1"></td>
    <td><input type="radio" id = "radio3" name= "gleich" value="3"></td>
</form>
</table>
  <button type="button" onclick="meineFunktion()"></button>
</code>```

We want the radio button value to be set in the innerhtml of . So we tried this.

```<code>    function meineFunktion() {
    if (opener.document.getElementById("a1").name == "b1"){
    window.close('schadensausmass.html')
    opener.document.getElementById("eins").innerHTML= document.myForm.elements[1].value
}
</code>```

Unfortunately the innerHtml doesnt change. If we do it like this

```<code>opener.document.getElementById("eins").innerHTML="Foo"
</code>```

the innerHTML does change.
So the problem has something to do with document.myForm.elements[1].value
Any tips what could be wrong here?

答:
Change

document.myForm.elements[1].value

to

document.forms.myForm.elements[1].value

You have to specify that you would like to get a form in the document. Make sure myform matches the name attribute of the form.

You can read more about forms and how to get its elements here

Body:
in our html we have a document with a radio button and a value.

This Code opens a popup:

      <input id="vname" name="vname">
      Cell
      <button id="a1" class="button button-block"/ onclick="popup1()" name="button1">Eintragen</button>

function popup1(){
    a1.name = "b1"
    window.open('schadensausmass.html', "popup", "width=700,height=600");
    alert("t")
    }

This is the separate Html File (popup):

<form name="myForm">
    <input type="radio" id = "radio1" name= "gleich" value="2">
    <input type="radio" id = "radio2" name= "gleich" value="1">
    <input type="radio" id = "radio3" name= "gleich" value="3">
</form>

  <button type="button" onclick="meineFunktion()"></button>

We want the radio button value to be set in the innerhtml of . So we tried this.

    function meineFunktion() {
    if (opener.document.getElementById("a1").name == "b1"){
    window.close('schadensausmass.html')
    opener.document.getElementById("eins").innerHTML= document.myForm.elements[1].value
}

Unfortunately the innerHtml doesnt change. If we do it like this

opener.document.getElementById("eins").innerHTML="Foo"

the innerHTML does change.
So the problem has something to do with document.myForm.elements[1].value
Any tips what could be wrong here?


问:
MIN (DATE) when date is string Hive
I need a min value for a date but when I use min(date) this function doesn't work because for example 2015-5-10 is less than 2015-5-5. </p>

答:
Try converting it to date.

 MIN (TO_DATE( CONCAT ( yourdate , '00:00:00' ) ) )

You may also try this to cast the char to date if the above does not work . Then apply min

```<code>cast(to_date(from_unixtime(unix_timestamp(yourdate , 'yyyy-mm-dd'))) as date)
</code>```

Title: MIN (DATE) when date is string Hive

Body:
Try converting it to date.

 MIN (TO_DATE( CONCAT ( yourdate , '00:00:00' ) ) )

You may also try this to cast the char to date if the above does not work . Then apply min

cast(to_date(from_unixtime(unix_timestamp(yourdate , 'yyyy-mm-dd'))) as date)


问:
Get rid of NaN as key in python dictionary
I have a dictionary in which one key is a NaN, and I want to delete the key and its corresponding value. I have tried this:

```<code>from math import isnan

clean_dict = filter(lambda k: not isnan(k), dict_HMDB_ID)
</code>```

but the clean_dict is not a dictionary. I want to output it from python, but I get ''

答:
you could do:

```<code>from math import nan
dict_HMDB_ID.pop(nan)
clean_dict = dict_HMDB_ID
</code>```

or the other way around if you wna to preserve dict_HMDB_ID

```<code>from math import nan
clean_dict = dict(dict_HMDB_ID)
clean_dict.pop(nan)
</code>```

Body:
I have a dictionary in which one key is a NaN, and I want to delete the key and its corresponding value. I have tried this:

from math import isnan

clean_dict = filter(lambda k: not isnan(k), dict_HMDB_ID)

but the clean_dict is not a dictionary. I want to output it from python, but I get ''

Body:
you could do:

from math import nan
dict_HMDB_ID.pop(nan)
clean_dict = dict_HMDB_ID

or the other way around if you wna to preserve dict_HMDB_ID

from math import nan
clean_dict = dict(dict_HMDB_ID)
clean_dict.pop(nan)


问:
Visual Studio Intelligent Project Templates
I need to construct a Visual Studio project template that has a certain amount of intelligence. I've discovered a way to get Visual Studio to call my custom code upon creation of a new project from my template, the custom code displays a dialog box and gathers information from the user, then defines additional substitutions that the project template can use. All well and good.

This template was previously a collection of several very similar templates, which differed only in which interface was implemented by the main class. My goal is to condense this collection of templates into a single "smart template" which automatically implements the correct interface depending on user input.

To do that, I need to modify the generated code at the time it is created. Visual Studio calls my custom wizard code after the new project is created, then I'd like to go into the newly-created C# code and add the Interface implementation programmatically. I'd like to add the " : IMyInterface" after the main class, then trigger IntelliSense to expand the implementation for me. This is the part I don't know how to do.

Can anyone give me some pointers on how to automate the imlementation of an interface using the Visual Studio object model?

答:
The problem using GAX is it requires end users to download the framework before installing a template which was built using GAX.

A better solution is using VS 2010 SDK to build VSIX, which will not require end users to download any additional plug-in to install your template. You can have a look here: Multi-Project Templates with Wizard: Visual Studio 2010 Sample