问:
Remove HTML paragraph using removeChild
I wrote a code like below:

```<code>     <input type="button" value="remove" onclick="remove()"/>

     <p id="p2">
        before hr
        <hr/>
        after hr
     </p>

  <script>
     function remove() {
        var p = document.getElementById('p2');
        p.parentNode.removeChild(p);
     }
  </script>
</code>```

When I hit the button, only "before hr" disappear - hr and "after hr" text don't.

If I change
 to
 :

```<code><div id="p2">
    before hr
    <hr/>
    after hr
 </div>
</code>```

everything works properly (i.e. like I supposed it should works ;) )

Could somebody explain me the reasons, please?

答:
you code is not correct, is not possible to put
 inside the

```<code><p id="p2">
        before hr
        <hr/>
        after hr
     </p>
</code>```

in a good browser the browser correct your code

```<code> <p id="p2">
            before hr
    </p>
   <hr/>
    <p>

       after hr
    </p>
</code>```

one posibility use span or div

```<code> <span id="p2">
            before hr
            <hr/>
            after hr
         </span>
</code>```

Title: Remove HTML paragraph using removeChild

Body:
I wrote a code like below:

     <input type="button" value="remove" onclick="remove()"/>

        before hr

        after hr

When I hit the button, only "before hr" disappear - hr and "after hr" text don't.

If I change
 to
 :

    before hr

    after hr

everything works properly (i.e. like I supposed it should works ;) )

Could somebody explain me the reasons, please?

Body:
you code is not correct, is not possible to put <hr> inside the <p>

<p id="p2">
        before hr
        <hr/>
        after hr
     </p>

in a good browser the browser correct your code

 <p id="p2">
            before hr
    </p>
   <hr/>
    <p>

       after hr
    </p>

one posibility use span or div

 <span id="p2">
            before hr
            <hr/>
            after hr
         </span>


来源: stackexchange

问:
UIDatepicker and a textField
i wont to use a datepickerview and a texfield.
i use it like thise, when i touch the textfiled the datepicker apears ( textfield.inputview=...) but i want when i select a date in the pickerview, it should appear in the textfield, how to do this please ??

thanks

答:
For this you will need to implement delegate for UITextField and in its - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField write following code.

```<code>- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    [textField resignFirstResponder];
</code>```

// here you can write code for setting the center of datePicker.
        return NO;
    }

After this you will have to add action methods for picker change event in this method you will set textField text from picker value.

```<code>NSDateFormatter *datePickerFormat = [[NSDateFormatter alloc] init];
    [datePickerFormat setDateFormat:@"HH:mm"]; //here specify your format..
    yourTextField.text = [datePickerFormat stringFromDate:timePicker.date];
[datePickerFormat release];
</code>```

thanks,

ContentLicense: CC BY-SA 3.0

Title: UIDatepicker and a textField

Body:
For this you will need to implement delegate for UITextField and in its - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField write following code.

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    [textField resignFirstResponder];

// here you can write code for setting the center of datePicker.
        return NO;
    }

After this you will have to add action methods for picker change event in this method you will set textField text from picker value.

NSDateFormatter *datePickerFormat = [[NSDateFormatter alloc] init];
    [datePickerFormat setDateFormat:@"HH:mm"]; //here specify your format..
    yourTextField.text = [datePickerFormat stringFromDate:timePicker.date];
[datePickerFormat release];

thanks,


问:
Custom UIView alert not appearing after successful Login
I'm trying to trigger a small, timed UIView popup after a user successfully logs in, however, I need it to appear on the screen after the LoginController is dismissed. Can anyone help in understanding where I am going wrong here? Perhaps it is necessary to trigger it from the rootViewController after the view is dismissed, but I don't know how to trigger it from the LoginController.

The LoginController dismisses properly, and the print statement is logging so I know the completion block is working properly, however the UIView is not staying on top of other views.

Should I create some sort of extension that allows me to trigger it from another class? Any tips would be greatly appreciated.

LoginController()

```<code>DispatchQueue.main.async {

    self.view.window?.rootViewController?.dismiss(animated: true, completion: {
                // completion handler after successful login
                print("completion handler: logged in")
                self.showAlert()
                })
    }
</code>```

Custom alert/popup functions

```<code>func showAlert()    {
    popupAlert = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 200))
    popupAlert?.backgroundColor = .red
    self.view.addSubview(popupAlert)

    Timer.scheduledTimer(timeInterval: 4.0, target: self, selector: #selector(dismissAlert), userInfo: nil, repeats: false)
}

@objc func dismissAlert()   {
    if popupAlert != nil {
        popupAlert.removeFromSuperview()
    }
}
</code>```

答:
It appears that the root vc is the login 1 so your code inside completion doesn't trigger , so add it to window</p>

```<code>extension UIViewController {
    func showAlert() {
        let popupAlert = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 200))
        popupAlert.backgroundColor = .red
        let wind = (UIApplication.shared.delegate as! AppDelegate).window!
        wind.addSubview(popupAlert)
        Timer.scheduledTimer(withTimeInterval: 4.0, repeats: false) { (t) in
            t.invalidate()
            popupAlert.removeFromSuperview()
        }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to trigger a small, timed UIView popup after a user successfully logs in, however, I need it to appear on the screen after the LoginController is dismissed. Can anyone help in understanding where I am going wrong here? Perhaps it is necessary to trigger it from the rootViewController after the view is dismissed, but I don't know how to trigger it from the LoginController.

The LoginController dismisses properly, and the print statement is logging so I know the completion block is working properly, however the UIView is not staying on top of other views.

Should I create some sort of extension that allows me to trigger it from another class? Any tips would be greatly appreciated.

LoginController()

DispatchQueue.main.async {

    self.view.window?.rootViewController?.dismiss(animated: true, completion: {
                // completion handler after successful login
                print("completion handler: logged in")
                self.showAlert()
                })
    }

Custom alert/popup functions

func showAlert()    {
    popupAlert = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 200))
    popupAlert?.backgroundColor = .red
    self.view.addSubview(popupAlert)

    Timer.scheduledTimer(timeInterval: 4.0, target: self, selector: #selector(dismissAlert), userInfo: nil, repeats: false)
}

@objc func dismissAlert()   {
    if popupAlert != nil {
        popupAlert.removeFromSuperview()
    }
}

Body:
It appears that the root vc is the login 1 so your code inside completion doesn't trigger , so add it to window

extension UIViewController {
    func showAlert() {
        let popupAlert = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 200))
        popupAlert.backgroundColor = .red
        let wind = (UIApplication.shared.delegate as! AppDelegate).window!
        wind.addSubview(popupAlert)
        Timer.scheduledTimer(withTimeInterval: 4.0, repeats: false) { (t) in
            t.invalidate()
            popupAlert.removeFromSuperview()
        }
    }
}


问:
how to trigger button to open up user input/text box
so im trying to create "kanban/to do list" website, and im having trouble with triggering the add button. Im trying to trigger "add" button to open up a user input box. So I have this "add" button which creates a small box. but i cannot figure out how to add a small area in that box where i could write any type of text.

Ive done alot of reasearch, but no one is making the same type of to do list app.

```<code>div class="board">
    <div class="board-column todo">
            <button type="button" class="btn" onclick="addEvent()">+</button>
            <div class="board-column-header">To do</div>
            <div class="board-column-content"></div>

.btn {
    display: inline-block;
    position: absolute;
    z-index: 1;
    right: 10px;
    top: 10px;
    display:block;
    width:30px;
    height:30px;
    line-height:25px;
    border: 2px solid #fff;
    border-radius: 50%;
    color: #fff;
    background: #4A9FF9;
    text-align:center;
    box-shadow: 0 0 3px rgba(92, 92, 92, 0.2);
    font-size:20px;
    cursor: pointer;
</code>```

forgot to mention. in this spesific box, i want to have that input/text box

```<code>
    board-item-content {
        position: relative;
        padding: 20px;
        background: #fff;
        border-radius: 10px;
        font-size: 20px;
        cursor: pointer;
        box-shadow: 1px 1px 5px 0 rgba(92, 92, 92, 0.2);
    }
</code>```

答:
You can do something like that using jquery / javascript

Note : this is small idea example, you can change as per your need.

function addEvent() {
var html = "<input type='text' name='box'>";
$('.board-column-content').append(html);

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.btn {
    display: inline-block;
    position: absolute;
    z-index: 1;
    right: 10px;
    top: 10px;
    display:block;
    width:30px;
    height:30px;
    line-height:25px;
    border: 2px solid #fff;
    border-radius: 50%;
    color: #fff;
    background: #4A9FF9;
    text-align:center;
    box-shadow: 0 0 3px rgba(92, 92, 92, 0.2);
    font-size:20px;
    cursor: pointer;</code>```

            <button type="button" class="btn" onclick="addEvent()">+</button>

To do

```

Body:
so im trying to create "kanban/to do list" website, and im having trouble with triggering the add button. Im trying to trigger "add" button to open up a user input box. So I have this "add" button which creates a small box. but i cannot figure out how to add a small area in that box where i could write any type of text.

Ive done alot of reasearch, but no one is making the same type of to do list app.

div class="board">

            <button type="button" class="btn" onclick="addEvent()">+</button>

To do

.btn {
    display: inline-block;
    position: absolute;
    z-index: 1;
    right: 10px;
    top: 10px;
    display:block;
    width:30px;
    height:30px;
    line-height:25px;
    border: 2px solid #fff;
    border-radius: 50%;
    color: #fff;
    background: #4A9FF9;
    text-align:center;
    box-shadow: 0 0 3px rgba(92, 92, 92, 0.2);
    font-size:20px;
    cursor: pointer;

forgot to mention. in this spesific box, i want to have that input/text box

    board-item-content {
        position: relative;
        padding: 20px;
        background: #fff;
        border-radius: 10px;
        font-size: 20px;
        cursor: pointer;
        box-shadow: 1px 1px 5px 0 rgba(92, 92, 92, 0.2);
    }

Body:
You can do something like that using jquery / javascript

Note : this is small idea example, you can change as per your need.

function addEvent() {
var html = "<input type='text' name='box'>";
$('.board-column-content').append(html);

}

.btn {
    display: inline-block;
    position: absolute;
    z-index: 1;
    right: 10px;
    top: 10px;
    display:block;
    width:30px;
    height:30px;
    line-height:25px;
    border: 2px solid #fff;
    border-radius: 50%;
    color: #fff;
    background: #4A9FF9;
    text-align:center;
    box-shadow: 0 0 3px rgba(92, 92, 92, 0.2);
    font-size:20px;
    cursor: pointer;

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="board-column todo">
            <button type="button" class="btn" onclick="addEvent()">+</button>
            <div class="board-column-header">To do</div>
            <div class="board-column-content"></div>


问:
Android: Google Drive onActivityResult() getting resultCode 0 (RESULT_CANCELED)
I've been scouring the Google documentation and sample code and Stack Overflow for a solution to this, and while I've seen a number of people running into the same symptoms I haven't found anything that helps in my particular case.

Basically I'm trying to do an auth workflow for the Google Drive REST API, and while I get as far as the Google account selection page, when it returns to my calling activity, I'm always seeing a result of RESULT_CANCELED (i.e., 0) instead of RESULT_OK (i.e., -1), no matter what account is selected.

I've checked to make sure that the credentials are set up correctly on the Google developer console — and they were working previously with authentication via the now-defunct CloudRail library. (As far as I can tell, now with Google Sign-In you don't provide any client id, etc.: that's all handled on Google's end when it matches your package name.)

Here is my call for authentication:

```<code>    GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestScopes(new Scope(DriveScopes.DRIVE))
            .build();
    mSignInClient = GoogleSignIn.getClient(activity, signInOptions);
</code>```

And here is the activity's onActivityResult():

```<code>@Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
    switch (requestCode) {
        case REQUEST_GOOGLE_SIGN_IN:
            if (resultCode == Activity.RESULT_OK && resultData != null) {
                /*** NEVER GET HERE ***/
                handleSignInResult(this, resultData);
            }
            else {
                /*** ALWAYS GET HERE ***/
                Log.e(TAG, String.format("Unable to complete Google sign-in (resultCode: %d)", resultCode));
            }
        }
        break;
    }
    super.onActivityResult(requestCode, resultCode, resultData);
}
</code>```

I'm assuming that this is a case of me doing something obviously dumb and wrong — and was hoping that just typing out the question would help me figure out what it is, but that hasn't happened yet.

答:
As I expected, it was something relatively simple that I was doing wrong. So for anyone having the same issue and stepping over my body while searching for a solution, here's what I found:

While I did have the credentials in the Google developer console set up correctly, with my package name and SHA1 generated, as directed by the documentation, from mykeystore.keystore, what I missed was that Android Studio doesn't sign debug builds with mykeystore.keystore by default. Instead it uses its own provided debug.keystore.

So the thing to do is to create a new OAuth client ID with your package name and the SHA1 from Android Studio's debug.keystore instead of one's own. (You can either hunt down debug.keystore on your system, or run the Gradle "signingReport" task and get it from there.)

Hope that helps someone.

Body:
I've been scouring the Google documentation and sample code and Stack Overflow for a solution to this, and while I've seen a number of people running into the same symptoms I haven't found anything that helps in my particular case.

Basically I'm trying to do an auth workflow for the Google Drive REST API, and while I get as far as the Google account selection page, when it returns to my calling activity, I'm always seeing a result of RESULT_CANCELED (i.e., 0) instead of RESULT_OK (i.e., -1), no matter what account is selected.

I've checked to make sure that the credentials are set up correctly on the Google developer console — and they were working previously with authentication via the now-defunct CloudRail library. (As far as I can tell, now with Google Sign-In you don't provide any client id, etc.: that's all handled on Google's end when it matches your package name.)

Here is my call for authentication:

    GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestScopes(new Scope(DriveScopes.DRIVE))
            .build();
    mSignInClient = GoogleSignIn.getClient(activity, signInOptions);

And here is the activity's onActivityResult():

@Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
    switch (requestCode) {
        case REQUEST_GOOGLE_SIGN_IN:
            if (resultCode == Activity.RESULT_OK && resultData != null) {
                /*** NEVER GET HERE ***/
                handleSignInResult(this, resultData);
            }
            else {
                /*** ALWAYS GET HERE ***/
                Log.e(TAG, String.format("Unable to complete Google sign-in (resultCode: %d)", resultCode));
            }
        }
        break;
    }
    super.onActivityResult(requestCode, resultCode, resultData);
}

I'm assuming that this is a case of me doing something obviously dumb and wrong — and was hoping that just typing out the question would help me figure out what it is, but that hasn't happened yet.


问:
CDH 6.2 - add new host error: dpkg-query: no packages found matching cloudera-manager-agent
I am tring to add a new host.

but it fails with this message at the end "dpkg-query: no packages found matching cloudera-manager-agent"

The following is the "/tmp/scm_prepare_node.vQZe0yDf/scm_prepare_node.log" on the failing host:

```<code>using SSH_CLIENT to get the SCM hostname: 10.4.34.22 37758 22
opening logging file descriptor
###CLOUDERA_SCM### SCRIPT_START
###CLOUDERA_SCM### TAKE_LOCK
BEGIN flock 4
END (0)
###CLOUDERA_SCM### DETECT_ROOT
effective UID is 1000
BEGIN which pbrun
END (1)
BEGIN sudo -S id
uid=0(root) gid=0(root) groups=0(root)
END (0)
Using 'sudo ' to acquire root privileges
###CLOUDERA_SCM### DETECT_DISTRO
BEGIN grep 'Ubuntu' /etc/lsb-release
DISTRIB_ID=Ubuntu
DISTRIB_DESCRIPTION="Ubuntu 16.04.1 LTS"
END (0)
BEGIN grep DISTRIB_CODENAME /etc/lsb-release
DISTRIB_CODENAME=xenial
END (0)
BEGIN echo DISTRIB_CODENAME=xenial | cut -d = -f 2
xenial
END (0)
###CLOUDERA_SCM### DETECT_SCM
BEGIN host -t PTR 10.4.34.22
Host 22.34.4.10.in-addr.arpa. not found: 3(NXDOMAIN)
END (1)
BEGIN which python
/usr/bin/python
END (0)
BEGIN python -c 'import socket; import sys; s = socket.socket(socket.AF_INET); s.settimeout(5.0); s.connect((sys.argv[1], int(sys.argv[2]))); s.close();' 10.4.34.22 7182
END (0)
BEGIN which wget
/usr/bin/wget
END (0)
BEGIN wget -qO- -T 1 -t 1 http://169.254.169.254/latest/meta-data/public-hostname && /bin/echo
END (4)
###CLOUDERA_SCM### REPO_INSTALL
Checking https://archive.cloudera.com/cm6/6.2.0/ubuntu1604/apt/dists/
Checking https://archive.cloudera.com/cm6/6.2.0/dists/
Using
installing repository file /tmp/scm_prepare_node.vQZe0yDf/repos/ubuntu_xenial/cloudera-manager.list
repository file /tmp/scm_prepare_node.vQZe0yDf/repos/ubuntu_xenial/cloudera-manager.list installed
installing apt keys
BEGIN sudo apt-key add /tmp/scm_prepare_node.vQZe0yDf/customGPG
OK
END (0)
installing priority file /tmp/scm_prepare_node.vQZe0yDf/ubuntu_xenial
priority file /tmp/scm_prepare_node.vQZe0yDf/ubuntu_xenial installed
###CLOUDERA_SCM### REFRESH_METADATA
BEGIN sudo apt-get update
Hit:1 http://security.ubuntu.com/ubuntu xenial-security InRelease
Hit:2 http://us.archive.ubuntu.com/ubuntu xenial InRelease
Hit:3 http://us.archive.ubuntu.com/ubuntu xenial-updates InRelease
Hit:4 http://us.archive.ubuntu.com/ubuntu xenial-backports InRelease
Reading package lists...
END (0)
BEGIN sudo apt-get update
Hit:1 http://us.archive.ubuntu.com/ubuntu xenial InRelease
Hit:2 http://security.ubuntu.com/ubuntu xenial-security InRelease
Hit:3 http://us.archive.ubuntu.com/ubuntu xenial-updates InRelease
Hit:4 http://us.archive.ubuntu.com/ubuntu xenial-backports InRelease
Reading package lists...
END (0)
###CLOUDERA_SCM### PACKAGE_INSTALL cloudera-manager-agent
BEGIN sudo dpkg -l cloudera-manager-agent | grep -E '^ii[[:space:]]*cloudera-manager-agent[[:space:]]*'
dpkg-query: no packages found matching cloudera-manager-agent
END (1)
BEGIN sudo apt-cache show cloudera-manager-agent
E: No packages found
END (100)
cloudera-manager-agent must have Version=6.2.0 and Build=968826, exiting
closing logging file descriptor
</code>```

Note that:

both the master node and the new host node run ubuntu 16

Public Cloudera Repository

答:
Can you try installing the Cloudera agent manually on each node(when the number of nodes are less):

```<code>$ sudo apt-get install cloudera-manager-agent cloudera-manager-daemons
</code>```

On every cluster host, configure the Cloudera Manager Agent to point to the Cloudera Manager Server by setting the following properties in the /etc/cloudera-scm-agent/config.ini

```<code>$ sudo service cloudera-scm-agent start
</code>```

Make sure JAVA is installed in all the nodes

For some reason the sources.list.d file becomes empty after running the manager on these nodes.

Body:
I am tring to add a new host.

but it fails with this message at the end "dpkg-query: no packages found matching cloudera-manager-agent"

The following is the "/tmp/scm_prepare_node.vQZe0yDf/scm_prepare_node.log" on the failing host:

using SSH_CLIENT to get the SCM hostname: 10.4.34.22 37758 22
opening logging file descriptor
###CLOUDERA_SCM### SCRIPT_START
###CLOUDERA_SCM### TAKE_LOCK
BEGIN flock 4
END (0)
###CLOUDERA_SCM### DETECT_ROOT
effective UID is 1000
BEGIN which pbrun
END (1)
BEGIN sudo -S id
uid=0(root) gid=0(root) groups=0(root)
END (0)
Using 'sudo ' to acquire root privileges
###CLOUDERA_SCM### DETECT_DISTRO
BEGIN grep 'Ubuntu' /etc/lsb-release
DISTRIB_ID=Ubuntu
DISTRIB_DESCRIPTION="Ubuntu 16.04.1 LTS"
END (0)
BEGIN grep DISTRIB_CODENAME /etc/lsb-release
DISTRIB_CODENAME=xenial
END (0)
BEGIN echo DISTRIB_CODENAME=xenial | cut -d = -f 2
xenial
END (0)
###CLOUDERA_SCM### DETECT_SCM
BEGIN host -t PTR 10.4.34.22
Host 22.34.4.10.in-addr.arpa. not found: 3(NXDOMAIN)
END (1)
BEGIN which python
/usr/bin/python
END (0)
BEGIN python -c 'import socket; import sys; s = socket.socket(socket.AF_INET); s.settimeout(5.0); s.connect((sys.argv[1], int(sys.argv[2]))); s.close();' 10.4.34.22 7182
END (0)
BEGIN which wget
/usr/bin/wget
END (0)
BEGIN wget -qO- -T 1 -t 1 http://169.254.169.254/latest/meta-data/public-hostname && /bin/echo
END (4)
###CLOUDERA_SCM### REPO_INSTALL
Checking https://archive.cloudera.com/cm6/6.2.0/ubuntu1604/apt/dists/
Checking https://archive.cloudera.com/cm6/6.2.0/dists/
Using
installing repository file /tmp/scm_prepare_node.vQZe0yDf/repos/ubuntu_xenial/cloudera-manager.list
repository file /tmp/scm_prepare_node.vQZe0yDf/repos/ubuntu_xenial/cloudera-manager.list installed
installing apt keys
BEGIN sudo apt-key add /tmp/scm_prepare_node.vQZe0yDf/customGPG
OK
END (0)
installing priority file /tmp/scm_prepare_node.vQZe0yDf/ubuntu_xenial
priority file /tmp/scm_prepare_node.vQZe0yDf/ubuntu_xenial installed
###CLOUDERA_SCM### REFRESH_METADATA
BEGIN sudo apt-get update
Hit:1 http://security.ubuntu.com/ubuntu xenial-security InRelease
Hit:2 http://us.archive.ubuntu.com/ubuntu xenial InRelease
Hit:3 http://us.archive.ubuntu.com/ubuntu xenial-updates InRelease
Hit:4 http://us.archive.ubuntu.com/ubuntu xenial-backports InRelease
Reading package lists...
END (0)
BEGIN sudo apt-get update
Hit:1 http://us.archive.ubuntu.com/ubuntu xenial InRelease
Hit:2 http://security.ubuntu.com/ubuntu xenial-security InRelease
Hit:3 http://us.archive.ubuntu.com/ubuntu xenial-updates InRelease
Hit:4 http://us.archive.ubuntu.com/ubuntu xenial-backports InRelease
Reading package lists...
END (0)
###CLOUDERA_SCM### PACKAGE_INSTALL cloudera-manager-agent
BEGIN sudo dpkg -l cloudera-manager-agent | grep -E '^ii[[:space:]]*cloudera-manager-agent[[:space:]]*'
dpkg-query: no packages found matching cloudera-manager-agent
END (1)
BEGIN sudo apt-cache show cloudera-manager-agent
E: No packages found
END (100)
cloudera-manager-agent must have Version=6.2.0 and Build=968826, exiting
closing logging file descriptor

Note that:

both the master node and the new host node run ubuntu 16

Public Cloudera Repository

Body:
Can you try installing the Cloudera agent manually on each node(when the number of nodes are less):

$ sudo apt-get install cloudera-manager-agent cloudera-manager-daemons

On every cluster host, configure the Cloudera Manager Agent to point to the Cloudera Manager Server by setting the following properties in the /etc/cloudera-scm-agent/config.ini

$ sudo service cloudera-scm-agent start

Make sure JAVA is installed in all the nodes

For some reason the sources.list.d file becomes empty after running the manager on these nodes.


问:
Postgres: why do I need to quote column name in max()?
So I encountered the following behaviour which surprised me. I first thought DateTime might be a postgres data type but what about BidOpen? Then there is the funny thing with the case of the column name in the error message. I almost feel this has to do with unquoted names being case insensitive. Why do I need to surround the column name in quotes for the query to work?

```<code>mydatabase=# select max("DateTime") from fx.candle;
         max
---------------------
 2019-04-26 20:59:00
(1 row)

mydatabase=# select max(DateTime) from fx.candle;
ERROR:  column "datetime" does not exist
LINE 1: select max(DateTime) from fx.candle;
                   ^
HINT:  Perhaps you meant to reference the column "candle.DateTime".
mydatabase=# select max(BidOpen) from fx.candle;
ERROR:  column "bidopen" does not exist
LINE 1: select max(BidOpen) from fx.candle;
                   ^
HINT:  Perhaps you meant to reference the column "candle.BidOpen".
mydatabase=# select max("BidOpen") from fx.candle;
   max
---------
 125.816
(1 row)
</code>```

The schema looks like this:

```<code>mydatabase=# \d fx.candle;
                                        Table "fx.candle"
  Column   |            Type             |                            Modifiers
-----------+-----------------------------+-----------------------------------------------------------------
 id        | integer                     | not null default nextval('fx.candle_id_seq'::regclass)
 DateTime  | timestamp without time zone |
 BidOpen   | double precision            | not null
 BidHigh   | double precision            | not null
 BidLow    | double precision            | not null
 BidClose  | double precision            | not null
 AskOpen   | double precision            | not null
 AskHigh   | double precision            | not null
 AskLow    | double precision            | not null
 AskClose  | double precision            | not null
 symbol_id | integer                     |
Indexes:
    "candle_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
    "candle_symbol_id_fkey" FOREIGN KEY (symbol_id) REFERENCES fx.symbol(id)
</code>```

答:
My understanding is that Postgres is not case sensitive regarding column and table names unless you actually create them using double quotes in the beginning.  If that be the case, then you would need to forever refer to them using double quotes, to ensure that the proper case literal is being used.

So, to avoid your current situation, you should also avoid creating column/table names in a case sensitive manner.

Your create table should look something like this:

```<code>create table fx.candle (
    id integer not null default nextval('fx.candle_id_seq'::regclass),
    ...
    datetime timestamp without time zone   -- NO quotes here; important!
    ...
)
</code>```

Body:
So I encountered the following behaviour which surprised me. I first thought DateTime might be a postgres data type but what about BidOpen? Then there is the funny thing with the case of the column name in the error message. I almost feel this has to do with unquoted names being case insensitive. Why do I need to surround the column name in quotes for the query to work?

mydatabase=# select max("DateTime") from fx.candle;
         max
---------------------
 2019-04-26 20:59:00
(1 row)

mydatabase=# select max(DateTime) from fx.candle;
ERROR:  column "datetime" does not exist
LINE 1: select max(DateTime) from fx.candle;
                   ^
HINT:  Perhaps you meant to reference the column "candle.DateTime".
mydatabase=# select max(BidOpen) from fx.candle;
ERROR:  column "bidopen" does not exist
LINE 1: select max(BidOpen) from fx.candle;
                   ^
HINT:  Perhaps you meant to reference the column "candle.BidOpen".
mydatabase=# select max("BidOpen") from fx.candle;
   max
---------
 125.816
(1 row)

The schema looks like this:

mydatabase=# \d fx.candle;
                                        Table "fx.candle"
  Column   |            Type             |                            Modifiers
-----------+-----------------------------+-----------------------------------------------------------------
 id        | integer                     | not null default nextval('fx.candle_id_seq'::regclass)
 DateTime  | timestamp without time zone |
 BidOpen   | double precision            | not null
 BidHigh   | double precision            | not null
 BidLow    | double precision            | not null
 BidClose  | double precision            | not null
 AskOpen   | double precision            | not null
 AskHigh   | double precision            | not null
 AskLow    | double precision            | not null
 AskClose  | double precision            | not null
 symbol_id | integer                     |
Indexes:
    "candle_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
    "candle_symbol_id_fkey" FOREIGN KEY (symbol_id) REFERENCES fx.symbol(id)

Body:
My understanding is that Postgres is not case sensitive regarding column and table names unless you actually create them using double quotes in the beginning.  If that be the case, then you would need to forever refer to them using double quotes, to ensure that the proper case literal is being used.

So, to avoid your current situation, you should also avoid creating column/table names in a case sensitive manner.

Your create table should look something like this:

create table fx.candle (
    id integer not null default nextval('fx.candle_id_seq'::regclass),
    ...
    datetime timestamp without time zone   -- NO quotes here; important!
    ...
)


问:
How to handle two different times if they are not in the same day?
I'm handling restaurant opening and closing hours , i am using moment to parse time it and it works perfect but there is one case in which its not working,
If the restaurant open at 9:00 am and closes 1:00 am (next day), it gives restaurant is closed no matter the time .</p>

```<code>   if (current_time.isBetween(opening_hour, close_hour))  {
     console.log('its open');
   } else {
     console.log('its closed');
   }

</code>```

答:
Another approach is to save opening hour and duration of work:</p>

```<code>
const opening_hour = moment('9:00am', 'hh:mm');
const current_time = moment();

const duration = 16 * 60; //duration in minutes, 16 hours

if (current_time.isBetween(opening_hour, opening_hour.clone().add(duration, 'minutes'))) {
     console.log('its open');
} else {
     console.log('its closed');
}
</code>```

Body:
I'm handling restaurant opening and closing hours , i am using moment to parse time it and it works perfect but there is one case in which its not working,
If the restaurant open at 9:00 am and closes 1:00 am (next day), it gives restaurant is closed no matter the time .

   if (current_time.isBetween(opening_hour, close_hour))  {
     console.log('its open');
   } else {
     console.log('its closed');
   }

Body:
Another approach is to save opening hour and duration of work:

const opening_hour = moment('9:00am', 'hh:mm');
const current_time = moment();

const duration = 16 * 60; //duration in minutes, 16 hours

if (current_time.isBetween(opening_hour, opening_hour.clone().add(duration, 'minutes'))) {
     console.log('its open');
} else {
     console.log('its closed');
}


问:
Merge 64 Bit and 32 bit android APK as per new android requirement
We created 64-bit version of my app as per the android link.

Now we get two folders with 32-bit apk and 64-bit apk which is fine.

Now I want to know, how to merge both this 32/64 bit apk. Is it possible to merge them or we need to upload both 32 bit and 64-bit apk separately in google play store?

答:
You can upload two APKs in the same release as long as the APK targeting 64-bit has a higher version code than the APK targeting 32-bit (Google Play will complain if you don't do that). All the documentation on this topic can be found at: https://developer.android.com/google/play/publishing/multiple-apks

A simpler alternative is to upload a single Android App Bundle in place of an APK, and Google Play will take care of generating the APKs for each of the native architecture your app supports. The documentation can be found at: https://developer.android.com/platform/technology/app-bundle


问:
Importing JSON from a server within Angular
I am reading data from a JSON, which is one a server and it updates regularly and changes. I need to be able to read this JSON from the server so that I display the most up to date information on my web page.

Currently, the to be able to read the JSONs they are stored within the same project folder as my angular project. (This was because they were not set up on the server when I started).

This is how I currently import the JSON to be able to read it:

```<code>import jsonInfo from '../../../info.json'
</code>```

I thought I would be able to change the file link to the server address, like so:

```<code>import jsonInfo from 'http://servername/folder/info.json'
</code>```

But, VSCode gives me an error: Cannot find module 'http://servername/folder/info.json'

This is definitely the location of the JSON I am trying to load because when I click the link it takes me to the JSON and displays it.

My question is, how do I import the JSON into my .ts from a server so that I can keep getting the updated information from the JSON?

答:
JSON file on a server is just like any other web resource you would try to access (like an API endpoint, for example).

So you should use built in angular http client to access this JSON file.

For example:

```<code>import { HttpClient } from '@angular/common/http';

export class SomeService {
  constructor(private http: HttpClient) { }

  getInfo() {
    return this.http.get('http://servername/folder/info.json');
  }

}

//...

export class SomeComponent implements OnInit {

  info: any;

  constructor(private someService: SomeService) {}

  ngOnInit() {
    this.someService.getInfo().subscribe(info => this.info = info)
  }

}

</code>```

Body:
I am reading data from a JSON, which is one a server and it updates regularly and changes. I need to be able to read this JSON from the server so that I display the most up to date information on my web page.

Currently, the to be able to read the JSONs they are stored within the same project folder as my angular project. (This was because they were not set up on the server when I started).

This is how I currently import the JSON to be able to read it:

import jsonInfo from '../../../info.json'

I thought I would be able to change the file link to the server address, like so:

import jsonInfo from 'http://servername/folder/info.json'

But, VSCode gives me an error: Cannot find module 'http://servername/folder/info.json'

This is definitely the location of the JSON I am trying to load because when I click the link it takes me to the JSON and displays it.

My question is, how do I import the JSON into my .ts from a server so that I can keep getting the updated information from the JSON?

Body:
JSON file on a server is just like any other web resource you would try to access (like an API endpoint, for example).

So you should use built in angular http client to access this JSON file.

For example:

import { HttpClient } from '@angular/common/http';

export class SomeService {
  constructor(private http: HttpClient) { }

  getInfo() {
    return this.http.get('http://servername/folder/info.json');
  }

}

//...

export class SomeComponent implements OnInit {

  info: any;

  constructor(private someService: SomeService) {}

  ngOnInit() {
    this.someService.getInfo().subscribe(info => this.info = info)
  }

}


问:
Angular 8 using Ivy module.ngfactory cannot find
I have a snippet:

```<code>import { platformBrowser }    from '@angular/platform-browser';
import { enableProdMode } from '@angular/core';
enableProdMode();

import '../../../src/bundle';

import {ModuleNgFactory} from './module.ngfactory';

platformBrowser().bootstrapModuleFactory(ModuleNgFactory);
</code>```

As soon, I enable ivy, i face this error:

```<code>Running "cory-build-aot" task

Compiling @angular/core : module as esm5

Compiling @angular/common : module as esm5

Compiling @angular/platform-browser : module as esm5

Compiling @angular/common/http : module as esm5

Compiling @angular/router : module as esm5

Compiling @angular/forms : module as esm5
Hash: d7163c5eb0d56ede4ba6
Version: webpack 4.32.2
Time: 24870ms
Built at: 05/29/2019 2:43:19 PM
 4 assets
Entrypoint polyfills = polyfills.d7163c5eb0d56ede4ba6.js sourcemaps/polyfills.d7163c5eb0d56ede4ba6.js.map
Entrypoint bundle = bundle.d7163c5eb0d56ede4ba6.js sourcemaps/bundle.d7163c5eb0d56ede4ba6.js.map
[0] ./test/angular-webpack/angular/polyfills.ts 0 bytes {1} [built]
[1] ./test/angular-webpack/angular/bundle.aot.ts 0 bytes {0} [built]

ERROR in test/angular-webpack/angular/bundle.aot.ts(7,31): error TS2307: Cannot find module './module.ngfactory'.

Child html-webpack-plugin for "index.html":
     1 asset
    Entrypoint undefined = index.html
    [0] ./node_modules/html-webpack-plugin/lib/loader.js!./test/angular-webpack/index.html 261 bytes {0} [built]
Warning: Command failed: ./node_modules/.bin/webpack-cli --color --cache --production --config /home/patrikx3/Projects/patrikx3/corifeus/corifeus-web/node_modules/corifeus-builder-angular/src/webpack.test.config.js

Compiling @angular/core : module as esm5

Compiling @angular/common : module as esm5

Compiling @angular/platform-browser : module as esm5

Compiling @angular/common/http : module as esm5

Compiling @angular/router : module as esm5

Compiling @angular/forms : module as esm5
 Use --force to continue.

Aborted due to warnings.

Execution Time (2019-05-29 14:42:53 UTC+2)
cory-build-aot  25.8s  ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 100%
Total 25.9s

patrikx3@workstation:~/Projects/patrikx3/corifeus/corifeus-web$
</code>```

What the error is:
ERROR in test/angular-webpack/angular/bundle.aot.ts(7,31): error TS2307: Cannot find module './module.ngfactory'.

I try to enable ivy, by adding angularCompilerOptions section to enableIvy to be true, and that is when I get this error.

答: need to add allowEmptyCodegenFiles : true in angularCompilerOptions in tsconfig.app.json

Body:
I have a snippet:

import { platformBrowser }    from '@angular/platform-browser';
import { enableProdMode } from '@angular/core';
enableProdMode();

import '../../../src/bundle';

import {ModuleNgFactory} from './module.ngfactory';

platformBrowser().bootstrapModuleFactory(ModuleNgFactory);

As soon, I enable ivy, i face this error:

Running "cory-build-aot" task

Compiling @angular/core : module as esm5

Compiling @angular/common : module as esm5

Compiling @angular/platform-browser : module as esm5

Compiling @angular/common/http : module as esm5

Compiling @angular/router : module as esm5

Compiling @angular/forms : module as esm5
Hash: d7163c5eb0d56ede4ba6
Version: webpack 4.32.2
Time: 24870ms
Built at: 05/29/2019 2:43:19 PM
 4 assets
Entrypoint polyfills = polyfills.d7163c5eb0d56ede4ba6.js sourcemaps/polyfills.d7163c5eb0d56ede4ba6.js.map
Entrypoint bundle = bundle.d7163c5eb0d56ede4ba6.js sourcemaps/bundle.d7163c5eb0d56ede4ba6.js.map
[0] ./test/angular-webpack/angular/polyfills.ts 0 bytes {1} [built]
[1] ./test/angular-webpack/angular/bundle.aot.ts 0 bytes {0} [built]

ERROR in test/angular-webpack/angular/bundle.aot.ts(7,31): error TS2307: Cannot find module './module.ngfactory'.

Child html-webpack-plugin for "index.html":
     1 asset
    Entrypoint undefined = index.html
    [0] ./node_modules/html-webpack-plugin/lib/loader.js!./test/angular-webpack/index.html 261 bytes {0} [built]
Warning: Command failed: ./node_modules/.bin/webpack-cli --color --cache --production --config /home/patrikx3/Projects/patrikx3/corifeus/corifeus-web/node_modules/corifeus-builder-angular/src/webpack.test.config.js

Compiling @angular/core : module as esm5

Compiling @angular/common : module as esm5

Compiling @angular/platform-browser : module as esm5

Compiling @angular/common/http : module as esm5

Compiling @angular/router : module as esm5

Compiling @angular/forms : module as esm5
 Use --force to continue.

Aborted due to warnings.

Execution Time (2019-05-29 14:42:53 UTC+2)
cory-build-aot  25.8s  ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 100%
Total 25.9s

patrikx3@workstation:~/Projects/patrikx3/corifeus/corifeus-web$

What the error is:
ERROR in test/angular-webpack/angular/bundle.aot.ts(7,31): error TS2307: Cannot find module './module.ngfactory'.

I try to enable ivy, by adding angularCompilerOptions section to enableIvy to be true, and that is when I get this error.


答:
Use HttpClient get method.</p>

```<code>this.httpClient.get('http://servername/folder/info.json').subscribe(data => {
  // your logic
})
</code>```

Title: Importing JSON from a server within Angular

Body:
Use HttpClient get method.

this.httpClient.get('http://servername/folder/info.json').subscribe(data => {
  // your logic
})


问:
How to pass jenkins parameters as array to bash script?
I want to pass in jenkins parameters as array args to my bash script.

I have tried below but no luck.

```<code>   stage('Foo Step') {
        steps {
            script {
                sh "chmod 755 runFooBar.sh"
                sh """
                    ./runFooBar.sh --baz="${params.BAZ[@]}" --bar="${params.BAR}" --foo="${params.FOO[@]}"
                """
            }
        }
    }
</code>```

I am getting this error when I run above script.

```<code> WorkflowScript: 48: unexpected token: @ @ line 48, column 75.
 ./runFooBar.sh  --baz="${params.BAZ[@]}" --bar
                                     ^
</code>```

Thank you in advance.

Cheers!

答:
Had similar issue to resolve.
Try to remove the '[@]' as groovy seems not to appreciate this.

In my case it looks as follows and works thus far:

```<code>steps {
    script {
        RECIPIENTS = '"user1@domain" "user2@domain" "user3@domain"'
        sh "./send_email.sh ${RECIPIENTS}"
    }
}

</code>```

Body:
I want to pass in jenkins parameters as array args to my bash script.

I have tried below but no luck.

   stage('Foo Step') {
        steps {
            script {
                sh "chmod 755 runFooBar.sh"
                sh """
                    ./runFooBar.sh --baz="${params.BAZ[@]}" --bar="${params.BAR}" --foo="${params.FOO[@]}"
                """
            }
        }
    }

I am getting this error when I run above script.

 WorkflowScript: 48: unexpected token: @ @ line 48, column 75.
 ./runFooBar.sh  --baz="${params.BAZ[@]}" --bar
                                     ^

Thank you in advance.

Cheers!

Body:
Had similar issue to resolve.
Try to remove the '[@]' as groovy seems not to appreciate this.

In my case it looks as follows and works thus far:

steps {
    script {
        RECIPIENTS = '"user1@domain" "user2@domain" "user3@domain"'
        sh "./send_email.sh ${RECIPIENTS}"
    }
}


问:
Replace text with an image in javascript
I'm looking for a way to replace text with an image in javascript but I can not do it,

For example text:

```<code><div><p class="YellowTxt">MyYellowTxt</p></div>
<div><p class="BlueTxt">MyBlueTxt</p></div>
<div><p class="GreenTxt">MyGreenTxt</p></div>
</code>```

To have, a yellow, blue and green image.

答:
Use innerHTML:

function replace() {
  var el = document.getElementsByClassName('YellowTxt')[0]
  el.innerHTML = ''
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <p class="YellowTxt">MyYellowTxt</p>
</div>
<div>
  <p class="BlueTxt">MyBlueTxt</p>
</div>
<div>
  <p class="GreenTxt">MyGreenTxt</p>
</div>

<hr />

<button onclick="replace()">Replace</button></code>```

Body:
I'm looking for a way to replace text with an image in javascript but I can not do it,

For example text:

MyYellowTxt

MyBlueTxt

MyGreenTxt

To have, a yellow, blue and green image.

Body:
Use innerHTML:

function replace() {
  var el = document.getElementsByClassName('YellowTxt')[0]
  el.innerHTML = '<img src="" alt="image"/>'
}

<div>
  <p class="YellowTxt">MyYellowTxt</p>
</div>
<div>
  <p class="BlueTxt">MyBlueTxt</p>
</div>
<div>
  <p class="GreenTxt">MyGreenTxt</p>
</div>

<hr />

<button onclick="replace()">Replace</button>


问:
Getting data from server and the data is not updating from server, it stays old data
I am getting data from server using UnityWebRequest. At the first time it receives, when I update my data in server, the unity data is not updated and it shows me old data. I have to clear the cache and again get the data from server.

Here is the code.

```<code>public Text mytext;

void Start()
{
    StartCoroutine(GetText());
}

IEnumerator GetText()
{
    UnityWebRequest www = UnityWebRequest.Get("https://www.simplearcadegamers.com/wp-content/uploads/2019/GetData.php");
    yield return www.SendWebRequest();

    if(www.isNetworkError || www.isHttpError)
    {
        Debug.Log(www.error);
    }
    else
    {
        // Show results as text
        Debug.Log(www.downloadHandler.text);

        // Or retrieve results as binary data
        byte[] results = www.downloadHandler.data;
    }
}
</code>```

答:
Unity WWW caches results by default, as a quick workaround you can append a randomized query at the end of the URL to ensure it always returns new results, e.g. ?random=<generate random number here> - see: https://answers.unity.com/questions/209078/disable-cache-for-www.html

A proper way to do this would be to abandon using the now obsolete WWW classes, and do proper new requests via UnityWebRequest & disabling cache.

Body:
I am getting data from server using UnityWebRequest. At the first time it receives, when I update my data in server, the unity data is not updated and it shows me old data. I have to clear the cache and again get the data from server.

Here is the code.

public Text mytext;

void Start()
{
    StartCoroutine(GetText());
}

IEnumerator GetText()
{
    UnityWebRequest www = UnityWebRequest.Get("https://www.simplearcadegamers.com/wp-content/uploads/2019/GetData.php");
    yield return www.SendWebRequest();

    if(www.isNetworkError || www.isHttpError)
    {
        Debug.Log(www.error);
    }
    else
    {
        // Show results as text
        Debug.Log(www.downloadHandler.text);

        // Or retrieve results as binary data
        byte[] results = www.downloadHandler.data;
    }
}


问:
Angular 4 and ngx-datatable: 'ngx-datatable' is not a known element
I try to use ngx-datatable in my angular 4 project using system.js to load the module, but it throws errors like this:

Can't bind to 'rows' since it isn't a known property of ngx-datatable.

  Can't bind to 'columns' since it isn't a known property of ngx-datatable.

  ngx-datatable is not a known element:

I guess system.js does not load the module correctly but i can't find a working demo on how to do this. The documentation is not helpful either.

system.config.js:

```<code>map: {
     ...
     '@swimlane/ngx-datatable': 'npm:@swimlane/ngx-datatable/release/index.js',
     ...
}
</code>```

app.module.ts:

```<code>import { NgxDatatableModule } from '@swimlane/ngx-datatable';
...
imports: [
    ...
    NgxDatatableModule,
    ...
],
</code>```

component.html:

```<code><ngx-datatable
     [rows]="rows"
     [columns]="columns">
</ngx-datatable>
</code>```

component.ts:

```<code>rows = [
    { name: 'Austin', gender: 'Male', company: 'Swimlane' },
    { name: 'Dany', gender: 'Male', company: 'KFC' },
    { name: 'Molly', gender: 'Female', company: 'Burger King' },
];
columns = [
    { prop: 'name' },
    { name: 'Gender' },
    { name: 'Company' }
];
</code>```

package.json:

```<code>...
"@angular/animations": "^4.3.0",
"@angular/common": "^4.3.0",
"@angular/compiler": "^4.3.0",
"@angular/compiler-cli": "^4.3.0",
"@angular/core": "^4.3.0",
"@angular/forms": "^4.3.0",
"@angular/http": "^4.3.0",
"@angular/platform-browser": "^4.3.0",
"@angular/platform-browser-dynamic": "^4.3.0",
"@angular/platform-server": "^4.3.0",
"@angular/router": "^4.3.0",
"@angular/upgrade": "4.3.0",
"@swimlane/ngx-datatable": "^9.3.1",
...
</code>```

答:
I installed it running properly for  me.
Please refer this link

```<code>Please import in App.module.ts like below:

    import { NgxDatatableModule } from '@swimlane/ngx-datatable';
@NgModule({
  imports: [
    NgxDatatableModule]});
</code>```

Please see the App.component.html

```<code> <ngx-datatable class="material"
            [rows]="rows"
            [columns]="column">
          </ngx-datatable>
</code>```

Body:
I try to use ngx-datatable in my angular 4 project using system.js to load the module, but it throws errors like this:

Can't bind to 'rows' since it isn't a known property of ngx-datatable.

  Can't bind to 'columns' since it isn't a known property of ngx-datatable.

  ngx-datatable is not a known element:

I guess system.js does not load the module correctly but i can't find a working demo on how to do this. The documentation is not helpful either.

system.config.js:

map: {
     ...
     '@swimlane/ngx-datatable': 'npm:@swimlane/ngx-datatable/release/index.js',
     ...
}

app.module.ts:

import { NgxDatatableModule } from '@swimlane/ngx-datatable';
...
imports: [
    ...
    NgxDatatableModule,
    ...
],

component.html:

<ngx-datatable
     [rows]="rows"
     [columns]="columns">
</ngx-datatable>

component.ts:

rows = [
    { name: 'Austin', gender: 'Male', company: 'Swimlane' },
    { name: 'Dany', gender: 'Male', company: 'KFC' },
    { name: 'Molly', gender: 'Female', company: 'Burger King' },
];
columns = [
    { prop: 'name' },
    { name: 'Gender' },
    { name: 'Company' }
];

package.json:

...
"@angular/animations": "^4.3.0",
"@angular/common": "^4.3.0",
"@angular/compiler": "^4.3.0",
"@angular/compiler-cli": "^4.3.0",
"@angular/core": "^4.3.0",
"@angular/forms": "^4.3.0",
"@angular/http": "^4.3.0",
"@angular/platform-browser": "^4.3.0",
"@angular/platform-browser-dynamic": "^4.3.0",
"@angular/platform-server": "^4.3.0",
"@angular/router": "^4.3.0",
"@angular/upgrade": "4.3.0",
"@swimlane/ngx-datatable": "^9.3.1",
...

Body:
I installed it running properly for  me.
Please refer this link

Please import in App.module.ts like below:

    import { NgxDatatableModule } from '@swimlane/ngx-datatable';
@NgModule({
  imports: [
    NgxDatatableModule]});

Please see the App.component.html

 <ngx-datatable class="material"
            [rows]="rows"
            [columns]="column">
          </ngx-datatable>


问:
Angular 7: Await function in interceptor
I have built an error interceptor in my first Angular application which is all new for me. The interceptor tries to refresh a Firebase authorization token when a 401 response code occures. Therefore I have written the following code:

```<code>@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(private authService: AuthService, private alertService: AlertService) { }

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
        catchError(err => {
            if (err.status === 401) {
                let user = localStorage.getItem('currentUser');
                if (!user) {
                    this.logout(false);
                    return throwError(err.error);
                }
                let currentUser = JSON.parse(user);
                if (!currentUser || !currentUser.stsTokenManager || !currentUser.stsTokenManager.accessToken) {
                    this.logout(false);
                    return throwError(err.error);
                }
                const reference = this;
                this.authService.getToken(currentUser, true).then(t => {
                    // How do I await and return this properly?
                    return reference.updateTokenAndRetry(request, next, currentUser, t);
                }); // Get token and refresh
            }
            this.alertService.showAlert({
                text: 'Fout tijdens het verzenden van het verzoek',
            });
            return throwError(err.error);
        })
    );
}

updateTokenAndRetry(request: HttpRequest<any>, next: HttpHandler, currentUser: any, token: string): Observable<HttpEvent<any>> {
    // Update local stored user
    currentUser.stsTokenManager.accessToken = token;
    localStorage.setItem('currentUser', JSON.stringify(currentUser));

    // Add the new token to the request
    request = request.clone({
        setHeaders: {
            Authorization: token,
        },
    });

    return next.handle(request);
}
</code>```

The token gets refreshed fine. However the network call is not being executed after the refresh, which reference.updateTokenAndRetry(request, next, currentUser, t); should do.

I assume the reason for this, is that this.authService.getToken(currentUser, true) returns a Promise (this is the Firebase plugin and can't be changed). I want to return return reference.updateTokenAndRetry(request, next, currentUser, t); but this is not possible since it's in an async function block.

How can I await or return the next network call? I can't make the intercept function async. I am pretty stuck at this point.

答:
Arwin solution works well, but only in an environment where one request is send at the time.

In order to get this to work save the refreshToken method into an Observable with the pipe share. This will allow multiple subscribers but a single result.

Wrap the next.handle(request) method in another Subject<any> and return the subject.
If the request fires an error call that isn't a 401 error call subject.error.

After refreshing the token call this.updateTokenAndRetry(request, next, currentUser, token).subscribe(result => subject.next(result); to make sure that the request is returned to the initial subscriber.

Below code is pseudo code and should work in your case.

```<code>refreshTokenObservable: Observable<any>;

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    let subject = new Subject<any>();

    next.handle(request).pipe(
        catchError(err => {
            if (err.status === 401) {
                let user = localStorage.getItem('currentUser');
                if (!user) {
                    this.logout(false);
                    subject.error(err.error);
                    return;
                }
                let currentUser = JSON.parse(user);
                if (!currentUser || !currentUser.stsTokenManager || !currentUser.stsTokenManager.accessToken) {
                    this.logout(false);
                    subject.error(err.error);
                    return;
                }
                // Return a newly created function here
                this.refreshToken(currentUser).subscribe(token => {

                    this.updateTokenAndRetry(request, next, currentUser, token).subscribe(result => subject.next(result);
                    this.refreshTokenObservable = null; // clear observable for next failed login attempt
                });
            }
            this.alertService.showAlert({
                text: 'Fout tijdens het verzenden van het verzoek',
            });
            subject.error(err.error);
        })
    ).subscribe(result => subject.next(result));

    return subject.asObservable();
}

refreshToken(currentUser: any) {

    if(this.refreshTokenObservable == null)
    {
        // By making use of the from operator of RxJS convert the promise to an observable
        this.refreshTokenObservable = from(this.authService.getToken(currentUser, true)).pipe(share());
    }

    return this.refreshTokenObservable;
}

updateTokenAndRetry(request: HttpRequest<any>, next: HttpHandler, currentUser: any, token: string): Observable<HttpEvent<any>> {
    // Update local stored user
    currentUser.stsTokenManager.accessToken = token;
    localStorage.setItem('currentUser', JSON.stringify(currentUser));

    // Add the new token to the request
    request = request.clone({
        setHeaders: {
            Authorization: token,
        },
    });

    return next.handle(request);
}
</code>```

Body:
I have built an error interceptor in my first Angular application which is all new for me. The interceptor tries to refresh a Firebase authorization token when a 401 response code occures. Therefore I have written the following code:

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(private authService: AuthService, private alertService: AlertService) { }

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
        catchError(err => {
            if (err.status === 401) {
                let user = localStorage.getItem('currentUser');
                if (!user) {
                    this.logout(false);
                    return throwError(err.error);
                }
                let currentUser = JSON.parse(user);
                if (!currentUser || !currentUser.stsTokenManager || !currentUser.stsTokenManager.accessToken) {
                    this.logout(false);
                    return throwError(err.error);
                }
                const reference = this;
                this.authService.getToken(currentUser, true).then(t => {
                    // How do I await and return this properly?
                    return reference.updateTokenAndRetry(request, next, currentUser, t);
                }); // Get token and refresh
            }
            this.alertService.showAlert({
                text: 'Fout tijdens het verzenden van het verzoek',
            });
            return throwError(err.error);
        })
    );
}

updateTokenAndRetry(request: HttpRequest<any>, next: HttpHandler, currentUser: any, token: string): Observable<HttpEvent<any>> {
    // Update local stored user
    currentUser.stsTokenManager.accessToken = token;
    localStorage.setItem('currentUser', JSON.stringify(currentUser));

    // Add the new token to the request
    request = request.clone({
        setHeaders: {
            Authorization: token,
        },
    });

    return next.handle(request);
}

The token gets refreshed fine. However the network call is not being executed after the refresh, which reference.updateTokenAndRetry(request, next, currentUser, t); should do.

I assume the reason for this, is that this.authService.getToken(currentUser, true) returns a Promise (this is the Firebase plugin and can't be changed). I want to return return reference.updateTokenAndRetry(request, next, currentUser, t); but this is not possible since it's in an async function block.

How can I await or return the next network call? I can't make the intercept function async. I am pretty stuck at this point.

Body:
Arwin solution works well, but only in an environment where one request is send at the time.

In order to get this to work save the refreshToken method into an Observable with the pipe share. This will allow multiple subscribers but a single result.

Wrap the next.handle(request) method in another Subject<any> and return the subject.
If the request fires an error call that isn't a 401 error call subject.error.

After refreshing the token call this.updateTokenAndRetry(request, next, currentUser, token).subscribe(result => subject.next(result); to make sure that the request is returned to the initial subscriber.

Below code is pseudo code and should work in your case.

refreshTokenObservable: Observable<any>;

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    let subject = new Subject<any>();

    next.handle(request).pipe(
        catchError(err => {
            if (err.status === 401) {
                let user = localStorage.getItem('currentUser');
                if (!user) {
                    this.logout(false);
                    subject.error(err.error);
                    return;
                }
                let currentUser = JSON.parse(user);
                if (!currentUser || !currentUser.stsTokenManager || !currentUser.stsTokenManager.accessToken) {
                    this.logout(false);
                    subject.error(err.error);
                    return;
                }
                // Return a newly created function here
                this.refreshToken(currentUser).subscribe(token => {

                    this.updateTokenAndRetry(request, next, currentUser, token).subscribe(result => subject.next(result);
                    this.refreshTokenObservable = null; // clear observable for next failed login attempt
                });
            }
            this.alertService.showAlert({
                text: 'Fout tijdens het verzenden van het verzoek',
            });
            subject.error(err.error);
        })
    ).subscribe(result => subject.next(result));

    return subject.asObservable();
}

refreshToken(currentUser: any) {

    if(this.refreshTokenObservable == null)
    {
        // By making use of the from operator of RxJS convert the promise to an observable
        this.refreshTokenObservable = from(this.authService.getToken(currentUser, true)).pipe(share());
    }

    return this.refreshTokenObservable;
}

updateTokenAndRetry(request: HttpRequest<any>, next: HttpHandler, currentUser: any, token: string): Observable<HttpEvent<any>> {
    // Update local stored user
    currentUser.stsTokenManager.accessToken = token;
    localStorage.setItem('currentUser', JSON.stringify(currentUser));

    // Add the new token to the request
    request = request.clone({
        setHeaders: {
            Authorization: token,
        },
    });

    return next.handle(request);
}


问:
Android Studio Image Asset Launcher Icon Background Color
I have a .png logo for my app which doesn't have a background, when I add it to android studio as an Image Asset I am forced to have a background. The hex field doesn't accept 8 digit color codes, 6 digits only. Is there anyway to keep the background invisible?</p>

答:
This is just another workaround.

For the 'Foreground Layer', select 'Asset type' as text and delete the default text in the text field.

For the 'Background Layer', select 'Asset type' as image and now choose the path of the image you want as an icon.

And you are good to go.


问:
Design considerations for realtime OPC system
We are in the process of redesigning a disjointed realtime OPC system which has proven to be cumbersome. Our technology stack is C#, .NET 4 and SQL Server 2008 R2, hosted on 32 bit Windows Server 2003. Physical archtecture currently dictates that all tiers are to be hosted on a single server, although with sufficient motivation (read: ROI) this could be increased to 2.

The basic existing architecture is:

External OPC devices call our webservice to populate SQL with realtime data, approxomately 300 events per second. We have no control over volume or batch processing here, although in the rewrite I would like to implement batching in the web service to spare SQL from 300 insert statements per second.

SQL is used as a central resource for various components (about 9 in total, all to be redesigned) that perform tasks ranging from alarms to reporting. This is currently the biggest problem with the existing design, in that there is no single BLL or even DAL through which all these components consume/manipulate data or govern behavior.

Components range from Windows Services to Web Services to Windows Applications. The biggest consumer of CPU time and SQL connections is a Windows Forms application that monitors all realtime data and raises alarms as required. It also does realtime trend graphs, which is quite expensive to run.

For the rewrite there is a strong push towards WPF with which, apart from the learning curve, I have no problem. My question is more concerned with the underlying architecture:

I am currently doing some research on how to implement a single DAL and BLL. For the DAL I am leaning towards EF or nHibernate, with Linq-to-SQL also a possibility.

For the BLL I only have experience in CSLA.NET, and I fear this may be a bit over the top for a system in which speed and resource consumption is crucial.

Does anybody have any experience with a similiar system, and are willing to share a few lessons or design guidelines?

答:
Im not sure I like the idea of having an SQL server as a central point in the system. this server is going to get hammered - every time data changes on a device, it will write to the database. Every client will then continually refresh at a constant rate to detect if there are any changes. this is going to be a lot of work for the SQL server.

The OPC protocol involves clients subscribing to a server, so they can then be notified on change of any data. Using SQL in the middle prevents this.

Would you not be far better off using/creating an OPC server to retrieve all data from the device, then allowing each client to connect to this? That way they are only recieving data when it changes, rather than having to constantly check for updates?

If you need to log for historical reasons, you can always make an extra client which then logs the data to an SQL database.


问:
Unity 3D: what is the correct way to detect that the collision has already been processed for another collision participant?
I have a class CollisionHandler which has the OnCollisionEnter method. Each collideable entity in the game has CollisionHandler as a component. So, when 2 objects collide the OnCollisionEnter method is called twice and it's ok because the damage and other things are processed as a result of touching object "B" by object "A" and vice versa.

In addition, each collision creates a flash effect and plays a sound of impact and of course, these effects are also played twice for each collision. Although it wouldn't be imperceptible to the player it doesn't seem to be correct anyway. In order to prevent it, I came up with the following solution: I save the current frame number in another collision participant so it will know that these effects have been played already by the first one.

```<code>private void OnCollisionEnter(Collision collision)
{
    // Calculate the damage caused by `this.gameObject` to `collision.gameObject`.
    // ...

    // Play an impact sound and show a visual effect.
    if (thisObject.CollisionFrameId != Time.frameCount)
    {
        otherObject.CollisionFrameId = Time.frameCount;
        // play sound
        // show hit effect
    }
}
</code>```

Although it works I'm not sure (I'm a novice in Unity) that it's the best practice and if so please suggest other possible solutions.

Note that I didn't ask "Why is OnCollisionEnter getting called twice?". I know why it happens. My question is about the other, though it does mention the name of the same function it still doesn't asks the same.

答:
You could do a GetComponent on the other object with one of your scripts (or the same script) and set the RecentCollisionObject to the current script or gameObject (and maybe a given time frame just for additional safety (if only one triggers it, but not the other for some reason)).

On each collision you check if RecentCollisionObject is the other object (and if no more than ~0.01 seconds has passed). If true, you know that particular collision must already have been processed by the other object just now, so reset all values from that other object and do nothing else. So the next collision which occurs, no matter how soon, will do this cycle anew and work as expected.

This way you let only the first to trigger the collide code execute your code (like a sound). The point is that both collision events are ran in the same frame, so no matter which triggers first, you can prevent the second from running.

Body:
I have a class CollisionHandler which has the OnCollisionEnter method. Each collideable entity in the game has CollisionHandler as a component. So, when 2 objects collide the OnCollisionEnter method is called twice and it's ok because the damage and other things are processed as a result of touching object "B" by object "A" and vice versa.

In addition, each collision creates a flash effect and plays a sound of impact and of course, these effects are also played twice for each collision. Although it wouldn't be imperceptible to the player it doesn't seem to be correct anyway. In order to prevent it, I came up with the following solution: I save the current frame number in another collision participant so it will know that these effects have been played already by the first one.

private void OnCollisionEnter(Collision collision)
{
    // Calculate the damage caused by `this.gameObject` to `collision.gameObject`.
    // ...

    // Play an impact sound and show a visual effect.
    if (thisObject.CollisionFrameId != Time.frameCount)
    {
        otherObject.CollisionFrameId = Time.frameCount;
        // play sound
        // show hit effect
    }
}

Although it works I'm not sure (I'm a novice in Unity) that it's the best practice and if so please suggest other possible solutions.

Note that I didn't ask "Why is OnCollisionEnter getting called twice?". I know why it happens. My question is about the other, though it does mention the name of the same function it still doesn't asks the same.


问:
Remove HTML paragraph using removeChild
I wrote a code like below:

```<code>     <input type="button" value="remove" onclick="remove()"/>

     <p id="p2">
        before hr
        <hr/>
        after hr
     </p>

  <script>
     function remove() {
        var p = document.getElementById('p2');
        p.parentNode.removeChild(p);
     }
  </script>
</code>```

When I hit the button, only "before hr" disappear - hr and "after hr" text don't.

If I change
 to
 :

```<code><div id="p2">
    before hr
    <hr/>
    after hr
 </div>
</code>```

everything works properly (i.e. like I supposed it should works ;) )

Could somebody explain me the reasons, please?

答:
Your HTML is invalid. Use a validator.

A
 element may not contain an
 element, but the end tag for the
 element is optional.

This means that the
 element is implicitly ended by the
 and the
 tag is discarded because it doesn't match an open
.

The resulting DOM looks like this:

```<code> <p id="p2">before hr</p>
 <hr/>
 after hr
</code>```

Since the
 element and the text node following it are not inside the paragraph, they are not removed when the paragraph is removed.

Your reduced test case has been reduced so much that inferring the correct semantics for your content is impossible, but perhaps you need something like:

```<code><div id="p2">
    <p>before hr</p>
    <hr>
    <p>after hr</p>
</div>
</code>```

Title: Remove HTML paragraph using removeChild

Body:
I wrote a code like below:

     <input type="button" value="remove" onclick="remove()"/>

        before hr

        after hr

When I hit the button, only "before hr" disappear - hr and "after hr" text don't.

If I change
 to
 :

    before hr

    after hr

everything works properly (i.e. like I supposed it should works ;) )

Could somebody explain me the reasons, please?

Body:
Your HTML is invalid. Use a validator.

A <p> element may not contain an <hr> element, but the end tag for the <p> element is optional.

This means that the <p> element is implicitly ended by the <hr> and the </p> tag is discarded because it doesn't match an open <p>.

The resulting DOM looks like this:

 <p id="p2">before hr</p>
 <hr/>
 after hr

Since the <hr> element and the text node following it are not inside the paragraph, they are not removed when the paragraph is removed.

Your reduced test case has been reduced so much that inferring the correct semantics for your content is impossible, but perhaps you need something like:

<div id="p2">
    <p>before hr</p>
    <hr>
    <p>after hr</p>
</div>


问:
react native vector icons showing X instead of icon
I cant seem to figure this out. I can get something to show, but its a box with an X in it, so im assuming its not picking up the vector icons. Any advice?

I have the show icon true, I have the tint color, I have the vector icons (i have tried both ionicons and font awesome, to no avail.

Code:

```<code>import React, { Component} from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { createBottomTabNavigator, createAppContainer } from 'react-
navigation';
import Icon from 'react-native-vector-icons/FontAwesome';

class HomeScreen extends Component {

    static navigationOptions = {
        title: 'Home'
    };

 render(){
     return (
         <View style={{ flex:1, alignItems:'center', justifyContent:'center'
         }}>
             <Text>Home Screen</Text>
         </View>
     );
  }
  }

  const RootStack = createBottomTabNavigator(
      {
          Home: {
              screen: HomeScreen,
              navigationOptions: {
              tabBarLabel: 'Home',
              tabBarIcon: ({ tintColor }) => (
                  <Icon name = 'home' size={25} color={tintColor} />
              )
          }
      },
   },

   {
        tabBarOptions: {
        showIcon:true,
        tintColor:'red'
   }
  }
  );

  const AppContainer = createAppContainer(RootStack);

  const styles = StyleSheet.create({

 })

export default class App extends Component{
   render(){
   return <AppContainer />;
   }
}
</code>```

答: Fixed this. Once i realized it was the vectors, i just linked react-native with react-native-vectors.</p>

Body:
I cant seem to figure this out. I can get something to show, but its a box with an X in it, so im assuming its not picking up the vector icons. Any advice?

I have the show icon true, I have the tint color, I have the vector icons (i have tried both ionicons and font awesome, to no avail.

Code:

import React, { Component} from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { createBottomTabNavigator, createAppContainer } from 'react-
navigation';
import Icon from 'react-native-vector-icons/FontAwesome';

class HomeScreen extends Component {

    static navigationOptions = {
        title: 'Home'
    };

 render(){
     return (
         <View style={{ flex:1, alignItems:'center', justifyContent:'center'
         }}>
             <Text>Home Screen</Text>
         </View>
     );
  }
  }

  const RootStack = createBottomTabNavigator(
      {
          Home: {
              screen: HomeScreen,
              navigationOptions: {
              tabBarLabel: 'Home',
              tabBarIcon: ({ tintColor }) => (
                  <Icon name = 'home' size={25} color={tintColor} />
              )
          }
      },
   },

   {
        tabBarOptions: {
        showIcon:true,
        tintColor:'red'
   }
  }
  );

  const AppContainer = createAppContainer(RootStack);

  const styles = StyleSheet.create({

 })

export default class App extends Component{
   render(){
   return <AppContainer />;
   }
}


问:
Passing client-side JSON to back-end using ajax
I'm trying to connect the behavior of 2-3 APIs based on JSON responses from one or another API. I'm using ASP.NET MVC and vanilla JS.

The goal is to use a places API (Algolia) so a user can choose a place from an autocomplete input box and after choosing pass the name variable from the JSON to the next API which is a weather API (DarkSky).

The Algolia API is completely JS based and running on the client-side using the following html elements and scripts provided by Algolia:

<input type="search" id="address-input" placeholder="Search for a place.." />
```

<pre class="lang-html prettyprint-override"><code><script>
    var placesAutocomplete = places({
        appId: "my-app-id",
        apiKey: "my-api-key",
        container: document.querySelector('#address-input')
    });
</script>
</code>```

```

<p>After selecting a place the API returns the following JSON structure:</p>

```{
"query": "new york",
"suggestion": {
"name": "New York",
"country": "United States of America",
...},
...
}
```

<p>I want to use the name attribute i.e. "New York" and pass it to my back-end API client so I can use it for the GET request towards the DarkSky API.</p>

<p>I made a AJAX script for posting that value back to my MVC Controller but after a lot of trial and error I still don't know how to setup the Controller action to receive the data and and make it available to the rest of the back-end.</p>

<p>Here is the ajax script:</p>

<pre class="lang-html prettyprint-override"><code><script>
placesAutocomplete.on('change', function resultSelected(e) {
        var place = e.suggestion.name || '';
        $.ajax({
            type: 'POST',
            url: 'Ajax', //name of the action in the Home controller
            data: { place }
        })
    });
</script>
</code>```

Could you please guide me how my action should look like and is my ajax script ok.

Thank you!

答:
Your Controller Action should look something like below:

```<code>public class PlaceController : Controller
{
    [HttpPost]
    public JsonResult Search(string place)
    {
       // process
       return Json(place, JsonRequestBehavior.AllowGet);
    }
}
</code>```

Your AJAX request

```<code>    var place = "New York";
    $.ajax({
        type: 'POST',
        url: "/Place/Search", or // @Url.Action("Search", "Place")
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: { place : place },
        success: function(data){

        }
    });
</code>```

Body:
I'm trying to connect the behavior of 2-3 APIs based on JSON responses from one or another API. I'm using ASP.NET MVC and vanilla JS.

The goal is to use a places API (Algolia) so a user can choose a place from an autocomplete input box and after choosing pass the name variable from the JSON to the next API which is a weather API (DarkSky).

The Algolia API is completely JS based and running on the client-side using the following html elements and scripts provided by Algolia:

<input type="search" id="address-input" placeholder="Search for a place.." />

After selecting a place the API returns the following JSON structure:

{
"query": "new york",
"suggestion": {
"name": "New York",
"country": "United States of America",
...},
...
}

I want to use the name attribute i.e. "New York" and pass it to my back-end API client so I can use it for the GET request towards the DarkSky API.

I made a AJAX script for posting that value back to my MVC Controller but after a lot of trial and error I still don't know how to setup the Controller action to receive the data and and make it available to the rest of the back-end.

Here is the ajax script:

Could you please guide me how my action should look like and is my ajax script ok.

Thank you!

Body:
Your Controller Action should look something like below:

public class PlaceController : Controller
{
    [HttpPost]
    public JsonResult Search(string place)
    {
       // process
       return Json(place, JsonRequestBehavior.AllowGet);
    }
}

Your AJAX request

    var place = "New York";
    $.ajax({
        type: 'POST',
        url: "/Place/Search", or // @Url.Action("Search", "Place")
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: { place : place },
        success: function(data){

        }
    });


问:
GTM preview not starting
I have a GTM installed on the site. GTM tracking code is present on the site, and Google Tag Assistant (Chrome extension) shows that it fires.
But when I press Preview and open the site, I don't see the usual GTM panel on the bottom with information which tag fired and which didn't.

Can it be because of a Javascript error on the site?

custom.js?5b6084:316 Uncaught TypeError: Cannot read property
  'totalPanels' of undefined

If not, what can it be?

答: I faced the same problem. Later noticed that GTM Debugger wont preview if you are logged in as admin in the CMS.</p>

Title: GTM preview not starting


问:
WPF ListView control is populated but invisible
I have a ListView, populated with ItemsSource pointing to a list of login histories, so that I can choose from previous successful logins instead of having to type user, host, etc. over. This seemed to be working fine, but for some reason now the databinding is working fine but the items in the control are invisible. I can tell the control is being populated correctly because "ghosts" of the items are available and highlight when I mouseover them, in the correct number as in my ItemsSource,  and they are bound correctly - for instance if my ItemsSource has LoginA, LoginQ, and LoginZ and click on the second 'invisible' item, LoginQ happens. I've tried messing with opacity, changing where ItemsSource is bound (after/before login dialog appears, etc). with no joy. Compared to an older working version I can't see anything that appears to be relevant. Hints, suggestions, and catcalls welcome.....</p>

答:
devdigital's answer helped me find the problem; I was attempting to bind to the fields in my LoginHistory class which were defined as:

public string foo;

I had been previously defining the fields as:

public string foo {get; set; }

but changed them when I was having some issues with accessibility, and never changed them back. Having the { get; set; } defined allows them to be visible to the databinding again.
Ken (I'm the OP, but somehow the question originally got posted as a 'new user', so I don't think I can marked these as answered).