问:
how to close sweet alert on ajax request completion
I am using Sweet-alert in my angular app.

```<code>function GetDataFromServer(url) {
        SweetAlert.swal(
    {
        title: "",
        text: "Please wait.",
        imageUrl: "../../app/app-img/loading_spinner.gif",
        showConfirmButton: false
    });
        return $http.get(url)
        .then(success)
        .catch(exception);
        function success(response) {
            //SweetAlert.swal(
            //  {
            //      title: "",
            //      text: "data loaded",
            //  });
            return response.data;
        }
        function exception(ex) {
            return (ex);
        }

    }
</code>```

Req #1 (Main Objective of my this post)

What I am looking for is when the ajax request completes i.e.,
  controls enters in the then(), Sweet alert should automatically hide.

Req #2
Also while request processing, I don't want to have the Close pop-up button (Ok button) in the sweet alert.

As per the documentation,showConfirmButton: false should hide it but it's not.

Any help/suggestion highly appreciated.

Thanks.

答:
For automatically hiding the pop-over when it's done, you should set your initial pop-over to a variable so you can access it later. Maybe:

```<code>function GetDataFromServer(url) {
    SweetAlert.swal({
        title: "",
        text: "Please wait.",
        imageUrl: "../../app/app-img/loading_spinner.gif",
        showConfirmButton: false
    });
    return $http.get(url)
    .then(success)
    .catch(exception);
    function success(response) {
        swal.close()
        return response.data;
    }
    function exception(ex) {
        return (ex);
    }

}
</code>```

It's right on: https://t4t5.github.io/sweetalert/ in the methods section near the bottom.

Since you don't have a specific 'way' you want to do hide the ok button and you're just looking for suggestions, you could always just use a little CSS to target it and give it the ol display: none; setup.

Body:
I am using Sweet-alert in my angular app.

function GetDataFromServer(url) {
        SweetAlert.swal(
    {
        title: "",
        text: "Please wait.",
        imageUrl: "../../app/app-img/loading_spinner.gif",
        showConfirmButton: false
    });
        return $http.get(url)
        .then(success)
        .catch(exception);
        function success(response) {
            //SweetAlert.swal(
            //  {
            //      title: "",
            //      text: "data loaded",
            //  });
            return response.data;
        }
        function exception(ex) {
            return (ex);
        }

    }

Req #1 (Main Objective of my this post)

What I am looking for is when the ajax request completes i.e.,
  controls enters in the then(), Sweet alert should automatically hide.

Req #2
Also while request processing, I don't want to have the Close pop-up button (Ok button) in the sweet alert.

As per the documentation,showConfirmButton: false should hide it but it's not.

Any help/suggestion highly appreciated.

Thanks.

Body:
For automatically hiding the pop-over when it's done, you should set your initial pop-over to a variable so you can access it later. Maybe:

function GetDataFromServer(url) {
    SweetAlert.swal({
        title: "",
        text: "Please wait.",
        imageUrl: "../../app/app-img/loading_spinner.gif",
        showConfirmButton: false
    });
    return $http.get(url)
    .then(success)
    .catch(exception);
    function success(response) {
        swal.close()
        return response.data;
    }
    function exception(ex) {
        return (ex);
    }

}

It's right on: https://t4t5.github.io/sweetalert/ in the methods section near the bottom.

Since you don't have a specific 'way' you want to do hide the ok button and you're just looking for suggestions, you could always just use a little CSS to target it and give it the ol display: none; setup.


来源: stackexchange

问:
how can I use FirstOrDefault()?
I have this code and I want to set a value to Viewdate when the expression returns no data:

```<code>ViewData["Fix"] = db.PreStatusViws.Where(c => c.LkpNameFix == "1").FirstOrDefault().NumCoefficientFix;
</code>```

can I set zero or a "Text" for that? I no, what can I do?!
note: FirstOrDefault(null) cause an error.

答:
You just have to select your NumCoefficientFix property before calling FirstOrDefault:

```<code>ViewData["Fix"] = db.PreStatusViws
                    .Where(c => c.LkpNameFix == "1")
                    .Select(c => c.NumCoefficientFix)
                    .FirstOrDefault();`
</code>```

Or in LINQ notation:

```<code>ViewData["Fix"] = (from c in db.PreStatusViws
                   where c.LkpNameFix == "1"
                   select c.NumCoefficientFix
                  ).FirstOrDefault();
</code>```

ContentLicense: CC BY-SA 2.5

Title: how can I use FirstOrDefault()?

Body:
I have this code and I want to set a value to Viewdate when the expression returns no data:

ViewData["Fix"] = db.PreStatusViws.Where(c => c.LkpNameFix == "1").FirstOrDefault().NumCoefficientFix;

can I set zero or a "Text" for that? I no, what can I do?!
note: FirstOrDefault(null) cause an error.

Body:
You just have to select your NumCoefficientFix property before calling FirstOrDefault:

ViewData["Fix"] = db.PreStatusViws
                    .Where(c => c.LkpNameFix == "1")
                    .Select(c => c.NumCoefficientFix)
                    .FirstOrDefault();`

Or in LINQ notation:

ViewData["Fix"] = (from c in db.PreStatusViws
                   where c.LkpNameFix == "1"
                   select c.NumCoefficientFix
                  ).FirstOrDefault();


问:
IBDesignable view causes endless rebuilding
I'm writing a UIView subclass that uses both IBInspectable and IBDesignable. I'm not doing anything unusual, but my subclass causes Xcode 6.2 to endlessly rebuild the project. My Identity Inspector shows this state oscillation under the heading 'Designables':

Every time the build restarts, the inspector loses focus. This makes it hard to edit anything from IB, which defeats the purpose of writing this class in the first place.

Here is the implementation of my DesignableTestView:

```<code>import UIKit
@IBDesignable class DesignableTestView: UIView {

    @IBInspectable var testBackground:UIColor? {
        didSet {
            if testBackground != nil {
                self.backgroundColor = testBackground
            }
        }
    }
}
</code>```

Is there any way to change my code or settings of Xcode to prevent the constant rebuilding?

答: I was still having this issue (in Xcode 8.3.3) even after moving my IBDesignable classes into a separate framework. What worked for me was to open the offending Xib file, uncheck Editor > Automatically Refresh Views, and then restart Xcode.

ContentLicense: CC BY-SA 3.0

Body:
I'm writing a UIView subclass that uses both IBInspectable and IBDesignable. I'm not doing anything unusual, but my subclass causes Xcode 6.2 to endlessly rebuild the project. My Identity Inspector shows this state oscillation under the heading 'Designables':

Every time the build restarts, the inspector loses focus. This makes it hard to edit anything from IB, which defeats the purpose of writing this class in the first place.

Here is the implementation of my DesignableTestView:

import UIKit
@IBDesignable class DesignableTestView: UIView {

    @IBInspectable var testBackground:UIColor? {
        didSet {
            if testBackground != nil {
                self.backgroundColor = testBackground
            }
        }
    }
}

Is there any way to change my code or settings of Xcode to prevent the constant rebuilding?


问:
react with Rails 5, getting CSRF error for post with axios
I'm trying to use react_on_rails to build my first example with react and rails. I'm trying to save some data to the rails backend, using axios for the ajax.

here's my code:

```<code>import store from "../store/helloWorld";
import axios from "axios";

export const SAVE_NAME = "SAVE_NAME";

export function saveNameAction(name) {
  return {
    type: SAVE_NAME,
    name
  };
}

export function saveName(name) {
  axios
    .post("/hello_world", saveNameAction(name))
    .then(function(response) {
      console.log(response);
    })
    .catch(function(error) {
      console.log(error);
    });
}
</code>```

and the component:

```<code>import PropTypes from "prop-types";
import React from "react";
import * as actions from "../actions/helloWorld";

export default class HelloWorld extends React.Component {
  static propTypes = {
    name: PropTypes.string.isRequired // this is passed from the Rails view
  };

  /**
   * @param props - Comes from your rails view.
   */
  constructor(props) {
    super(props);
    this.state = { name: this.props.name };
  }

  updateName(name) {
    this.setState({ name: name });
  }

  handleSubmit(event) {
    event.preventDefault();
    actions.saveName(this.state.name);
  }

  render() {
    return (
      <div>
        <h3>
          Hellopp, {this.state.name}!
        </h3>
        <hr />
        <form>
          <label htmlFor="name">Say hello to:</label>
          <input
            id="name"
            type="text"
            value={this.state.name}
            onChange={e => this.updateName(e.target.value)}
          />

          <input
            type="submit"
            value="Submit"
            onClick={event => this.handleSubmit(event)}
          />
        </form>
      </div>
    );
  }
}
</code>```

The problem is that when I click the submit, my backend reports

```<code>Started POST "/hello_world" for ::1 at 2017-07-07 15:30:44 +0200
Processing by HelloWorldController#create as HTML
  Parameters: {"type"=>"SAVE_NAME", "name"=>"Stranger", "hello_world"=>{"type"=>"SAVE_NAME", "name"=>"Stranger"}}
Can't verify CSRF token authenticity.
Completed 422 Unprocessable Entity in 1ms (ActiveRecord: 0.0ms)

ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):
</code>```

For one, I don't understand why the parameters seem to be passed twice, but that's not even generating a warning, so don't care for now.

The problem is that I don't see a way to obtain the CSRF tokens in my react code to use in the post requests

should I just disable CSRF? or is there a better way?

答:
ActionController::InvalidAuthenticityToken
  (ActionController::InvalidAuthenticityToken):

Rails handles CSRF attacks by appending authenticity_token to every Non-GET requests(POST,PUT/PATCH and DELETE). The error means you are not sending authencity_token in the request params, You should append an unique authenticity_token to the params, something like "authuenticity_token" => "BsfdgtZ1hshxgthjj" which should resolve the issue.

Body:
I'm trying to use react_on_rails to build my first example with react and rails. I'm trying to save some data to the rails backend, using axios for the ajax.

here's my code:

import store from "../store/helloWorld";
import axios from "axios";

export const SAVE_NAME = "SAVE_NAME";

export function saveNameAction(name) {
  return {
    type: SAVE_NAME,
    name
  };
}

export function saveName(name) {
  axios
    .post("/hello_world", saveNameAction(name))
    .then(function(response) {
      console.log(response);
    })
    .catch(function(error) {
      console.log(error);
    });
}

and the component:

import PropTypes from "prop-types";
import React from "react";
import * as actions from "../actions/helloWorld";

export default class HelloWorld extends React.Component {
  static propTypes = {
    name: PropTypes.string.isRequired // this is passed from the Rails view
  };

  /**
   * @param props - Comes from your rails view.
   */
  constructor(props) {
    super(props);
    this.state = { name: this.props.name };
  }

  updateName(name) {
    this.setState({ name: name });
  }

  handleSubmit(event) {
    event.preventDefault();
    actions.saveName(this.state.name);
  }

  render() {
    return (

          Hellopp, {this.state.name}!

        <form>
          Say hello to:
          <input
            id="name"
            type="text"
            value={this.state.name}
            onChange={e => this.updateName(e.target.value)}
          />

          <input
            type="submit"
            value="Submit"
            onClick={event => this.handleSubmit(event)}
          />
        </form>

    );
  }
}

The problem is that when I click the submit, my backend reports

Started POST "/hello_world" for ::1 at 2017-07-07 15:30:44 +0200
Processing by HelloWorldController#create as HTML
  Parameters: {"type"=>"SAVE_NAME", "name"=>"Stranger", "hello_world"=>{"type"=>"SAVE_NAME", "name"=>"Stranger"}}
Can't verify CSRF token authenticity.
Completed 422 Unprocessable Entity in 1ms (ActiveRecord: 0.0ms)

ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):

For one, I don't understand why the parameters seem to be passed twice, but that's not even generating a warning, so don't care for now.

The problem is that I don't see a way to obtain the CSRF tokens in my react code to use in the post requests

should I just disable CSRF? or is there a better way?


问:
How could I create a "Authorize {App} to use your account" interface
I'm currently working during my internship on a Twitter bot project, I can manage to schedule and post tweets but asking users for their secret Keys and tokens is a bit intimidating.
How could I create an interface like this one :

答: You need to implement 3-legged OAuth and sign-in with Twitter in your application. Depending on the language you are using, you'll probably find a third-party Twitter client library that can help you.</p>


问:
JSON Deserializing string value to List<T> using Newtonsoft - constructor arg is null in C#
I am using Newtonsoft libraries for serialization and deserialization json object.
The reference code is below:

```<code> public abstract class BaseNode
{
    [JsonConstructor]
    protected BaseNode(string [] specifications)
    {
        if (specifications == null)
        {
            throw new ArgumentNullException();
        }
        if (specifications.Length == 0)
        {
            throw new ArgumentException();
        }

        Name = specifications[0];
        Identifier = specifications[1];
        //Owner = specifications[2];
    }

    public string Name{ get; protected set; }
    public string Identifier { get; protected set; }
    public string Owner { get; protected set; }
}

public class ComputerNode: BaseNode
{
    [JsonConstructor]
    public ComputerNode(string[] specifications):base(specifications)
    {
        Owner = specifications[2];
    }
}
</code>```

Serialization works fine and I can save the json formatted data in a file. I am storing a list of ComputerNode objects in a file.
Following code for file read/write operation:

```<code>public class Operation<T>
{
    public string path;

    public Operation()
    {
        var path = Path.Combine(Directory.GetCurrentDirectory(), "nodes.txt");

        if (File.Exists(path) == false)
        {
            using (File.Create(path))
            {
            }
        }
        this.path = path;
    }

    public void Write(string path, List<T> nodes)
    {
        var ser = JsonConvert.SerializeObject(nodes);

        File.WriteAllText(path, ser);
    }

    public List<T> Read(string path)
    {
        var text = File.ReadAllText(path);

        var res =  JsonConvert.DeserializeObject<List<T>>(text);
        return res;
    }

}
</code>```

The expected file Read result should be a list of ComputerNode objects stored in a file.
However, while deserialization - creating an object of ComputerNode, correct constructor is called but the argument (string[] specifications) is null.

Is there any better way to work with it.

Please do not suggest to change BaseNode.cs or ComputerNode.cs

Thanks for suggestion...

Correct Answer

Overridden with new Json constructor. In BaseNode.cs

```<code>    [JsonConstructor]
    public BaseNode(string Owner, string Name, string Identifier)
    {
        this.Name = Name;
        this.Identifier = Identifier;
    }
</code>```

and
Overridden a Json constructor - ComputerNode.cs

```<code>    [JsonConstructor]
    public ComputerNode(string Owner, string Name, string Identifier):base(Owner, Name, Identifier)
    {
        this.Owner = Owner;
    }
</code>```

答:
in practice if you run

```<code>var ser = JsonConvert.SerializeObject(nodes);
File.WriteAllText(path, ser);
</code>```

where nodes is a List<T>

then

```<code>var text = File.ReadAllText(path);
var res =  JsonConvert.DeserializeObject<List<T>>(text);
</code>```

where res is a List<T>

According to the JsonConstructor documentation: http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonConstructorAttribute.htm

Instructs the JsonSerializer to use the specified constructor when deserializing that object.

No where it is said that there will be a constructor parameter related with the string to be deserialized.

in fact the constructor you designate ([JsonConstructor]) try to override the result of the deserialization with an always null parameter

In your case you should have

```<code>[JsonConstructor]
protected BaseNode()
{

}
</code>```

to avoid the constructor over interacting with the deserialization.

IMHO, the deserializer will never (according to documentation) give a parameter to a constructor.

Body:
I am using Newtonsoft libraries for serialization and deserialization json object.
The reference code is below:

 public abstract class BaseNode
{
    [JsonConstructor]
    protected BaseNode(string [] specifications)
    {
        if (specifications == null)
        {
            throw new ArgumentNullException();
        }
        if (specifications.Length == 0)
        {
            throw new ArgumentException();
        }

        Name = specifications[0];
        Identifier = specifications[1];
        //Owner = specifications[2];
    }

    public string Name{ get; protected set; }
    public string Identifier { get; protected set; }
    public string Owner { get; protected set; }
}

public class ComputerNode: BaseNode
{
    [JsonConstructor]
    public ComputerNode(string[] specifications):base(specifications)
    {
        Owner = specifications[2];
    }
}

Serialization works fine and I can save the json formatted data in a file. I am storing a list of ComputerNode objects in a file.
Following code for file read/write operation:

public class Operation<T>
{
    public string path;

    public Operation()
    {
        var path = Path.Combine(Directory.GetCurrentDirectory(), "nodes.txt");

        if (File.Exists(path) == false)
        {
            using (File.Create(path))
            {
            }
        }
        this.path = path;
    }

    public void Write(string path, List<T> nodes)
    {
        var ser = JsonConvert.SerializeObject(nodes);

        File.WriteAllText(path, ser);
    }

    public List<T> Read(string path)
    {
        var text = File.ReadAllText(path);

        var res =  JsonConvert.DeserializeObject<List<T>>(text);
        return res;
    }

}

The expected file Read result should be a list of ComputerNode objects stored in a file.
However, while deserialization - creating an object of ComputerNode, correct constructor is called but the argument (string[] specifications) is null.

Is there any better way to work with it.

Please do not suggest to change BaseNode.cs or ComputerNode.cs

Thanks for suggestion...

Correct Answer

Overridden with new Json constructor. In BaseNode.cs

    [JsonConstructor]
    public BaseNode(string Owner, string Name, string Identifier)
    {
        this.Name = Name;
        this.Identifier = Identifier;
    }

and
Overridden a Json constructor - ComputerNode.cs

    [JsonConstructor]
    public ComputerNode(string Owner, string Name, string Identifier):base(Owner, Name, Identifier)
    {
        this.Owner = Owner;
    }

Body:
in practice if you run

var ser = JsonConvert.SerializeObject(nodes);
File.WriteAllText(path, ser);

where nodes is a List<T>

then

var text = File.ReadAllText(path);
var res =  JsonConvert.DeserializeObject<List<T>>(text);

where res is a List<T>

According to the JsonConstructor documentation: http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonConstructorAttribute.htm

Instructs the JsonSerializer to use the specified constructor when deserializing that object.

No where it is said that there will be a constructor parameter related with the string to be deserialized.

in fact the constructor you designate ([JsonConstructor]) try to override the result of the deserialization with an always null parameter

In your case you should have

[JsonConstructor]
protected BaseNode()
{

}

to avoid the constructor over interacting with the deserialization.

IMHO, the deserializer will never (according to documentation) give a parameter to a constructor.


问:
How can hide the textbox on basis on checkbox in JSP
In my JSP page two fields one is textbox and one is checkbox, I tried with     j query and java script also for hiding the textbox on checked of checkbox but it is not reflecting. Below I am mentioning code here

```<code><p class="contact"> <input id="check" name="check" value="check" style="margin-right: 10px" type="checkbox" tabindex="11">
        <label for="name"> Not Yet Registered</label> </p>

        <p class= "reg"><label for="reg">Register No.</label></p><br>
        <input id = "reg" maxlength="15"  name= "reg" placeholder="Reg No." type ="text" tabindex="12"><br><br>
</code>```

J query

```<code>$('#check').click(function() {
  $('.reg')[this.checked ? "hide" : "show"]();
});
</code>```

Kindly Help me out

答:
```<code>`$('.reg')[this.checked ? "hide" : "show"]();`
</code>```

this will hide only the
 tag you need to use $('#reg')[this.checked ? "hide" : "show"]();

to hide the input box.

full code

```<code>$(document).ready(function () {
    $('#check').click(function () {
        $('.reg')[this.checked ? "hide" : "show"]();
        $('#reg')[this.checked ? "hide" : "show"]();
    });
});
</code>```

Body:
In my JSP page two fields one is textbox and one is checkbox, I tried with     j query and java script also for hiding the textbox on checked of checkbox but it is not reflecting. Below I am mentioning code here

 <input id="check" name="check" value="check" style="margin-right: 10px" type="checkbox" tabindex="11">
         Not Yet Registered

Register No.

        <input id = "reg" maxlength="15"  name= "reg" placeholder="Reg No." type ="text" tabindex="12">

J query

$('#check').click(function() {
  $('.reg')[this.checked ? "hide" : "show"]();
});

Kindly Help me out

Body:
`$('.reg')[this.checked ? "hide" : "show"]();`

this will hide only the <p> tag you need to use $('#reg')[this.checked ? "hide" : "show"]();

to hide the input box.

full code

$(document).ready(function () {
    $('#check').click(function () {
        $('.reg')[this.checked ? "hide" : "show"]();
        $('#reg')[this.checked ? "hide" : "show"]();
    });
});


问:
Calculate lower and upper log10 value of numbers
I would like to calculate the log10 lower and upper values of a number. E.g. for val=4 it should return 1 as lower and 10 as upper log10 value.

```<code>data a;
  infile datalines;
  input val;
  datalines;
4
27
38765
983434
;
run;
</code>```

This should be the result:

How can I achieve this and which functions are needed? The function log10 calculates just the value of val to the base of 10.

答:
I'm not a math Ph.D., but log10 does what log10 says it does, namely, calculate the log-base-10 of a number.  I've never heard of "lower log10" or "upper log10", nor has Google as far as I can tell.

What it sounds like you want is the number which would have an integer logarithm (base 10) which is less than or equal to the number given, and the number which would have an integer logarithm (base 10) which is greater than or equal to the number given.  (What if the number given is exactly 10, you don't say what to do).

Easily enough done by re-exponentiating after floor/ceil:

```<code>data _null_;
  input x;
  l_x = 10**(floor(log10(x)));
  u_x = 10**(ceil(log10(x)));
  put x= l_x= u_x=;
datalines;
4
27
38765
983434
;;;;
run;
</code>```

Body:
I would like to calculate the log10 lower and upper values of a number. E.g. for val=4 it should return 1 as lower and 10 as upper log10 value.

data a;
  infile datalines;
  input val;
  datalines;
4
27
38765
983434
;
run;

This should be the result:

How can I achieve this and which functions are needed? The function log10 calculates just the value of val to the base of 10.

Body:
I'm not a math Ph.D., but log10 does what log10 says it does, namely, calculate the log-base-10 of a number.  I've never heard of "lower log10" or "upper log10", nor has Google as far as I can tell.

What it sounds like you want is the number which would have an integer logarithm (base 10) which is less than or equal to the number given, and the number which would have an integer logarithm (base 10) which is greater than or equal to the number given.  (What if the number given is exactly 10, you don't say what to do).

Easily enough done by re-exponentiating after floor/ceil:

data _null_;
  input x;
  l_x = 10**(floor(log10(x)));
  u_x = 10**(ceil(log10(x)));
  put x= l_x= u_x=;
datalines;
4
27
38765
983434
;;;;
run;


问:
Sqlite.Swift Ambiguous Column Name Swift
My code is as follows:

```<code>let assetTag = Expression<String>("asset_tag")

let query2 = mdm.select(mdm[assetTag],os, mac, lastReported)
                .filter(mdm[assetTag] != "ipad" && location == facility)
                .order(mdm[assetTag])
                .join(mdm, on: ewp[assetTag] == mdm[assetTag])

            let results2 = try! db.prepare(query2)
</code>```

I am getting error that says:

fatal error: 'try!' expression unexpectedly raised an error: ambiguous column name: mdm.asset_tag (code: 1): file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-802.0.53/src/swift/stdlib/public/core/ErrorType.swift, line 182

My database has two tables, one called eWP and one called MDM. Both do have a column called asset_tag so I thought by doing mdm[assetTag] that would select the correct one but it still throws the error.

EDIT

Still unable to resolve issue. I create my tables as follows:

```<code>let db = try Connection("\(path)/db.sqlite3")

        try db.run(ewp.create { t in
            t.column(assetTag)
            t.column(location)
            t.column(deviceStatus)

        })

        try db.run(mdm.create { t in
            t.column(assetTag)
            t.column(os)
            t.column(mac)
            t.column(lastReported)

        })

    }
</code>```

For some reason, mdm[assetTag] is still saying the column is ambiguous but theres only 1 column like that.

答:
Found the answer. I was joining the mdm table on itself. I needed to change the join to:

.join(ewp, on: ewp[assetTag] == mdm[assetTag])

Body:
My code is as follows:

let assetTag = Expression<String>("asset_tag")

let query2 = mdm.select(mdm[assetTag],os, mac, lastReported)
                .filter(mdm[assetTag] != "ipad" && location == facility)
                .order(mdm[assetTag])
                .join(mdm, on: ewp[assetTag] == mdm[assetTag])

            let results2 = try! db.prepare(query2)

I am getting error that says:

fatal error: 'try!' expression unexpectedly raised an error: ambiguous column name: mdm.asset_tag (code: 1): file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-802.0.53/src/swift/stdlib/public/core/ErrorType.swift, line 182

My database has two tables, one called eWP and one called MDM. Both do have a column called asset_tag so I thought by doing mdm[assetTag] that would select the correct one but it still throws the error.

EDIT

Still unable to resolve issue. I create my tables as follows:

let db = try Connection("\(path)/db.sqlite3")

        try db.run(ewp.create { t in
            t.column(assetTag)
            t.column(location)
            t.column(deviceStatus)

        })

        try db.run(mdm.create { t in
            t.column(assetTag)
            t.column(os)
            t.column(mac)
            t.column(lastReported)

        })

    }

For some reason, mdm[assetTag] is still saying the column is ambiguous but theres only 1 column like that.


问:
How do I get the xpath, or other locators?
I needed help to get the best possible element locator can I use for a button with the following code;</p>

```<code><button onclick="btnProcess($(this), 'Adding...','fa-refresh fa-spin',0);callServer('/DejavuMobile/action/UserGroupModel_AddItem/Users/Add?hfUsername=8_44&ic=44&hfService=', function(response){ btnProcess($(this), 'Add new item','fa-plus',1);loadContent($('#UserAddUI') ,response); });" class="btn btn-xs btn-labeled btn-info" type="button" style="padding-right:12px;padding-left:12px;margin-left:15px;margin-bottom:15px;"><span class="btn-label"><i class="fa fa-plus"></i></span>Add new Group</button>
</code>```

答:
The most readable one:

```<code>//button[text()='Add new Group']
</code>```

It's possible to create path using class or any other attribute, but by text in this case is the most clear and easy way.

Body:
I needed help to get the best possible element locator can I use for a button with the following code;

<button onclick="btnProcess($(this), 'Adding...','fa-refresh fa-spin',0);callServer('/DejavuMobile/action/UserGroupModel_AddItem/Users/Add?hfUsername=8_44&ic=44&hfService=', function(response){ btnProcess($(this), 'Add new item','fa-plus',1);loadContent($('#UserAddUI') ,response); });" class="btn btn-xs btn-labeled btn-info" type="button" style="padding-right:12px;padding-left:12px;margin-left:15px;margin-bottom:15px;">Add new Group</button>

Body:
The most readable one:

//button[text()='Add new Group']

It's possible to create path using class or any other attribute, but by text in this case is the most clear and easy way.


问:
Can someone help me point out my error here?
```<code>def target(heart):

    age = input("Enter your age: ")
    rest_heart = input("Enter your resting heart rate: ")
    intensity = input("Enter your heart intensity: ")
    max_heart = 220 - age
    reserve = max_heart - rest_heart
    return rest_heart + intensity * reserve

print(target(heart))
</code>```

Error message:

```<code>Traceback (most recent call last):

  File "<string>", line 9, in <module>

NameError: name 'heart' is not defined
</code>```

If someone could point out the error, that'd be greatly appreciated

答:
Simply answering your question wouldn't really help you since one day or another you will need to know how to handle your errors by yourself.. In this context i'm offering you this tutorial which will teach you python appropriately with applications.

However, the problem of your script is that you're trying to call a variable heart you didn't create in the first place.

Also, like others pointed out, passing heart as a parameter is useless since you're not using it inside your function.

As a conclusion, I advise you to follow the guide provided above.

Hope this was somehow helpfull.

Body:
def target(heart):

    age = input("Enter your age: ")
    rest_heart = input("Enter your resting heart rate: ")
    intensity = input("Enter your heart intensity: ")
    max_heart = 220 - age
    reserve = max_heart - rest_heart
    return rest_heart + intensity * reserve

print(target(heart))

Error message:

Traceback (most recent call last):

  File "<string>", line 9, in <module>

NameError: name 'heart' is not defined

If someone could point out the error, that'd be greatly appreciated


问:
Elasticsearch-Rails & Elasticsearch 5.4: Geopoint not updating
So I am running a Rails 5 application using elasticsearch-rails Gem to work with Elasticsearch 5.4.

Everything works fine, the only problem I am having is that when I update the location using Geocoding to retrieve the new longitude and latitude, the coordinates do not get updated in Elasticsearch (using Geopoint). It is however correctly reflected in the database, meaning Geocoding, etc. works fine.

models/concerns/user_searchable.rb

```<code>include Elasticsearch::Model
include Elasticsearch::Model::Callbacks

index_name Rails.application.class.parent_name.underscore
document_type self.name.downcase

settings index: { number_of_shards: 1 } do
  mapping dynamic: false do
    indexes :description, analyzer: 'english'
    indexes :tagline, analyzer: 'english'
    indexes :username
    indexes :location, type: 'geo_point'
    indexes :active, type: 'boolean'
    ...
  end
end

after_touch() { __elasticsearch__.index_document }

def as_indexed_json(_options = {})
  self.as_json(
      except: [:email, :lat, :lng, :status, :termsofuse, :v_code],
      include: {
          photos: { only: [:name, :caption, :active, :image_data] }
  ).merge(
      location: {lat: lat, lon: lng},
      age: birthday.nil? ? 18 : ((Date.today - birthday.to_date) / 365.25).floor
  )
end
</code>```

Perhaps someone has a quick fix for this.

答:
@Georg Keferböck

You make a instance method location which will return { lat: lat, lon: lng } and then you can just include such method inside as_indexed_json.
That way it will be much more cleaner and also you can reuse it afterwards ;)

Regards

Body:
So I am running a Rails 5 application using elasticsearch-rails Gem to work with Elasticsearch 5.4.

Everything works fine, the only problem I am having is that when I update the location using Geocoding to retrieve the new longitude and latitude, the coordinates do not get updated in Elasticsearch (using Geopoint). It is however correctly reflected in the database, meaning Geocoding, etc. works fine.

models/concerns/user_searchable.rb

include Elasticsearch::Model
include Elasticsearch::Model::Callbacks

index_name Rails.application.class.parent_name.underscore
document_type self.name.downcase

settings index: { number_of_shards: 1 } do
  mapping dynamic: false do
    indexes :description, analyzer: 'english'
    indexes :tagline, analyzer: 'english'
    indexes :username
    indexes :location, type: 'geo_point'
    indexes :active, type: 'boolean'
    ...
  end
end

after_touch() { __elasticsearch__.index_document }

def as_indexed_json(_options = {})
  self.as_json(
      except: [:email, :lat, :lng, :status, :termsofuse, :v_code],
      include: {
          photos: { only: [:name, :caption, :active, :image_data] }
  ).merge(
      location: {lat: lat, lon: lng},
      age: birthday.nil? ? 18 : ((Date.today - birthday.to_date) / 365.25).floor
  )
end

Perhaps someone has a quick fix for this.


问:
How to add extra meta data to PNG?
is there a way to add some extra metadata to a PNG file and then retrieve it with PHP ?

like Comment field.

答:
If you have ImageMagick installed, it comes with two utilities: mogrify and identify.

To add comments:

```<code>$ mogrify.exe -comment "My test comment" plogo.png
</code>```

To retrieve comments:

```<code>$ identify.exe -verbose plogo.png  | grep -i "comment:"
    comment: My test comment
</code>```

I don't know if mogrify/identify functions are available as PHP libraries, but you can always use the php system command.

Title: How to add extra meta data to PNG?

Body:
If you have ImageMagick installed, it comes with two utilities: mogrify and identify.

To add comments:

$ mogrify.exe -comment "My test comment" plogo.png

To retrieve comments:

$ identify.exe -verbose plogo.png  | grep -i "comment:"
    comment: My test comment

I don't know if mogrify/identify functions are available as PHP libraries, but you can always use the php system command.


问:
FTP SSL through PeopleCode/Soft
I'm trying to use PeopleCode to get a file from a remote FTP server that uses SSL. The GetAttachment command returns error code 8, which indicates a problem connecting or authenticating with the "destination server" (which I'm assuming means "remote server"). I don't think the problem is in my code itself, although I'm not discounting that, but rather in the URL configuration and the security certificate.

First, my PeopleCode is:

```<code>&returnCode = GetAttachment(URL.MY_FTP_URL, &fileName, &destinationPath);
If &returnCode = %Attachment_Success Then
   [...]
Else
   MessageBox(0, "", 0, 0, "Fail: " | &returnCode)
End-If;
</code>```

I've created the URL definition via PeopleTools > Utilities > Administration > URLs. The URL is pretty straight forward. The URLID is "ftps://[remote server]/". I know this connection requires active mode and SSL, so I've added the properties (in addition to username and password) ACTIVEMODE = Y, and SSLUSAGELEVEL = 3.

Now, here is where I think the problem is. By adding the SSLUSAGELEVEL property, I also need to add the CERTALIAS property and (presumably) set it to the name of the SSL certificate. So I got the certificate, uploaded it and created the definition. I went back to the URL definition, added the CERTALIAS property, but the prompt box for the valid values is empty.

I think my problem now is that I need to perform some other step to get the certificate I created to show up in the CERTALIAS prompt. Is my approach generally in the right direction? Or am I missing something else entirely?

Thanks,

答:
First, confirm that it is working at the operating system level.

I have noticed that GetAttachment does not always copy over the ssl certificate with the proper file system permissions, in Oracle linux, to the app server working directory and because of the incorrect file permissions, the destination server will refuse the connection.

I had to create the key file with the correct file permissions and hardcode the path to this key file, with the correct file permissions, in the URL entry.

Title: FTP SSL through PeopleCode/Soft

Body:
I'm trying to use PeopleCode to get a file from a remote FTP server that uses SSL. The GetAttachment command returns error code 8, which indicates a problem connecting or authenticating with the "destination server" (which I'm assuming means "remote server"). I don't think the problem is in my code itself, although I'm not discounting that, but rather in the URL configuration and the security certificate.

First, my PeopleCode is:

&returnCode = GetAttachment(URL.MY_FTP_URL, &fileName, &destinationPath);
If &returnCode = %Attachment_Success Then
   [...]
Else
   MessageBox(0, "", 0, 0, "Fail: " | &returnCode)
End-If;

I've created the URL definition via PeopleTools > Utilities > Administration > URLs. The URL is pretty straight forward. The URLID is "ftps://[remote server]/". I know this connection requires active mode and SSL, so I've added the properties (in addition to username and password) ACTIVEMODE = Y, and SSLUSAGELEVEL = 3.

Now, here is where I think the problem is. By adding the SSLUSAGELEVEL property, I also need to add the CERTALIAS property and (presumably) set it to the name of the SSL certificate. So I got the certificate, uploaded it and created the definition. I went back to the URL definition, added the CERTALIAS property, but the prompt box for the valid values is empty.

I think my problem now is that I need to perform some other step to get the certificate I created to show up in the CERTALIAS prompt. Is my approach generally in the right direction? Or am I missing something else entirely?

Thanks,


问:
Sending information from iOS to macOS
I'm working on an app for iOS and macOS and should be installed on both devices (iOS device and Mac computer) to work.

I want an option to send strings from the iOS device to the Mac (for example: if the user writes "Hello World!" and presses "transfer" button I want to get it instantly on the Mac app).

What is the best option to send strings from an iOS app to a macOS app (it should work even when the device isn't near the computer and even if it's not connected to the same WIFI network)?

Thank you!

答:
You have two Options:

Server on MacOS + Client on iOS + Port Forwarding (Router)

Client on MacOS + Client on iOS + Server in the Internet

You would usually go for the second option because the user doesn't need to configure Port Forwarding.

The connection would be a HTTP(S) connection. On MacOS and iOS there are APIs available which support HTTP(S).

(If you need a more specific answer you need to ask a more specific question)

Title: Sending information from iOS to macOS


问:
Code swap. How would I swap the value of one CSV file column to another?
I have two CSV files. The first file(state_abbreviations.csv) has only states abbreviations and their full state names side by side(like the image below), the second file(test.csv) has the state abbreviations with additional info.

I want to replace each state abbreviation in test.csv with its associated state full name from the first file.

My approach was to read reach file, built a dict of the first file(state_abbreviations.csv). Read the second file(test.csv), then compare if an abbreviation matches the first file, if so replace it with the full name.

Any help is appreacited

```<code>import csv

state_initials = ("state_abbr")
state_names = ("state_name")
state_file = open("state_abbreviations.csv","r")
state_reader = csv.reader(state_file)

headers = None
final_state_initial= []
for row in state_reader:
    if not headers:
        headers = []
        for i, col in enumerate(row):
           if col in state_initials:
            headers.append(i)
    else:
        final_state_initial.append((row[0]))

print final_state_initial

headers = None
final_state_abbre= []
for row in state_reader:
    if not headers:
        headers = []
        for i, col in enumerate(row):
           if col in state_initials:
            headers.append(i)
    else:
        final_state_abbre.append((row[1]))

print final_state_abbre

final_state_initial
final_state_abbre
state_dictionary = dict(zip(final_state_initial, final_state_abbre))
print state_dictionary
</code>```

答:
Step 1: Ask Python to remember the abbreviated full names, so we are using dictionary for that

```<code>with open('state_abbreviations.csv', 'r') as f:
    csvreader = csv.reader(f)
    next(csvreader)
    abs = {r[0]: r[1] for r in csvreader}
</code>```

step 2: Replace the abbreviations with full names and write to an output, I used "test_output.csv"

```<code>with open('test.csv', 'r') as reading:
    csvreader = csv.reader(reading)
    next(csvreader)
    header = ['name', 'gender', 'birthdate', 'address', 'city', 'state']
    with open( 'test_output.csv', 'w' ) as f:
        writer = csv.writer(f)
        writer.writerow(header)
        for a in csvreader:
            writer.writerow(a[0], a[1], a[2], a[3], a[4], abs[a[5]])
</code>```

Body:
I have two CSV files. The first file(state_abbreviations.csv) has only states abbreviations and their full state names side by side(like the image below), the second file(test.csv) has the state abbreviations with additional info.

I want to replace each state abbreviation in test.csv with its associated state full name from the first file.

My approach was to read reach file, built a dict of the first file(state_abbreviations.csv). Read the second file(test.csv), then compare if an abbreviation matches the first file, if so replace it with the full name.

Any help is appreacited

import csv

state_initials = ("state_abbr")
state_names = ("state_name")
state_file = open("state_abbreviations.csv","r")
state_reader = csv.reader(state_file)

headers = None
final_state_initial= []
for row in state_reader:
    if not headers:
        headers = []
        for i, col in enumerate(row):
           if col in state_initials:
            headers.append(i)
    else:
        final_state_initial.append((row[0]))

print final_state_initial

headers = None
final_state_abbre= []
for row in state_reader:
    if not headers:
        headers = []
        for i, col in enumerate(row):
           if col in state_initials:
            headers.append(i)
    else:
        final_state_abbre.append((row[1]))

print final_state_abbre

final_state_initial
final_state_abbre
state_dictionary = dict(zip(final_state_initial, final_state_abbre))
print state_dictionary

Body:
Step 1: Ask Python to remember the abbreviated full names, so we are using dictionary for that

with open('state_abbreviations.csv', 'r') as f:
    csvreader = csv.reader(f)
    next(csvreader)
    abs = {r[0]: r[1] for r in csvreader}

step 2: Replace the abbreviations with full names and write to an output, I used "test_output.csv"

with open('test.csv', 'r') as reading:
    csvreader = csv.reader(reading)
    next(csvreader)
    header = ['name', 'gender', 'birthdate', 'address', 'city', 'state']
    with open( 'test_output.csv', 'w' ) as f:
        writer = csv.writer(f)
        writer.writerow(header)
        for a in csvreader:
            writer.writerow(a[0], a[1], a[2], a[3], a[4], abs[a[5]])


问:
Is there a way to use gsutil cp to do multiple copies?
I have a set of source/destination pairs for which I could do:
gsutil cp source1 dest1
gsutil cp source2 dest2
etc.

Is there a way to do this for the whole group of transfers in one gsutil command?

答: There's no way to do that with one gsutil command. The best I can recommend would be to write a script that runs the needed gsutil commands, possibly in parallel groups (e.g., 50 at once).</p>


问:
Dynamically match and replace using Bash
I'm using bash to dynamically find and replace a string with another string e.g.

```<code>href="/controller/action"

href="<?php echo $this->url("controller", action-> "action") ?>"
</code>```

I'm using this sed command to find and change it which works fine...

```<code>sed -i 's%href=\"/controller/action%href=\"<?php echo $this->url(\"controller\", action-> \"action\") ?>%g' changes.txt
</code>```

What I want is for the old string to look for any type following a pattern using a wildcard. I saw that this is an option but doesn't work.

```<code>sed -i 's%href=\"/(.*)/(.*)%href=\"<?php echo $this->url(\"/1\", action-> \"/2\") ?>%g' changes.txt
</code>```

How will I be able to run this command so that the controller and action can be anything and dynamically taken from the old string and inputted into the new string?

答:
You are using a greedy dot matching pattern the is almost never what you need since a dot matches any symbol and * quantifier grabs as many chars as it can. What you need is a negated bracket expression [^/]* matching zero or more chars other than /.

Also, since you are using a BRE POSIX regex you must escape the parentheses capturing a part of the pattern, else they denote literal ( and ) symbols.

Use

```<code>sed -i 's%href="/\([^/]*\)/\([^/]*\)%href="<?php echo $this->url("\1", action-> "\2") ?>%g' changes.txt
</code>```

Body:
I'm using bash to dynamically find and replace a string with another string e.g.

href="/controller/action"

href="<?php echo $this->url("controller", action-> "action") ?>"

I'm using this sed command to find and change it which works fine...

sed -i 's%href=\"/controller/action%href=\"<?php echo $this->url(\"controller\", action-> \"action\") ?>%g' changes.txt

What I want is for the old string to look for any type following a pattern using a wildcard. I saw that this is an option but doesn't work.

sed -i 's%href=\"/(.*)/(.*)%href=\"<?php echo $this->url(\"/1\", action-> \"/2\") ?>%g' changes.txt

How will I be able to run this command so that the controller and action can be anything and dynamically taken from the old string and inputted into the new string?

Body:
You are using a greedy dot matching pattern the is almost never what you need since a dot matches any symbol and * quantifier grabs as many chars as it can. What you need is a negated bracket expression [^/]* matching zero or more chars other than /.

Also, since you are using a BRE POSIX regex you must escape the parentheses capturing a part of the pattern, else they denote literal ( and ) symbols.

Use

sed -i 's%href="/\([^/]*\)/\([^/]*\)%href="<?php echo $this->url("\1", action-> "\2") ?>%g' changes.txt


问:
Getting exception while joining the below queries, could someone help me on joining the queries?
Query 1 :

```<code>  select col1,sum(col2) from tablea src
  join
  (select distinct col3,ROW_NUMBER() OVER(ORDER BY col3 desc) as RN )
   From tableb) trgt
   where RN=1 and src.col3 = trgt.col3 group by col1
</code>```

Query 2 :

```<code> select col1,sum(col2) from tablea src
 join
 (select distinct col3,ROW_NUMBER() OVER(ORDER BY col3 desc) as RN )
 From tableb) trgt
 where RN=2 and src.col3 = trgt.col3 group by col1
</code>```

Join Query :

```<code>   select *
   from (Query 1)  curr join (Query 2)
    prev on curr.col1 = prev.col1
</code>```

FAILED: ParseException line 6:75 cannot recognize input near 'as' 'curr' in subquery source

答:
I think there is no need to join these two queries, since they are very similar to each other like two drops of water.

Some kind of pivot query can do this job:

```<code>SELECT col1,
       SUM( CASE WHEN rn=1 THEN col2 END ),
       SUM( CASE WHEN rn=2 THEN col2 END )
FROM  tablea src
JOIN (
   select col3,ROW_NUMBER() OVER(ORDER BY col3 desc) as RN )
   From tableb
) trgt
ON src.col3 = trgt.col3 AND trgt.rn <= 2
GROUP BY col1
</code>```

Body:
Query 1 :

  select col1,sum(col2) from tablea src
  join
  (select distinct col3,ROW_NUMBER() OVER(ORDER BY col3 desc) as RN )
   From tableb) trgt
   where RN=1 and src.col3 = trgt.col3 group by col1

Query 2 :

 select col1,sum(col2) from tablea src
 join
 (select distinct col3,ROW_NUMBER() OVER(ORDER BY col3 desc) as RN )
 From tableb) trgt
 where RN=2 and src.col3 = trgt.col3 group by col1

Join Query :

   select *
   from (Query 1)  curr join (Query 2)
    prev on curr.col1 = prev.col1

FAILED: ParseException line 6:75 cannot recognize input near 'as' 'curr' in subquery source

Body:
I think there is no need to join these two queries, since they are very similar to each other like two drops of water.

Some kind of pivot query can do this job:

SELECT col1,
       SUM( CASE WHEN rn=1 THEN col2 END ),
       SUM( CASE WHEN rn=2 THEN col2 END )
FROM  tablea src
JOIN (
   select col3,ROW_NUMBER() OVER(ORDER BY col3 desc) as RN )
   From tableb
) trgt
ON src.col3 = trgt.col3 AND trgt.rn <= 2
GROUP BY col1


问:
How to prevent PostgreSQL to make uncontrolled checkpoints?
I want to be able to disable PostgreSQL to auto checkpoint.

I just want to fsync wal files on disk without saving changes made in shared_buffer.

I set checkpoint_segments and checkpoint_timeout to big values, but still it makes additional checkpoints.

I don't want to checkpoint not even he needs to swap pages or is out of memory.

答:
There are other causes for checkpoints:

Recovery has finished (could happen after a server crash).

Start of an online backup.

Database shutdown.

Before and after CREATE DATABASE.

After DROP DATABASE.

Before and after ALTER DATABASE SET TABLESPACE (you probably don't do that every day).

During DROP TABLESPACE (ditto).

And, of course, an explicit CHECKPOINT command.

I hope I haven't forgotten anything – could one of these cause the checkpoints you observe?

Set log_checkpoints to on, then the log file will show the cause of the checkpoint in the checkpoint starting message.

Are you sure that it is a good idea to avoid checkpoints? They are needed so that you can recover your database if there is a problem.


问:
send follow request to protected user in twitter
I am using Tweepy to automatically send follow request to twitter users who have protected profile. But I get Not authorized exception while using api.create_friendship(uid) method. Is there any workaround for this problem?

答: No, there's no API method to enable you to do this. The requests have to be acknowledged via the Twitter website.</p>


问:
Shift the offset during eval (using sourcemap)
I'm loading a script from a file, and I'm using eval() to generate a Javascript code like this:

```<code>var code = fs.readFileSync('myfile');
var shiftedCode= 'function(param) {' + code + '}\n'+ '//# sourceURL=myfile';
eval(shiftedCode)
</code>```

The problem is when I put a breakpoint or debugger inside the code, it stops two lines after the correct one because of the added chars at the beginning I suppose.

Is there a way to shift the sourceURL to the correct start point may be using sourcemaps?

Thank you in advance for your help.

答:
you can use below package offset-sourcemap-lines </p>

```<code>var offsetLines = require('offset-sourcemap-lines');
var conv = require('convert-source-map');
var fs = require('fs');

var codeWithSourceMapComment = fs.readFileSync('/path/to/code-with-sourcemap-comment.js', 'utf-8');
var originalMap = conv.fromSource(codeWithSourceMapComment).toObject();

var header = 'function(param) {' + code + '}\n';
var offset = header.match(/\n/g).length + 2; //you might need to work on this

var offsettedMap = offsetLines(originalMap, offset);

var codeBody = conv.removeComments(codeWithSourceMapComment);
var newSourceMapComment = conv.fromObject(offsettedMap).toComment();
console.log(header + codeBody + '\n' + newSourceMapComment);
</code>```

Body:
I'm loading a script from a file, and I'm using eval() to generate a Javascript code like this:

var code = fs.readFileSync('myfile');
var shiftedCode= 'function(param) {' + code + '}\n'+ '//# sourceURL=myfile';
eval(shiftedCode)

The problem is when I put a breakpoint or debugger inside the code, it stops two lines after the correct one because of the added chars at the beginning I suppose.

Is there a way to shift the sourceURL to the correct start point may be using sourcemaps?

Thank you in advance for your help.

Body:
you can use below package offset-sourcemap-lines

var offsetLines = require('offset-sourcemap-lines');
var conv = require('convert-source-map');
var fs = require('fs');

var codeWithSourceMapComment = fs.readFileSync('/path/to/code-with-sourcemap-comment.js', 'utf-8');
var originalMap = conv.fromSource(codeWithSourceMapComment).toObject();

var header = 'function(param) {' + code + '}\n';
var offset = header.match(/\n/g).length + 2; //you might need to work on this

var offsettedMap = offsetLines(originalMap, offset);

var codeBody = conv.removeComments(codeWithSourceMapComment);
var newSourceMapComment = conv.fromObject(offsettedMap).toComment();
console.log(header + codeBody + '\n' + newSourceMapComment);


问:
How to get CPU usage in Qt?
I have a main server and 4 computers connected. How can I learn which computer use how much CPU and disk.

I write code using Qt and C++.

答: Qt does not have an API for this.  You'll need to use the platforms native API.</p>

ContentLicense: CC BY-SA 4.0

Title: How to get CPU usage in Qt?


问:
How to insert strings into array and let it choose between 2D arrays a random array?
I can't really think of a suitable question sentence, so let me explain what am I trying to do here.

I'm running a project where the user will input sentences into my program/temporary memory. It will then scans for words, then it will pass the word ( it can be anything ) into a variable - let just call it myWord.

Simultaneously, that word will be scan through my arrays ( database ) to look for its synonyms. That synonym will then be chose randomly from my list of arrays and then be assigned to myWord. The myWord will overwrite the sentence originally input and output the new sentence.

Conclusively, how can I code to make my software scan the sentence that hold synonyms ( i will not change all words to its synonyms, just certain word - can code that myself )  and to choose its synonyms (to rewrite original) from arrays?

Any ideas, algorithms, approaches or libraries is greatly appreciated.
Thank you.

答:
If you are using c++11, what you can use is an unordered map of word to all its synonyms:

```<code>#include <unordered_map>
#include <vector>

unordered_map<string, vector<string>> makeSynonyms() {
   unordered_map<string, vector<string>> synonyms;
   // load up your synonyms
   synomyms["happy"] = {"cheerful", "pleased", "delighted"};
   synomyms["cheerful"] = {"happy", "pleased", "delighted"};
   synonyms["pleased"] = {"happy", "cheerful", "delighted"};
   return synonyms;
}
</code>```

Now to use it, you can pick a random synonym from the synonyms map for each word in your input.

```<code>unordered_map<string, vector<string>> synonyms = makeSynonyms();
string myWord = "happy";
vector<string> wordSynonyms = synonyms[myWord]; // this gets a list of synonyms
// now you can get a random element from the list
</code>```

Body:
If you are using c++11, what you can use is an unordered map of word to all its synonyms:

#include <unordered_map>
#include <vector>

unordered_map<string, vector<string>> makeSynonyms() {
   unordered_map<string, vector<string>> synonyms;
   // load up your synonyms
   synomyms["happy"] = {"cheerful", "pleased", "delighted"};
   synomyms["cheerful"] = {"happy", "pleased", "delighted"};
   synonyms["pleased"] = {"happy", "cheerful", "delighted"};
   return synonyms;
}

Now to use it, you can pick a random synonym from the synonyms map for each word in your input.

unordered_map<string, vector<string>> synonyms = makeSynonyms();
string myWord = "happy";
vector<string> wordSynonyms = synonyms[myWord]; // this gets a list of synonyms
// now you can get a random element from the list


问:
Linq: help me to make this work
I have this column:

```<code>    PersonId   CategoryId   SubCategoryId
1      61           47
2      61           48
3      61           0           424
4      61           0           425
5      84           55
6      61                       585
7      101          48
8      101                      424
8      666          47
10     666                      424
</code>```

When i search only for categoryId its fine, and subCategoryId its fine, but when i search for both, like categoryId = 47 && subCategoryId = 424.
I cant make it work... in this case i only need person 61 and person 666.

i can do with a foreach, but not a good idea for performance.

u guys can help me?

```<code>if (ids.IdCategory != null && ids.IdSubCategory != null)
{
    query = unitOfWork.PersonSkillsRepository.GetAll().Where(m => m.IdCategory == ids.IdCategory || m.IdSubCategory == ids.IdSubCategory);
}
else if (ids.IdCategory != null)
    query = unitOfWork.PersonSkillsRepository.GetAll().Where(m => m.IdCategory == ids.IdCategory);
else
    query = unitOfWork.PersonSkillsRepository.GetAll().Where(m => m.IdSubCategory == ids.IdSubCategory);
</code>```

first case i get half what i want... but i want some way to filter, because in this way i get 101 too and i dont know how to see if people have both category and subcategory

and i cant see a way to do this without a foreach

答:
```<code>entities.Where(z => z.categoryId == 47 || z.subCategoryId == 424)
    .GroupBy(z => z.personId)
    .Where(z => z.Count() == 2)
    .SelectMany(z => z.ToList());
</code>```

will likely get you the data that you need.

That query says 'filter the data and only return those where categoryId is 47 or subCategoryId = 424'. Then it groups them together and checks that there are two of them (i.e. one row for the categoryId and one for the subCategoryId).

Title: Linq: help me to make this work

Body:
I have this column:

    PersonId   CategoryId   SubCategoryId
1      61           47
2      61           48
3      61           0           424
4      61           0           425
5      84           55
6      61                       585
7      101          48
8      101                      424
8      666          47
10     666                      424

When i search only for categoryId its fine, and subCategoryId its fine, but when i search for both, like categoryId = 47 && subCategoryId = 424.
I cant make it work... in this case i only need person 61 and person 666.

i can do with a foreach, but not a good idea for performance.

u guys can help me?

if (ids.IdCategory != null && ids.IdSubCategory != null)
{
    query = unitOfWork.PersonSkillsRepository.GetAll().Where(m => m.IdCategory == ids.IdCategory || m.IdSubCategory == ids.IdSubCategory);
}
else if (ids.IdCategory != null)
    query = unitOfWork.PersonSkillsRepository.GetAll().Where(m => m.IdCategory == ids.IdCategory);
else
    query = unitOfWork.PersonSkillsRepository.GetAll().Where(m => m.IdSubCategory == ids.IdSubCategory);

first case i get half what i want... but i want some way to filter, because in this way i get 101 too and i dont know how to see if people have both category and subcategory

and i cant see a way to do this without a foreach

Body:
entities.Where(z => z.categoryId == 47 || z.subCategoryId == 424)
    .GroupBy(z => z.personId)
    .Where(z => z.Count() == 2)
    .SelectMany(z => z.ToList());

will likely get you the data that you need.

That query says 'filter the data and only return those where categoryId is 47 or subCategoryId = 424'. Then it groups them together and checks that there are two of them (i.e. one row for the categoryId and one for the subCategoryId).


问:
IQueryable WhereLike extension with unknown property type
I'm trying to create a WhereLike extension to IQueryable but I can't know the type of the property at runtime.

Here is my code:

```<code>    public static IQueryable WhereLike(this IQueryable source, string propertyName, string pattern)
    {
        if (source == null) throw new ArgumentNullException("source");
        if (propertyName == null) throw new ArgumentNullException("propertyName");

        var a = Expression.Parameter(typeof(object), "a");
        var prop = Expression.Property(a, propertyName);

        return source.Provider.CreateQuery(
            Expression.Call(
                typeof(SqlMethods), "Like",
                null,
                prop, Expression.Constant(pattern)));
    }
</code>```

I get the exception: Instance property 'foo' is not defined for type 'System.Object'

Do you know a way to handle property setting without knowing target type at compile time ?

答:
Determines whether a specific character string matches a specified pattern. A pattern can include regular characters and wildcard characters. During pattern matching, regular characters must exactly match the characters specified in the character string. However, wildcard characters can be matched with arbitrary fragments of the character string. Using wildcard characters makes the LIKE operator more flexible than using the = and != string comparison operators. If any one of the arguments is not of character string data type, the SQL Server Database Engine converts it to character string data type, if it is possible. MSDN

Like operator will work on string type only. If that's what you wanted to do you can achieve with Contains method only, There are also StartsWith and EndsWith equivalent.

You can use Where method only in this extension method

```<code>  var containsParam = Expression.Parameter(typeof(T), "p");
MemberExpression multiSelectmember = Expression.Property(containsParam,propertyname);
    var lstValues = stringvalue;

ConstantExpression multiSelectConstant = Expression.Constant(stringvalue);
var callExpression = Expression.Call(typeof(String), "Contains",
new[] { typeof(string) }, multiSelectConstant, multiSelectmember);
var containsexp = Expression.Lambda<Func<T, bool>>(callExpression,
                                                containsParam);
</code>```

Body:
I'm trying to create a WhereLike extension to IQueryable but I can't know the type of the property at runtime.

Here is my code:

    public static IQueryable WhereLike(this IQueryable source, string propertyName, string pattern)
    {
        if (source == null) throw new ArgumentNullException("source");
        if (propertyName == null) throw new ArgumentNullException("propertyName");

        var a = Expression.Parameter(typeof(object), "a");
        var prop = Expression.Property(a, propertyName);

        return source.Provider.CreateQuery(
            Expression.Call(
                typeof(SqlMethods), "Like",
                null,
                prop, Expression.Constant(pattern)));
    }

I get the exception: Instance property 'foo' is not defined for type 'System.Object'

Do you know a way to handle property setting without knowing target type at compile time ?

Body:
Determines whether a specific character string matches a specified pattern. A pattern can include regular characters and wildcard characters. During pattern matching, regular characters must exactly match the characters specified in the character string. However, wildcard characters can be matched with arbitrary fragments of the character string. Using wildcard characters makes the LIKE operator more flexible than using the = and != string comparison operators. If any one of the arguments is not of character string data type, the SQL Server Database Engine converts it to character string data type, if it is possible. MSDN

Like operator will work on string type only. If that's what you wanted to do you can achieve with Contains method only, There are also StartsWith and EndsWith equivalent.

You can use Where method only in this extension method

  var containsParam = Expression.Parameter(typeof(T), "p");
MemberExpression multiSelectmember = Expression.Property(containsParam,propertyname);
    var lstValues = stringvalue;

ConstantExpression multiSelectConstant = Expression.Constant(stringvalue);
var callExpression = Expression.Call(typeof(String), "Contains",
new[] { typeof(string) }, multiSelectConstant, multiSelectmember);
var containsexp = Expression.Lambda<Func<T, bool>>(callExpression,
                                                containsParam);


问:
Exception when starting android xamarin forms app
I got the following exception within Xamarin in VS 2017 when I change the build configuration from Debug to Release:

```<code>07-07 14:34:49.820 D/AccessibilityManager(10619): setStateLocked: wasEnabled = false, mIsEnabled = false, wasTouchExplorationEnabled = false, mIsTouchExplorationEnabled = false, wasHighTextContrastEnabled = false, mIsHighTextContrastEnabled = false
07-07 14:34:49.820 D/AccessibilityManager(10619): java.lang.Throwable: setStateLocked
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.view.accessibility.AccessibilityManager.setStateLocked(AccessibilityManager.java:553)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.view.accessibility.AccessibilityManager.tryConnectToServiceLocked(AccessibilityManager.java:636)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.view.accessibility.AccessibilityManager.<init>(AccessibilityManager.java:226)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.view.accessibility.AccessibilityManager.getInstance(AccessibilityManager.java:206)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.view.View.setFlags(View.java:9843)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.view.ViewGroup.initViewGroup(ViewGroup.java:536)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.view.ViewGroup.<init>(ViewGroup.java:525)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.view.ViewGroup.<init>(ViewGroup.java:520)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.support.v7.widget.Toolbar.<init>(Toolbar.java:200)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.support.v7.widget.Toolbar.<init>(Toolbar.java:196)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at java.lang.reflect.Constructor.newInstance(Native Method)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at java.lang.reflect.Constructor.newInstance(Constructor.java:288)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.view.LayoutInflater.createView(LayoutInflater.java:607)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:743)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.view.LayoutInflater.inflate(LayoutInflater.java:482)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at md5fcb90111a512f6bdf8650a2bd92e7238.MainActivity.n_onCreate(Native Method)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at md5fcb90111a512f6bdf8650a2bd92e7238.MainActivity.onCreate(MainActivity.java:31)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.app.Activity.performCreate(Activity.java:6092)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1112)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2468)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2595)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.app.ActivityThread.access$800(ActivityThread.java:178)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.os.Handler.dispatchMessage(Handler.java:111)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.os.Looper.loop(Looper.java:194)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.app.ActivityThread.main(ActivityThread.java:5631)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at java.lang.reflect.Method.invoke(Native Method)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at java.lang.reflect.Method.invoke(Method.java:372)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
07-07 14:34:49.831 W/art     (10619): Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
</code>```

All I see from my app is a white screen. And as soon as I change the configuration back to Debug everything is working fine.

Some days ago before I have changed quite a lot on the GUI, everything was working fine. The problem is that I have no idea what the exception message is meaning. What is StateLocked?

As proposed from a comment I add below some more parts of my code:

MainActivity.cs:

```<code>[Activity(Label = "enio.TrackR", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
    protected override void OnCreate(Bundle bundle)
    {
        TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;

        base.OnCreate(bundle);

        global::Xamarin.Forms.Forms.Init(this, bundle);
        LoadApplication(new App());
    }
    protected override void OnStart()
    {
        base.OnStart();
        StartService(new Intent(this, typeof(LocationService)));

    }
}
</code>```

答:
I believe you need to change

```<code>StartService(new Intent(this, typeof(LocationService)));
</code>```

To

```<code>Intent serviceIntent = new Intent(this, typeof(LocationActivity));
context.StartActivity(serviceIntent);
</code>```

Body:
I got the following exception within Xamarin in VS 2017 when I change the build configuration from Debug to Release:

07-07 14:34:49.820 D/AccessibilityManager(10619): setStateLocked: wasEnabled = false, mIsEnabled = false, wasTouchExplorationEnabled = false, mIsTouchExplorationEnabled = false, wasHighTextContrastEnabled = false, mIsHighTextContrastEnabled = false
07-07 14:34:49.820 D/AccessibilityManager(10619): java.lang.Throwable: setStateLocked
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.view.accessibility.AccessibilityManager.setStateLocked(AccessibilityManager.java:553)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.view.accessibility.AccessibilityManager.tryConnectToServiceLocked(AccessibilityManager.java:636)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.view.accessibility.AccessibilityManager.<init>(AccessibilityManager.java:226)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.view.accessibility.AccessibilityManager.getInstance(AccessibilityManager.java:206)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.view.View.setFlags(View.java:9843)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.view.ViewGroup.initViewGroup(ViewGroup.java:536)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.view.ViewGroup.<init>(ViewGroup.java:525)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.view.ViewGroup.<init>(ViewGroup.java:520)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.support.v7.widget.Toolbar.<init>(Toolbar.java:200)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.support.v7.widget.Toolbar.<init>(Toolbar.java:196)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at java.lang.reflect.Constructor.newInstance(Native Method)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at java.lang.reflect.Constructor.newInstance(Constructor.java:288)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.view.LayoutInflater.createView(LayoutInflater.java:607)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:743)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.view.LayoutInflater.inflate(LayoutInflater.java:482)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at md5fcb90111a512f6bdf8650a2bd92e7238.MainActivity.n_onCreate(Native Method)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at md5fcb90111a512f6bdf8650a2bd92e7238.MainActivity.onCreate(MainActivity.java:31)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.app.Activity.performCreate(Activity.java:6092)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1112)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2468)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2595)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.app.ActivityThread.access$800(ActivityThread.java:178)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.os.Handler.dispatchMessage(Handler.java:111)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.os.Looper.loop(Looper.java:194)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at android.app.ActivityThread.main(ActivityThread.java:5631)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at java.lang.reflect.Method.invoke(Native Method)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at java.lang.reflect.Method.invoke(Method.java:372)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
07-07 14:34:49.820 D/AccessibilityManager(10619):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
07-07 14:34:49.831 W/art     (10619): Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable

All I see from my app is a white screen. And as soon as I change the configuration back to Debug everything is working fine.

Some days ago before I have changed quite a lot on the GUI, everything was working fine. The problem is that I have no idea what the exception message is meaning. What is StateLocked?

As proposed from a comment I add below some more parts of my code:

MainActivity.cs:

[Activity(Label = "enio.TrackR", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
    protected override void OnCreate(Bundle bundle)
    {
        TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;

        base.OnCreate(bundle);

        global::Xamarin.Forms.Forms.Init(this, bundle);
        LoadApplication(new App());
    }
    protected override void OnStart()
    {
        base.OnStart();
        StartService(new Intent(this, typeof(LocationService)));

    }
}

Body:
I believe you need to change

StartService(new Intent(this, typeof(LocationService)));

To

Intent serviceIntent = new Intent(this, typeof(LocationActivity));
context.StartActivity(serviceIntent);


问:
How to push Object element to an array in Vuejs/Javascript
I'm trying to build a small application in VueJs,
Following is my data set:

```<code>data(){
    return {
        pusher: '',
        channel:'',
        notify: [],
        notifications: '',
        notificationsNumber: '',
    }
},
</code>```

where I'm having an axios call in created property of components as:

```<code>axios.get('api/notifications', {headers: getHeader()}).then(response => {
    if(response.status === 200)
    {
        this.notify = response.data.notifications
        this.notificationsNumber = this.notify.length
    }
}).catch(errors => {
    console.log(errors);
})
</code>```

I'm having pusherJs implemented, so I'm having following code:

```<code>this.pusher = new Pusher('xxxxxxxx', {
    cluster: 'ap2',
    encrypted: true
});

var that = this
this.channel = this.pusher.subscribe('stellar_task');
this.channel.bind('company_info', function(data) {
    console.log(data.notification);
    that.notifications = data.notification
});
</code>```

Once the value is being obtained from pusher I want to push this to my array notify as watch property, something like this:

```<code>watch: {
    notifications(newValue) {
        this.notify.push(newValue)
        this.notificationsNumber = this.notificationsNumber + 1
    }
}
</code>```

So the problem is the data format which I'm receiving through pusher is in object form and push function is not getting implemented in this:

Screenshot:

Help me out with this.

答:
I'm making an assumption that response.data.notifications is an Array Like Object.

So all you have to do is:

```<code>this.notify = [...response.data.notifications];
</code>```

Body:
I'm trying to build a small application in VueJs,
Following is my data set:

data(){
    return {
        pusher: '',
        channel:'',
        notify: [],
        notifications: '',
        notificationsNumber: '',
    }
},

where I'm having an axios call in created property of components as:

axios.get('api/notifications', {headers: getHeader()}).then(response => {
    if(response.status === 200)
    {
        this.notify = response.data.notifications
        this.notificationsNumber = this.notify.length
    }
}).catch(errors => {
    console.log(errors);
})

I'm having pusherJs implemented, so I'm having following code:

this.pusher = new Pusher('xxxxxxxx', {
    cluster: 'ap2',
    encrypted: true
});

var that = this
this.channel = this.pusher.subscribe('stellar_task');
this.channel.bind('company_info', function(data) {
    console.log(data.notification);
    that.notifications = data.notification
});

Once the value is being obtained from pusher I want to push this to my array notify as watch property, something like this:

watch: {
    notifications(newValue) {
        this.notify.push(newValue)
        this.notificationsNumber = this.notificationsNumber + 1
    }
}

So the problem is the data format which I'm receiving through pusher is in object form and push function is not getting implemented in this:

Screenshot:

Help me out with this.

Body:
I'm making an assumption that response.data.notifications is an Array Like Object.

So all you have to do is:

this.notify = [...response.data.notifications];


问:
WPF DataGrid, customizing the display with a converter
I have a unique situation. In one class, I have an inner class that acts as pretty much just a "display" class. In the outer class there is a method called GetDisplayObject that returns a type of the inner class.

I'm trying to bind to a datagrid with the outer class, but by using a converter I'd like to get the correct display. This way I won't have to change a bunch of code in our application and just add a few lines in a couple .xaml files.

I made a little test app that pretty much sums up my problem at it's most basic level. Ideally I'd like to solve the problem by using a converter and returning values only as a display, that way when i'm using the SelectedItem I won't have to change a ton of code that is depending on that certain type(In this case would be the DataObject type).

So here is the objects i'm stuck dealing with

```<code>namespace TestApp
{
    public class DataObject
    {
        public class DataObjectDisplay
        {
            public string ObjectDisplay { get; set; }
        }

        // props
        public int Id { get; set; }
        public object Object1 { get; set; }
        public object Object2 { get; set; }

        // method for getting the display
        public DataObjectDisplay GetDisplayObject()
        {
            DataObjectDisplay display = new DataObjectDisplay();

            // logic for determining which object should be displayed
            if(Object1 == null)
            {
                display.ObjectDisplay = "Object1";
            }
            else
            {
                display.ObjectDisplay = "Object2";
            }
            return display;
        }
    }
}
</code>```

Here is the Code Behind of my xaml

```<code>using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;

namespace TestApp
{
public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        this.DataContext = this;
        InitializeComponent();

        this.DataObjectCollection = new ObservableCollection<DataObject>();
        this.DataObjectCollection.Add(new DataObject() { Id = 1, Object1 = "this", Object2 = "that" });
        this.DataObjectCollection.Add(new DataObject() { Id = 1, Object2 = "that" });

        this.SelectedItem = new DataObject();
    }

    private ObservableCollection<DataObject> dataObjectCollection;
    private DataObject selectedItem;

    public ObservableCollection<DataObject> DataObjectCollection
    {
        get { return this.dataObjectCollection; }
        set
        {
            dataObjectCollection = value;
            OnNotifyPropertyChanged("DataObjectCollection");
        }
    }

    public DataObject SelectedItem
    {
        get { return this.selectedItem; }
        set
        {
            selectedItem = value;
            OnNotifyPropertyChanged("SelectedItem");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnNotifyPropertyChanged(string property = "")
    {
        if(PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
    }
}
}
</code>```

Here is the xaml(This is something like what i'd want to do, using the itemtemplate or something similar, and then a converter to call this GetDisplay function)

```<code><Window x:Class="TestApp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:TestApp"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <local:DataObjectToDisplayDataObjectConverter x:Key="ToDisplayConverter"/>
</Window.Resources>
<StackPanel>
    <DataGrid ItemsSource="{Binding DataObjectCollection}" SelectedItem="{Binding SelectedItem}" MinHeight="200">
        <DataGrid.ItemTemplate>
            <DataTemplate>
                <ContentPresenter Content="{Binding Converter={StaticResource ToDisplayConverter}}"/>
            </DataTemplate>
        </DataGrid.ItemTemplate>
    </DataGrid>
</StackPanel>
</Window>
</code>```

And Finally the converter

```<code>using System;
using System.Globalization;
using System.Windows.Data;

namespace TestApp
{
public class DataObjectToDisplayDataObjectConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value != null && value.GetType() == typeof(DataObject))
        {
            DataObject dataObj = (DataObject)value;
            dataObj.GetDisplayObject();
            return dataObj;
        }
        return "Invalid Value";
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
}
</code>```

I am open to suggestions, but this is a small example. In our actual application changing one thing will most likely cascade into a huge ordeal.

答:
Luckily since it was a matter of if one object was null and it's related strings were empty, I was able to use Priority Binding with a converter to return DependencyProperty.UnsetValue and force it to use the next binding. I think this was the best solution for the situation.

So the xaml ended up looking like this.

```<code>    <DataGrid ItemsSource="{Binding DataObjectCollection}" SelectedItem="{Binding SelectedItem}" MinHeight="200">
        <DataGrid.Columns>
            <DataGridTemplateColumn>
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock>
                            <TextBlock.Text>
                                <PriorityBinding>
                                    <Binding Path="Object1" Converter="{StaticResource EmptyStringToDependencyPropertyUnset}"/>
                                    <Binding Path="Object2"/>
                                </PriorityBinding>
                            </TextBlock.Text>
                        </TextBlock>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>
</code>```

And the Converter ended up like this

```<code>    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if(value == null || value as string == string.Empty)
        {
            return DependencyProperty.UnsetValue;
        }
        return value;
    }
</code>```

Body:
I have a unique situation. In one class, I have an inner class that acts as pretty much just a "display" class. In the outer class there is a method called GetDisplayObject that returns a type of the inner class.

I'm trying to bind to a datagrid with the outer class, but by using a converter I'd like to get the correct display. This way I won't have to change a bunch of code in our application and just add a few lines in a couple .xaml files.

I made a little test app that pretty much sums up my problem at it's most basic level. Ideally I'd like to solve the problem by using a converter and returning values only as a display, that way when i'm using the SelectedItem I won't have to change a ton of code that is depending on that certain type(In this case would be the DataObject type).

So here is the objects i'm stuck dealing with

namespace TestApp
{
    public class DataObject
    {
        public class DataObjectDisplay
        {
            public string ObjectDisplay { get; set; }
        }

        // props
        public int Id { get; set; }
        public object Object1 { get; set; }
        public object Object2 { get; set; }

        // method for getting the display
        public DataObjectDisplay GetDisplayObject()
        {
            DataObjectDisplay display = new DataObjectDisplay();

            // logic for determining which object should be displayed
            if(Object1 == null)
            {
                display.ObjectDisplay = "Object1";
            }
            else
            {
                display.ObjectDisplay = "Object2";
            }
            return display;
        }
    }
}

Here is the Code Behind of my xaml

using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;

namespace TestApp
{
public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        this.DataContext = this;
        InitializeComponent();

        this.DataObjectCollection = new ObservableCollection<DataObject>();
        this.DataObjectCollection.Add(new DataObject() { Id = 1, Object1 = "this", Object2 = "that" });
        this.DataObjectCollection.Add(new DataObject() { Id = 1, Object2 = "that" });

        this.SelectedItem = new DataObject();
    }

    private ObservableCollection<DataObject> dataObjectCollection;
    private DataObject selectedItem;

    public ObservableCollection<DataObject> DataObjectCollection
    {
        get { return this.dataObjectCollection; }
        set
        {
            dataObjectCollection = value;
            OnNotifyPropertyChanged("DataObjectCollection");
        }
    }

    public DataObject SelectedItem
    {
        get { return this.selectedItem; }
        set
        {
            selectedItem = value;
            OnNotifyPropertyChanged("SelectedItem");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnNotifyPropertyChanged(string property = "")
    {
        if(PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
    }
}
}

Here is the xaml(This is something like what i'd want to do, using the itemtemplate or something similar, and then a converter to call this GetDisplay function)

<Window x:Class="TestApp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:TestApp"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <local:DataObjectToDisplayDataObjectConverter x:Key="ToDisplayConverter"/>
</Window.Resources>
<StackPanel>
    <DataGrid ItemsSource="{Binding DataObjectCollection}" SelectedItem="{Binding SelectedItem}" MinHeight="200">
        <DataGrid.ItemTemplate>
            <DataTemplate>
                <ContentPresenter Content="{Binding Converter={StaticResource ToDisplayConverter}}"/>
            </DataTemplate>
        </DataGrid.ItemTemplate>
    </DataGrid>
</StackPanel>
</Window>

And Finally the converter

using System;
using System.Globalization;
using System.Windows.Data;

namespace TestApp
{
public class DataObjectToDisplayDataObjectConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value != null && value.GetType() == typeof(DataObject))
        {
            DataObject dataObj = (DataObject)value;
            dataObj.GetDisplayObject();
            return dataObj;
        }
        return "Invalid Value";
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
}

I am open to suggestions, but this is a small example. In our actual application changing one thing will most likely cascade into a huge ordeal.

Body:
Luckily since it was a matter of if one object was null and it's related strings were empty, I was able to use Priority Binding with a converter to return DependencyProperty.UnsetValue and force it to use the next binding. I think this was the best solution for the situation.

So the xaml ended up looking like this.

    <DataGrid ItemsSource="{Binding DataObjectCollection}" SelectedItem="{Binding SelectedItem}" MinHeight="200">
        <DataGrid.Columns>
            <DataGridTemplateColumn>
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock>
                            <TextBlock.Text>
                                <PriorityBinding>
                                    <Binding Path="Object1" Converter="{StaticResource EmptyStringToDependencyPropertyUnset}"/>
                                    <Binding Path="Object2"/>
                                </PriorityBinding>
                            </TextBlock.Text>
                        </TextBlock>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>

And the Converter ended up like this

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if(value == null || value as string == string.Empty)
        {
            return DependencyProperty.UnsetValue;
        }
        return value;
    }