问:
Linux server programming
I got this code from Andy Tanenbaum's book. I am trying to run it. It compiles and waits for connection. But when I type localhost:886, I see no effect either in the browser or the terminal. (It should echo a new connection string as per the code).

```<code>#define     SERVER_PORT         886     /* The port at which the server listens */
#define     BUF_SIZE        64032       /* The size of buffer for request and response */
#define     QUEUE_SIZE      10      /* Block transfer size */

int main (int argc, char* argv[]) {

    int     sock = 0, bnd = 0, lst = 0, fd = 0, sa = 0, bytes = 0, on = 1, conn_count = 0;
    char    buf[BUF_SIZE];
    struct  sockaddr_in channel;            /* IP address holder */

    /* The address structure that binds with the socket */

    memset (&channel, 0, sizeof(channel));

    channel.sin_family      =   AF_INET;
    channel.sin_addr.s_addr     =   htonl (INADDR_ANY);
    channel.sin_port        =   htons (SERVER_PORT);

    /* Parital opening of the socket, while waiting for connection */

    sock                =   socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); /* Creates a new socket */
    if (sock < 0)
        printf ("Partial opening of the socket failed! Error: %d", sock);

    setsockopt (sock, SOL_SOCKET, SO_REUSEADDR, (char *) &on, sizeof(on));

    bnd             =   bind (sock, (struct sockaddr *) &channel, sizeof(channel));
    if (bnd < 0)
        printf ("Binding failure! Error: %d", bnd);

    lst             =   listen (sock, QUEUE_SIZE);
    if (lst < 0)
        printf ("Unable to listen on the socket! Error: %d", lst);

    /* The socket has been set-up. Wait for the connection and process it. */

    while (1) {

        conn_count      +=  1;
        printf ("Received connection: %d", conn_count);
        sa          =   accept (sock, 0, 0);
        if (sa < 0)
            puts ("Unable to accept the socket opened for connection.");

        read (sa, buf, BUF_SIZE);

        puts (buf);     /* Output the string to the screen */

        close (sa);
    }
}
</code>```

答:
Are you running this as sudo/root?  Your bind() might be failing because it is using privileged port.

[update from comment:]

Privileged ports are all ports below 1024.

Title: Linux server programming

Body:
I got this code from Andy Tanenbaum's book. I am trying to run it. It compiles and waits for connection. But when I type localhost:886, I see no effect either in the browser or the terminal. (It should echo a new connection string as per the code).

#define     SERVER_PORT         886     /* The port at which the server listens */
#define     BUF_SIZE        64032       /* The size of buffer for request and response */
#define     QUEUE_SIZE      10      /* Block transfer size */

int main (int argc, char* argv[]) {

    int     sock = 0, bnd = 0, lst = 0, fd = 0, sa = 0, bytes = 0, on = 1, conn_count = 0;
    char    buf[BUF_SIZE];
    struct  sockaddr_in channel;            /* IP address holder */

    /* The address structure that binds with the socket */

    memset (&channel, 0, sizeof(channel));

    channel.sin_family      =   AF_INET;
    channel.sin_addr.s_addr     =   htonl (INADDR_ANY);
    channel.sin_port        =   htons (SERVER_PORT);

    /* Parital opening of the socket, while waiting for connection */

    sock                =   socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); /* Creates a new socket */
    if (sock < 0)
        printf ("Partial opening of the socket failed! Error: %d", sock);

    setsockopt (sock, SOL_SOCKET, SO_REUSEADDR, (char *) &on, sizeof(on));

    bnd             =   bind (sock, (struct sockaddr *) &channel, sizeof(channel));
    if (bnd < 0)
        printf ("Binding failure! Error: %d", bnd);

    lst             =   listen (sock, QUEUE_SIZE);
    if (lst < 0)
        printf ("Unable to listen on the socket! Error: %d", lst);

    /* The socket has been set-up. Wait for the connection and process it. */

    while (1) {

        conn_count      +=  1;
        printf ("Received connection: %d", conn_count);
        sa          =   accept (sock, 0, 0);
        if (sa < 0)
            puts ("Unable to accept the socket opened for connection.");

        read (sa, buf, BUF_SIZE);

        puts (buf);     /* Output the string to the screen */

        close (sa);
    }
}


来源: stackexchange

问:
GraphQL-Ruby : When executing a mutation, get error Variable $...... is declared by ....(mutation).... but not used
I'm cutting my teeth on GraphQL ruby here and this seems like it should be basic but the docs make this very difficult to grok. Where did I go wrong here?

My goal is simply to make a GraphQL mutation in my Ruby app.

app/graphql/types/mutation_type.rb

```<code>module Types
  class MutationType < Types::BaseObject

    field :name, String

    field :create_trip, mutation: Mutations::CreateTrip
  end
end
</code>```

Here's the mutation in
app/graphql/mutations/create_trip.rb

```<code>class Mutations::CreateTrip < Mutations::BaseMutation
  null true
  argument :leavingFrom, String

  field :name, String

  type Types::TripType

  def resolve(leavingFrom: )
    new_trip = Trip.create(leavingFrom: leavingFrom)

    # this doesn't really do anything--- this is proof-of-concept code only
    if new_trip.save
      # Successful creation, return the created object with no errors
      {
        trip: trip,
        errors: [],
      }
    else
      # Failed save, return the errors to the client
      {
        trip: nil,
        errors: trip.errors.full_messages
      }
    end
  end
end
</code>```

the app/graphql/types/trip_type.rb is

```<code># frozen_string_literal: true

module Types
  class TripType < Types::BaseObject
    field :id, ID, null: false
    field :traveling_party_id, Integer
    field :name, String
  end
end
</code>```

When I run this mutation:

```<code>mutation CreateTrip($leavingFrom: String) {
  name
}
</code>```

(with some data for leavingFrom)

I get this unexpected result: "Variable $leavingFrom is declared by CreateTrip but not used"

Expected result: My mutation calls through to the resolve on my GraphQL mutation.

I think the problem is in my query, because it does not look like the Ruby code ever called. Contrary to the message itself, the  leavingFrom is indeed used by the mutation in the resolve body.

答:
The answer given here is totally right.

On a more explanatory way, when you are executing a query or a mutation (operation type), you can name your operation or not.

```<code><operation_type> <operation_name(optional)> (<variables>) {
  # your query or mutation
}

# without naming it
mutation($input: String) {
  # your mutation
}

# naming it
mutation MyMutation($input: String) {
  # your mutation
}
</code>```

Also I personally always use camelCase to name my mutations/queries and have a different name between mutation/query and operation name, using your example, I would do something like this:

```<code>mutation CreateTripMutation($leavingFrom: String) {
  createTrip(leavingFrom: $leavingFrom) {
    name
  },
}
</code>```

Hope to have helped you

ContentLicense: CC BY-SA 4.0

Body:
I'm cutting my teeth on GraphQL ruby here and this seems like it should be basic but the docs make this very difficult to grok. Where did I go wrong here?

My goal is simply to make a GraphQL mutation in my Ruby app.

app/graphql/types/mutation_type.rb

module Types
  class MutationType < Types::BaseObject

    field :name, String

    field :create_trip, mutation: Mutations::CreateTrip
  end
end

Here's the mutation in
app/graphql/mutations/create_trip.rb

class Mutations::CreateTrip < Mutations::BaseMutation
  null true
  argument :leavingFrom, String

  field :name, String

  type Types::TripType

  def resolve(leavingFrom: )
    new_trip = Trip.create(leavingFrom: leavingFrom)

    # this doesn't really do anything--- this is proof-of-concept code only
    if new_trip.save
      # Successful creation, return the created object with no errors
      {
        trip: trip,
        errors: [],
      }
    else
      # Failed save, return the errors to the client
      {
        trip: nil,
        errors: trip.errors.full_messages
      }
    end
  end
end

the app/graphql/types/trip_type.rb is

# frozen_string_literal: true

module Types
  class TripType < Types::BaseObject
    field :id, ID, null: false
    field :traveling_party_id, Integer
    field :name, String
  end
end

When I run this mutation:

mutation CreateTrip($leavingFrom: String) {
  name
}

(with some data for leavingFrom)

I get this unexpected result: "Variable $leavingFrom is declared by CreateTrip but not used"

Expected result: My mutation calls through to the resolve on my GraphQL mutation.

I think the problem is in my query, because it does not look like the Ruby code ever called. Contrary to the message itself, the  leavingFrom is indeed used by the mutation in the resolve body.

Body:
The answer given here is totally right.

On a more explanatory way, when you are executing a query or a mutation (operation type), you can name your operation or not.

<operation_type> <operation_name(optional)> (<variables>) {
  # your query or mutation
}

# without naming it
mutation($input: String) {
  # your mutation
}

# naming it
mutation MyMutation($input: String) {
  # your mutation
}

Also I personally always use camelCase to name my mutations/queries and have a different name between mutation/query and operation name, using your example, I would do something like this:

mutation CreateTripMutation($leavingFrom: String) {
  createTrip(leavingFrom: $leavingFrom) {
    name
  },
}

Hope to have helped you


问:
Table View Cell has no Initialiser
I am trying to display table view cell property into different table view cell when button I clicked . I am using story board . I added the Horizontal and vertical stack to contains the image and label properties . I want to display this property into another table view cell when user clicked the show button . In cellFor row function i defined the button action property . I am getting following error .Class 'DetailsViewCell' has no initializers. Cannot use instance member 'mc' within property initializer; property initializers run before 'self' is available

Here is the screenshot of the both view controller .

Here is the code .

```<code> func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//        guard let cell = tableView.dequeueReusableCell(withIdentifier: MovieCell.identifier, for: indexPath) as? MovieCell
//        else { return UITableViewCell() }

        let cell = tableView.dequeueReusableCell(withIdentifier: MovieViewCell.identifier, for: indexPath) as! MovieViewCell

        cell.showButton.tag = indexPath.row
        cell.showButton.addTarget(self, action: Selector("movieDetails"), for: .touchUpInside)

        let row = indexPath.row
        let title = presenter.getTitle(by: row)
        let overview = presenter.getOverview(by: row)
        let data = presenter.getImageData(by: row)
        cell.configureCell(title: title, overview: overview, data: data)
        return cell
    }
}
</code>```

Here is the code in identifier class with table view cell.

```<code>class MovieViewCell: UITableViewCell {

    static let identifier = "MovieViewCell"

    @IBOutlet weak var mainStackView: UIStackView!

    @IBOutlet weak var movieImage: UIImageView!

    @IBOutlet weak var movieTtile: UILabel!

    @IBOutlet weak var movieOverview: UILabel!

    @IBOutlet weak var showButton: UIButton!

    @IBAction func movieDetails(_ sender: UIButton) {

        var  dc : DetailsViewCell
        movieTtile = dc.movieTitle
        movieOverview = dc.movieOverview
        movieImage = dc.movieImage

    }

    func configureCell(title: String?, overview: String?, data: Data?) {

        movieTtile.text = title
        movieOverview.text = overview

        if let imageData = data{
            movieImage.image = UIImage(data: imageData)
        }
    }
}
</code>```

Here is the code for Details view cell.

```<code>class DetailsViewCell: UITableViewCell {

    @IBOutlet weak var movieTitle: UILabel!

    @IBOutlet weak var movieOverview: UILabel!

    @IBOutlet weak var movieImage: UIImageView!

         var mc : MovieViewCell

         movieTitle = mc.movieTtile
         movieOverview = mc.movieOverview
         movieImage = mc.movieImage

}

</code>```

答:
```<code>import UIKit

var loginData = ["", "", ""]

class LoginDataCell: UITableViewCell, UITextFieldDelegate {

    @IBOutlet weak var txtLoginData: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    func textFieldDidEndEditing(_ textField: UITextField) {
    if textField.tag == 0 {
       loginData[0] = textField.text
    } else if textField.tag == 1 {
      loginData[1] = textField.text
    } else if textField.tag == 2 {
      loginData[2] = textField.text
    }
    }

}
</code>```

Title: Table View Cell has no Initialiser

Body:
I am trying to display table view cell property into different table view cell when button I clicked . I am using story board . I added the Horizontal and vertical stack to contains the image and label properties . I want to display this property into another table view cell when user clicked the show button . In cellFor row function i defined the button action property . I am getting following error .Class 'DetailsViewCell' has no initializers. Cannot use instance member 'mc' within property initializer; property initializers run before 'self' is available

Here is the screenshot of the both view controller .

Here is the code .

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//        guard let cell = tableView.dequeueReusableCell(withIdentifier: MovieCell.identifier, for: indexPath) as? MovieCell
//        else { return UITableViewCell() }

        let cell = tableView.dequeueReusableCell(withIdentifier: MovieViewCell.identifier, for: indexPath) as! MovieViewCell

        cell.showButton.tag = indexPath.row
        cell.showButton.addTarget(self, action: Selector("movieDetails"), for: .touchUpInside)

        let row = indexPath.row
        let title = presenter.getTitle(by: row)
        let overview = presenter.getOverview(by: row)
        let data = presenter.getImageData(by: row)
        cell.configureCell(title: title, overview: overview, data: data)
        return cell
    }
}

Here is the code in identifier class with table view cell.

class MovieViewCell: UITableViewCell {

    static let identifier = "MovieViewCell"

    @IBOutlet weak var mainStackView: UIStackView!

    @IBOutlet weak var movieImage: UIImageView!

    @IBOutlet weak var movieTtile: UILabel!

    @IBOutlet weak var movieOverview: UILabel!

    @IBOutlet weak var showButton: UIButton!

    @IBAction func movieDetails(_ sender: UIButton) {

        var  dc : DetailsViewCell
        movieTtile = dc.movieTitle
        movieOverview = dc.movieOverview
        movieImage = dc.movieImage

    }

    func configureCell(title: String?, overview: String?, data: Data?) {

        movieTtile.text = title
        movieOverview.text = overview

        if let imageData = data{
            movieImage.image = UIImage(data: imageData)
        }
    }
}

Here is the code for Details view cell.

class DetailsViewCell: UITableViewCell {

    @IBOutlet weak var movieTitle: UILabel!

    @IBOutlet weak var movieOverview: UILabel!

    @IBOutlet weak var movieImage: UIImageView!

         var mc : MovieViewCell

         movieTitle = mc.movieTtile
         movieOverview = mc.movieOverview
         movieImage = mc.movieImage

}


问:
Need help isolating results from xhr request
When I run the code below, it's giving me a lot of information I don't want.  I only want to capture the data circled starting with 4. Does anyone know how to isolate the data in the request to get rid of everything but what is circled?  Also, if anyone knows how to bring the results to a csv or xlsx file, that would be even better.

Working code:

```<code>   import requests

url = "https://www.stockrover.com/stock_infos/grid?_dc=1644769629231"
</code>```

data = {
"ticker": 4,
"rank": "5",
}

```<code>payload = "state=%7B%22sortInfo%22%3A%7B%7D%2C%22columns%22%3A%5B77%2C32%2C498%2C500%2C31%2C27%2C499%2C30%2C578%2C28%2C29%2C544%2C181%2C185%2C186%5D%2C%22view%22%3A281%2C%22priorPrimaryColumn%22%3A170%2C%22filterData%22%3A%5B%5D%2C%22name%22%3A%22New%201%22%2C%22cType%22%3A%22Screener%22%2C%22cNode%22%3A%22s_39%22%2C%22cIsFolder%22%3Afalse%2C%22gridSelection%22%3A%22BTU%22%2C%22lastActive%22%3A1396898415%2C%22primaryColumn%22%3A76%2C%22folderDisabledParams%22%3A%7B%22filterData%22%3A%5B%5D%7D%2C%22mainGridDateRange%22%3A%22ytd%22%2C%22groupState%22%3Anull%2C%22moversGridDateRange%22%3A%221_day%22%2C%22peersGridDateRange%22%3A%221_day%22%2C%22lastGridSelections%22%3A%5B%22BTU%22%5D%2C%22lastQuantNode%22%3A%5B%5D%2C%22includeQuotesInTable%22%3Afalse%2C%22includeAllQuotesLastValue%22%3Afalse%2C%22markets%22%3A%7B%22panel%22%3A%22summary%22%7D%2C%22researchPanel%22%3A%22tablePanel%22%2C%22recentSearchTickers%22%3A%5B%22SPY%22%2C%22AMZN%22%2C%22AAPL%22%2C%22s_32%22%2C%22%5ENDX%22%2C%22AXP%22%2C%22XOM%22%2C%22AFL%22%2C%22%5EDJX%22%2C%22AIT%22%2C%22ADVC%22%5D%2C%22quotesBoxTickers%22%3A%5B%22AMZN%22%2C%22AAPL%22%2C%22SPY%22%5D%2C%22checkedQuotesBoxTickers%22%3A%5B%22AMZN%22%2C%22AAPL%22%2C%22SPY%22%5D%2C%22dashboard%22%3A%7B%22buttonRef%22%3A%22272%22%7D%2C%22tickerSelectedFeeds%22%3A%5B%22Benzinga%20News%22%2C%22Yahoo%20News%22%5D%2C%22marketSelectedFeeds%22%3A%5B%22Google%20News%22%2C%22Stock%20Market%20News%20-%20Investing.com%22%5D%2C%22bondsSelectedFeeds%22%3A%5B%22Bonds%20Strategy%20-%20Investing.com%22%5D%2C%22commoditiesSelectedFeeds%22%3A%5B%22Commodities%20%26%20Futures%20News%20-%20Investing.com%22%2C%22Commodities%20Fundamental%20Analysis%20-%20Investing.com%22%2C%22Commodities%20Strategy%20Analysis%20-%20Investing.com%22%5D%2C%22stocksSelectedFeeds%22%3A%5B%22CNNMoney%20News%22%2C%22Google%20News%22%2C%22Seeking%20Alpha%20Top%20Stories%22%5D%2C%22etfsSelectedFeeds%22%3A%5B%22Economy%20News%20-%20Investing.com%22%2C%22ETF%20Analysis%20-%20Investing.com%22%2C%22Investing%20Ideas%20-%20Investing.com%22%5D%2C%22topPanel%22%3A%22researchPanel%22%2C%22maxRecordsNode%22%3Afalse%2C%22version%22%3A7%2C%22lastGridSelectionsRaw%22%3A%5B%22BTU%22%5D%2C%22lastSelectionScreeners%22%3A%22s_39%22%2C%22quotesDisabled%22%3Atrue%2C%22lastSelectionPortfolios%22%3A%22p_2%22%2C%22comparisonPanels%22%3A%7B%22Portfolio%22%3A%22p_2%22%2C%22Index%22%3A%22%5EDJX%22%2C%22Watchlist%22%3A%22Watchlists%22%2C%22Screener%22%3A%22s_39%22%7D%2C%22lastSelectionWatchlists%22%3A%22w_26%22%2C%22indicesSelectedFeeds%22%3A%5B%22Google%20News%22%2C%22Yahoo%20News%22%5D%2C%22newsActive%22%3A%22tickerNews%22%2C%22recentSearchMetrics%22%3A%5B%22Price%22%2C%22EPS%22%2C%22Sales%22%5D%2C%22editPanel%22%3A%22positionsPanel%22%2C%22newsType%22%3A%22marketNews%22%2C%22tableColumns%22%3A%5B%22ticker%22%2C%22rank%22%2C%22score_rank%22%2C%22filter_score%22%2C%22company%22%2C%22cash%22%2C%22currentassets%22%2C%22netppe%22%2C%22intangibles%22%2C%22totalassets%22%2C%22currentliabilities%22%2C%22longtermdebt%22%2C%22totaldebt%22%2C%22totalliabilities%22%2C%22equity%22%2C%22tangiblebookvalue%22%2C%22cash_short_term_p%22%2C%22net_ppe_p%22%2C%22intangibles_p%22%5D%2C%22last_save%22%3A1644769379%2C%22panels%22%3A%7B%22collapsed%22%3A%7B%22chp%22%3Atrue%2C%22ip%22%3Atrue%2C%22mp%22%3Afalse%2C%22qp%22%3Afalse%2C%22conp%22%3Atrue%2C%22fsp%22%3Afalse%7D%2C%22viewportWidth%22%3A%221920%22%2C%22viewportHeight%22%3A%221069%22%2C%22chartPanelHeight%22%3A483%2C%22controlPanelWidth%22%3A296%2C%22insightPanelWidth%22%3A%22485%22%2C%22quoteBoxHeight%22%3A200%2C%22navigationPanelWidth%22%3A277%7D%7D&updateMarket=true&page=1&start=0&limit=250"
headers = {
  'authority': 'www.stockrover.com',
  'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="98", "Google Chrome";v="98"',
  'x-csrf-token': '7yR4pfI0kAArtjJak535+NJrpB0L212PAbXCg0kbyE4SyjFaQ73sMHJLiqAkPb5nGzfC8KvAa3kTADLAEQXyOQ==',
  'sec-ch-ua-mobile': '?0',
  'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36',
  'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
  'accept': 'application/json',
  'x-requested-with': 'XMLHttpRequest',
  'sec-ch-ua-platform': '"Windows"',
  'origin': 'https://www.stockrover.com',
  'sec-fetch-site': 'same-origin',
  'sec-fetch-mode': 'cors',
  'sec-fetch-dest': 'empty',
  'referer': 'https://www.stockrover.com/research/table/281/s_39/BTU',
  'accept-language': 'en-US,en;q=0.9',
  'cookie': 'remember_me_pref=0; user_name=test11964; plan=3; premiumBraintreeKey=MIIBCgKCAQEAzM4LJfrNnBOgRFB1dDJkmqTFCWT2Y%2BksOydD8xDH4R033WUzxbffMZb%2B3dqEyQvOVjLcwFIHByDc4Xwej7enas2E%2FVRyh7Cvyadn7M5zQeRyLcI9Ys5KCozMwxJPc0x76FlXPwiAo1Qlz3RcLb9wGHBag2R51FuTie%2BhVDCgzWajqDCREzRhi%2Fqlt3D%2FxXNo%2FiwJlpOUr%2Fx1QnkkILxgKlq1dD7KJ767O5ojYKXsO%2BV2Bfu7sSD3djsOxQJ1%2FRbaDm2E96EDkWhhOeOpPndQ6IuSl4NmnJg%2Fcq6f8csW8M3Ys%2BMZPFkdxPC4%2FfRM1XC9o76PjpVNBIO%2ByJEELKZedwIDAQAB; lr=1644769628; _Ruby2_session=Q1drcmlhazYvUFZLd0NydnRXUGpoUzArZDlxYWRCcW9sRUx5VDBydWVWRHdGWDZlMnlESURzbldwbFV1L0drbUlKaWt5MXRtaS9iR0ZYZEpPVHQ1N25qRnR1d3FrY0tzQW1qQm9CdTZ3MSs0d2c3MlpuMjRiQWhCOHI1cGNWekZ4cUdJd0ZFcGtpeng3MFlqZjFDUW9RYmpFMU9DeGdGMVZKR1EwMjVhSE9yVHl4VXFtQm9aYVBtNHF5d0pwMjJ1aVlNMUVRUzdnVFZWZ1AxQkY5Q0p6a2RKay9QL05tOWk4cHZiSERtaGRxeTlxTWZnV3Q0cjdwR3RndUtmeUp3QThhMnJaV2dGZjlPUUtjcGRidDhiajRxK2g0RUZTMWNZUDBaeGNCcUVxSDJ1QnZVRlRkWk9tUExJNWN3TDN5T1BQcmhVVGsycStVTzJRaUwvSkk2TnNVZldTOGU3Tm5wQ3RUMy9nazFqbzdrUWtvYzRwQWRpV3dnTVB3YzhodFV2U0FRR3VKdllMY01NZmdOdGtmOEJ4UT09LS1nTXBrYldhQ0pEeWJ3ak9qQjcrTGV3PT0%3D--1439f36a7f9362aee4b5b666747a2d63d72e81bd'
}

response = requests.request("POST", url, headers=headers, data=payload)
print(response.json())
</code>```

Body:
When I run the code below, it's giving me a lot of information I don't want.  I only want to capture the data circled starting with 4. Does anyone know how to isolate the data in the request to get rid of everything but what is circled?  Also, if anyone knows how to bring the results to a csv or xlsx file, that would be even better.

Working code:

   import requests

url = "https://www.stockrover.com/stock_infos/grid?_dc=1644769629231"

data = {
"ticker": 4,
"rank": "5",
}

payload = "state=%7B%22sortInfo%22%3A%7B%7D%2C%22columns%22%3A%5B77%2C32%2C498%2C500%2C31%2C27%2C499%2C30%2C578%2C28%2C29%2C544%2C181%2C185%2C186%5D%2C%22view%22%3A281%2C%22priorPrimaryColumn%22%3A170%2C%22filterData%22%3A%5B%5D%2C%22name%22%3A%22New%201%22%2C%22cType%22%3A%22Screener%22%2C%22cNode%22%3A%22s_39%22%2C%22cIsFolder%22%3Afalse%2C%22gridSelection%22%3A%22BTU%22%2C%22lastActive%22%3A1396898415%2C%22primaryColumn%22%3A76%2C%22folderDisabledParams%22%3A%7B%22filterData%22%3A%5B%5D%7D%2C%22mainGridDateRange%22%3A%22ytd%22%2C%22groupState%22%3Anull%2C%22moversGridDateRange%22%3A%221_day%22%2C%22peersGridDateRange%22%3A%221_day%22%2C%22lastGridSelections%22%3A%5B%22BTU%22%5D%2C%22lastQuantNode%22%3A%5B%5D%2C%22includeQuotesInTable%22%3Afalse%2C%22includeAllQuotesLastValue%22%3Afalse%2C%22markets%22%3A%7B%22panel%22%3A%22summary%22%7D%2C%22researchPanel%22%3A%22tablePanel%22%2C%22recentSearchTickers%22%3A%5B%22SPY%22%2C%22AMZN%22%2C%22AAPL%22%2C%22s_32%22%2C%22%5ENDX%22%2C%22AXP%22%2C%22XOM%22%2C%22AFL%22%2C%22%5EDJX%22%2C%22AIT%22%2C%22ADVC%22%5D%2C%22quotesBoxTickers%22%3A%5B%22AMZN%22%2C%22AAPL%22%2C%22SPY%22%5D%2C%22checkedQuotesBoxTickers%22%3A%5B%22AMZN%22%2C%22AAPL%22%2C%22SPY%22%5D%2C%22dashboard%22%3A%7B%22buttonRef%22%3A%22272%22%7D%2C%22tickerSelectedFeeds%22%3A%5B%22Benzinga%20News%22%2C%22Yahoo%20News%22%5D%2C%22marketSelectedFeeds%22%3A%5B%22Google%20News%22%2C%22Stock%20Market%20News%20-%20Investing.com%22%5D%2C%22bondsSelectedFeeds%22%3A%5B%22Bonds%20Strategy%20-%20Investing.com%22%5D%2C%22commoditiesSelectedFeeds%22%3A%5B%22Commodities%20%26%20Futures%20News%20-%20Investing.com%22%2C%22Commodities%20Fundamental%20Analysis%20-%20Investing.com%22%2C%22Commodities%20Strategy%20Analysis%20-%20Investing.com%22%5D%2C%22stocksSelectedFeeds%22%3A%5B%22CNNMoney%20News%22%2C%22Google%20News%22%2C%22Seeking%20Alpha%20Top%20Stories%22%5D%2C%22etfsSelectedFeeds%22%3A%5B%22Economy%20News%20-%20Investing.com%22%2C%22ETF%20Analysis%20-%20Investing.com%22%2C%22Investing%20Ideas%20-%20Investing.com%22%5D%2C%22topPanel%22%3A%22researchPanel%22%2C%22maxRecordsNode%22%3Afalse%2C%22version%22%3A7%2C%22lastGridSelectionsRaw%22%3A%5B%22BTU%22%5D%2C%22lastSelectionScreeners%22%3A%22s_39%22%2C%22quotesDisabled%22%3Atrue%2C%22lastSelectionPortfolios%22%3A%22p_2%22%2C%22comparisonPanels%22%3A%7B%22Portfolio%22%3A%22p_2%22%2C%22Index%22%3A%22%5EDJX%22%2C%22Watchlist%22%3A%22Watchlists%22%2C%22Screener%22%3A%22s_39%22%7D%2C%22lastSelectionWatchlists%22%3A%22w_26%22%2C%22indicesSelectedFeeds%22%3A%5B%22Google%20News%22%2C%22Yahoo%20News%22%5D%2C%22newsActive%22%3A%22tickerNews%22%2C%22recentSearchMetrics%22%3A%5B%22Price%22%2C%22EPS%22%2C%22Sales%22%5D%2C%22editPanel%22%3A%22positionsPanel%22%2C%22newsType%22%3A%22marketNews%22%2C%22tableColumns%22%3A%5B%22ticker%22%2C%22rank%22%2C%22score_rank%22%2C%22filter_score%22%2C%22company%22%2C%22cash%22%2C%22currentassets%22%2C%22netppe%22%2C%22intangibles%22%2C%22totalassets%22%2C%22currentliabilities%22%2C%22longtermdebt%22%2C%22totaldebt%22%2C%22totalliabilities%22%2C%22equity%22%2C%22tangiblebookvalue%22%2C%22cash_short_term_p%22%2C%22net_ppe_p%22%2C%22intangibles_p%22%5D%2C%22last_save%22%3A1644769379%2C%22panels%22%3A%7B%22collapsed%22%3A%7B%22chp%22%3Atrue%2C%22ip%22%3Atrue%2C%22mp%22%3Afalse%2C%22qp%22%3Afalse%2C%22conp%22%3Atrue%2C%22fsp%22%3Afalse%7D%2C%22viewportWidth%22%3A%221920%22%2C%22viewportHeight%22%3A%221069%22%2C%22chartPanelHeight%22%3A483%2C%22controlPanelWidth%22%3A296%2C%22insightPanelWidth%22%3A%22485%22%2C%22quoteBoxHeight%22%3A200%2C%22navigationPanelWidth%22%3A277%7D%7D&updateMarket=true&page=1&start=0&limit=250"
headers = {
  'authority': 'www.stockrover.com',
  'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="98", "Google Chrome";v="98"',
  'x-csrf-token': '7yR4pfI0kAArtjJak535+NJrpB0L212PAbXCg0kbyE4SyjFaQ73sMHJLiqAkPb5nGzfC8KvAa3kTADLAEQXyOQ==',
  'sec-ch-ua-mobile': '?0',
  'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36',
  'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
  'accept': 'application/json',
  'x-requested-with': 'XMLHttpRequest',
  'sec-ch-ua-platform': '"Windows"',
  'origin': 'https://www.stockrover.com',
  'sec-fetch-site': 'same-origin',
  'sec-fetch-mode': 'cors',
  'sec-fetch-dest': 'empty',
  'referer': 'https://www.stockrover.com/research/table/281/s_39/BTU',
  'accept-language': 'en-US,en;q=0.9',
  'cookie': 'remember_me_pref=0; user_name=test11964; plan=3; premiumBraintreeKey=MIIBCgKCAQEAzM4LJfrNnBOgRFB1dDJkmqTFCWT2Y%2BksOydD8xDH4R033WUzxbffMZb%2B3dqEyQvOVjLcwFIHByDc4Xwej7enas2E%2FVRyh7Cvyadn7M5zQeRyLcI9Ys5KCozMwxJPc0x76FlXPwiAo1Qlz3RcLb9wGHBag2R51FuTie%2BhVDCgzWajqDCREzRhi%2Fqlt3D%2FxXNo%2FiwJlpOUr%2Fx1QnkkILxgKlq1dD7KJ767O5ojYKXsO%2BV2Bfu7sSD3djsOxQJ1%2FRbaDm2E96EDkWhhOeOpPndQ6IuSl4NmnJg%2Fcq6f8csW8M3Ys%2BMZPFkdxPC4%2FfRM1XC9o76PjpVNBIO%2ByJEELKZedwIDAQAB; lr=1644769628; _Ruby2_session=Q1drcmlhazYvUFZLd0NydnRXUGpoUzArZDlxYWRCcW9sRUx5VDBydWVWRHdGWDZlMnlESURzbldwbFV1L0drbUlKaWt5MXRtaS9iR0ZYZEpPVHQ1N25qRnR1d3FrY0tzQW1qQm9CdTZ3MSs0d2c3MlpuMjRiQWhCOHI1cGNWekZ4cUdJd0ZFcGtpeng3MFlqZjFDUW9RYmpFMU9DeGdGMVZKR1EwMjVhSE9yVHl4VXFtQm9aYVBtNHF5d0pwMjJ1aVlNMUVRUzdnVFZWZ1AxQkY5Q0p6a2RKay9QL05tOWk4cHZiSERtaGRxeTlxTWZnV3Q0cjdwR3RndUtmeUp3QThhMnJaV2dGZjlPUUtjcGRidDhiajRxK2g0RUZTMWNZUDBaeGNCcUVxSDJ1QnZVRlRkWk9tUExJNWN3TDN5T1BQcmhVVGsycStVTzJRaUwvSkk2TnNVZldTOGU3Tm5wQ3RUMy9nazFqbzdrUWtvYzRwQWRpV3dnTVB3YzhodFV2U0FRR3VKdllMY01NZmdOdGtmOEJ4UT09LS1nTXBrYldhQ0pEeWJ3ak9qQjcrTGV3PT0%3D--1439f36a7f9362aee4b5b666747a2d63d72e81bd'
}

response = requests.request("POST", url, headers=headers, data=payload)
print(response.json())


问:
Why does my SwiftUI view not get onChange updates from a @Binding member of a @StateObject?
Given the setup I've outlined below, I'm trying to determine why ChildView's .onChange(of: _) is not receiving updates.

import SwiftUI

struct SomeItem: Equatable {
    var doubleValue: Double
}

struct ParentView: View {
    @State
    private var someItem = SomeItem(doubleValue: 45)

    var body: some View {
        Color.black
            .overlay(alignment: .top) {
                Text(someItem.doubleValue.description)
                    .font(.system(size: 50))
                    .foregroundColor(.white)
            }
            .onTapGesture { someItem.doubleValue += 10.0 }
            .overlay { ChildView(someItem: $someItem) }
    }
}

struct ChildView: View {
    @StateObject
    var viewModel: ViewModel

    init(someItem: Binding<SomeItem>) {
        _viewModel = StateObject(wrappedValue: ViewModel(someItem: someItem))
    }

    var body: some View {
        Rectangle()
            .fill(Color.red)
            .frame(width: 50, height: 70, alignment: .center)
            .rotationEffect(
                Angle(degrees: viewModel.someItem.doubleValue)
            )
            .onTapGesture { viewModel.changeItem() }
            .onChange(of: viewModel.someItem) { _ in
                print("Change Detected", viewModel.someItem.doubleValue)
            }
    }
}

@MainActor
final class ViewModel: ObservableObject {
    @Binding
    var someItem: SomeItem

    public init(someItem: Binding<SomeItem>) {
        self._someItem = someItem
    }

    public func changeItem() {
        self.someItem = SomeItem(doubleValue: .zero)
    }
}
```

Interestingly, if I make the following changes in ChildView, I get the behavior I want.

Change @StateObject to @ObservedObject

Change _viewModel = StateObject(wrappedValue: ViewModel(someItem: someItem)) to viewModel = ViewModel(someItem: someItem)

From what I understand, it is improper for ChildView's viewModel to be @ObservedObject because ChildView owns viewModel but @ObservedObject gives me the behavior I need whereas @StateObject does not.

Here are the differences I'm paying attention to:

When using @ObservedObject, I can tap the black area and see the changes applied to both the white text and red rectangle. I can also tap the red rectangle and see the changes observed in ParentView through the white text.

When using @StateObject, I can tap the black area and see the changes applied to both the white text and red rectangle. The problem lies in that I can tap the red rectangle here and see the changes reflected in ParentView but ChildView doesn't recognize the change (rotation does not change and "Change Detected" is not printed).

Is @ObservedObject actually correct since ViewModel contains a @Binding to a @State created in ParentView?

答:
Normally, I would not write such a convoluted solution to a problem, but it sounds like from your comments on another answer there are certain architectural issues that you are required to conform to.

The general issue with your initial approach is that onChange is only going to run when the view has a render triggered. Generally, that happens because some a passed-in property has changed, @State has changed, or a publisher on an ObservableObject has changed. In this case, none of those are true -- you have a Binding on your ObservableObject, but nothing that triggers the view to re-render. If Bindings provided a publisher, it would be easy to hook into that value, but since they do not, it seems like the logical approach is to store the state in the parent view in a way in which we can watch a @Published value.

Again, this is not necessarily the route I would take, but hopefully it fits your requirements:

```<code>struct SomeItem: Equatable {
    var doubleValue: Double
}

class Store : ObservableObject {
    @Published var someItem = SomeItem(doubleValue: 45)
}

struct ParentView: View {
    @StateObject private var store = Store()

    var body: some View {
        Color.black
            .overlay(alignment: .top) {
                Text(store.someItem.doubleValue.description)
                    .font(.system(size: 50))
                    .foregroundColor(.white)
            }
            .onTapGesture { store.someItem.doubleValue += 10.0 }
            .overlay { ChildView(store: store) }
    }
}

struct ChildView: View {
    @StateObject private var viewModel: ViewModel

    init(store: Store) {
        _viewModel = StateObject(wrappedValue: ViewModel(store: store))
    }

    var body: some View {
        Rectangle()
            .fill(Color.red)
            .frame(width: 50, height: 70, alignment: .center)
            .rotationEffect(
                Angle(degrees: viewModel.store.someItem.doubleValue)
            )
            .onTapGesture { viewModel.changeItem() }
            .onChange(of: viewModel.store.someItem.doubleValue) { _ in
                print("Change Detected", viewModel.store.someItem.doubleValue)
            }
    }
}

@MainActor
final class ViewModel: ObservableObject {
    var store: Store

    var cancellable : AnyCancellable?

    public init(store: Store) {
        self.store = store
        cancellable = store.$someItem.sink { [weak self] _ in
            self?.objectWillChange.send()
        }
    }

    public func changeItem() {
        store.someItem = SomeItem(doubleValue: .zero)
    }
}

</code>```

Body:
Given the setup I've outlined below, I'm trying to determine why ChildView's .onChange(of: _) is not receiving updates.

import SwiftUI

struct SomeItem: Equatable {
    var doubleValue: Double
}

struct ParentView: View {
    @State
    private var someItem = SomeItem(doubleValue: 45)

    var body: some View {
        Color.black
            .overlay(alignment: .top) {
                Text(someItem.doubleValue.description)
                    .font(.system(size: 50))
                    .foregroundColor(.white)
            }
            .onTapGesture { someItem.doubleValue += 10.0 }
            .overlay { ChildView(someItem: $someItem) }
    }
}

struct ChildView: View {
    @StateObject
    var viewModel: ViewModel

    init(someItem: Binding<SomeItem>) {
        _viewModel = StateObject(wrappedValue: ViewModel(someItem: someItem))
    }

    var body: some View {
        Rectangle()
            .fill(Color.red)
            .frame(width: 50, height: 70, alignment: .center)
            .rotationEffect(
                Angle(degrees: viewModel.someItem.doubleValue)
            )
            .onTapGesture { viewModel.changeItem() }
            .onChange(of: viewModel.someItem) { _ in
                print("Change Detected", viewModel.someItem.doubleValue)
            }
    }
}

@MainActor
final class ViewModel: ObservableObject {
    @Binding
    var someItem: SomeItem

    public init(someItem: Binding<SomeItem>) {
        self._someItem = someItem
    }

    public func changeItem() {
        self.someItem = SomeItem(doubleValue: .zero)
    }
}

Interestingly, if I make the following changes in ChildView, I get the behavior I want.

Change @StateObject to @ObservedObject

Change _viewModel = StateObject(wrappedValue: ViewModel(someItem: someItem)) to viewModel = ViewModel(someItem: someItem)

From what I understand, it is improper for ChildView's viewModel to be @ObservedObject because ChildView owns viewModel but @ObservedObject gives me the behavior I need whereas @StateObject does not.

Here are the differences I'm paying attention to:

When using @ObservedObject, I can tap the black area and see the changes applied to both the white text and red rectangle. I can also tap the red rectangle and see the changes observed in ParentView through the white text.

When using @StateObject, I can tap the black area and see the changes applied to both the white text and red rectangle. The problem lies in that I can tap the red rectangle here and see the changes reflected in ParentView but ChildView doesn't recognize the change (rotation does not change and "Change Detected" is not printed).

Is @ObservedObject actually correct since ViewModel contains a @Binding to a @State created in ParentView?

Body:
Normally, I would not write such a convoluted solution to a problem, but it sounds like from your comments on another answer there are certain architectural issues that you are required to conform to.

The general issue with your initial approach is that onChange is only going to run when the view has a render triggered. Generally, that happens because some a passed-in property has changed, @State has changed, or a publisher on an ObservableObject has changed. In this case, none of those are true -- you have a Binding on your ObservableObject, but nothing that triggers the view to re-render. If Bindings provided a publisher, it would be easy to hook into that value, but since they do not, it seems like the logical approach is to store the state in the parent view in a way in which we can watch a @Published value.

Again, this is not necessarily the route I would take, but hopefully it fits your requirements:

struct SomeItem: Equatable {
    var doubleValue: Double
}

class Store : ObservableObject {
    @Published var someItem = SomeItem(doubleValue: 45)
}

struct ParentView: View {
    @StateObject private var store = Store()

    var body: some View {
        Color.black
            .overlay(alignment: .top) {
                Text(store.someItem.doubleValue.description)
                    .font(.system(size: 50))
                    .foregroundColor(.white)
            }
            .onTapGesture { store.someItem.doubleValue += 10.0 }
            .overlay { ChildView(store: store) }
    }
}

struct ChildView: View {
    @StateObject private var viewModel: ViewModel

    init(store: Store) {
        _viewModel = StateObject(wrappedValue: ViewModel(store: store))
    }

    var body: some View {
        Rectangle()
            .fill(Color.red)
            .frame(width: 50, height: 70, alignment: .center)
            .rotationEffect(
                Angle(degrees: viewModel.store.someItem.doubleValue)
            )
            .onTapGesture { viewModel.changeItem() }
            .onChange(of: viewModel.store.someItem.doubleValue) { _ in
                print("Change Detected", viewModel.store.someItem.doubleValue)
            }
    }
}

@MainActor
final class ViewModel: ObservableObject {
    var store: Store

    var cancellable : AnyCancellable?

    public init(store: Store) {
        self.store = store
        cancellable = store.$someItem.sink { [weak self] _ in
            self?.objectWillChange.send()
        }
    }

    public func changeItem() {
        store.someItem = SomeItem(doubleValue: .zero)
    }
}


问:
How can I reference a JavaScript variable as a value in an expression with Mapbox?
new to mapbox and enjoying my journey so far.

I am curious if there is a way to reference a javascript variable within an expression.

I am trying to essentially reference some color values that are dynamic, However I've had no luck. I went through the MB docs but I havent been able to find information or options that match my conundrum. Thank you for any info, pointers.

```<code>const mbFillColorExpressionValue = Object.keys(fills)
   .map(fips => {
      return `"${fips}","${fills[fips].fill}"`;
   })
   .concat('"white"')
   .toString();

(mbFillColorExpressionValue returns a string "18089","#839EBE","18091","#839EBE","18127","#839EBE","white")

  this.map.setPaintProperty('counties-towns', 'fill-color', [
     'match',
     ['get', 'GEOID'],
     geoids,
     mbFillColorExpressionValue
   ]);
</code>```

答:
After reading the docs of Mapbox, I think the end result should look something like the code below. Each GEOID is paired with its corresponding fill. And the color white as a fallback on the last line.

```<code>this.map.setPaintProperty('counties-towns', 'fill-color', [
  'match',
   ['get', 'GEOID'],
   '18089', '#839EBE',
   '18091', '#839EBE',
   '18127', '#839EBE',
   'white'
]);
</code>```

To get to that result we first have to change the map method to a flatMap. This is because we can't add any keys when mapping over an array, but we can return an array for each item and the flatten it to turn the whole thing into a single array.

```<code>const mbFillColorExpressionValue = Object.keys(fills).flatMap(fips => [fips, fills[fips].fill]);
mbFillColorExpressionValue.push('white');
</code>```

From here we can use the spread syntax ... to place the contents of the mbFillColorExpressionValue array into the expression.

```<code>this.map.setPaintProperty('counties-towns', 'fill-color', [
  'match',
   ['get', 'GEOID'],
   ...mbFillColorExpressionValue
]);
</code>```

Body:
new to mapbox and enjoying my journey so far.

I am curious if there is a way to reference a javascript variable within an expression.

I am trying to essentially reference some color values that are dynamic, However I've had no luck. I went through the MB docs but I havent been able to find information or options that match my conundrum. Thank you for any info, pointers.

const mbFillColorExpressionValue = Object.keys(fills)
   .map(fips => {
      return `"${fips}","${fills[fips].fill}"`;
   })
   .concat('"white"')
   .toString();

(mbFillColorExpressionValue returns a string "18089","#839EBE","18091","#839EBE","18127","#839EBE","white")

  this.map.setPaintProperty('counties-towns', 'fill-color', [
     'match',
     ['get', 'GEOID'],
     geoids,
     mbFillColorExpressionValue
   ]);

Body:
After reading the docs of Mapbox, I think the end result should look something like the code below. Each GEOID is paired with its corresponding fill. And the color white as a fallback on the last line.

this.map.setPaintProperty('counties-towns', 'fill-color', [
  'match',
   ['get', 'GEOID'],
   '18089', '#839EBE',
   '18091', '#839EBE',
   '18127', '#839EBE',
   'white'
]);

To get to that result we first have to change the map method to a flatMap. This is because we can't add any keys when mapping over an array, but we can return an array for each item and the flatten it to turn the whole thing into a single array.

const mbFillColorExpressionValue = Object.keys(fills).flatMap(fips => [fips, fills[fips].fill]);
mbFillColorExpressionValue.push('white');

From here we can use the spread syntax ... to place the contents of the mbFillColorExpressionValue array into the expression.

this.map.setPaintProperty('counties-towns', 'fill-color', [
  'match',
   ['get', 'GEOID'],
   ...mbFillColorExpressionValue
]);


问:
Azure Pipeline - YAML how to unzip a downloaded secure file and then execute an exe
I have an Azure Pipeline using a YAML that has one task that downloads a zipped secure file:

```<code>- task: DownloadSecureFile@1
  displayName: Download Testpipelineapp
  name: testPipelineapp
  inputs:
    secureFile: TestPipelineapp.zip
</code>```

The download happens perfectly, but then I need to extract the contents because inside is an .EXE that I need to execute.

Any clue on how can I do this? I'm new to YAML and Azure Devops.

答:
There are a couple of options, depending on what's installed in your agent.

The hosted agent comes with a recent enough version of PowerShell to be able to use the Expand-Archive PowerShell function. And it has 7z installed, so you could call that too.

```<code>- script: |
      7z x path-to-downloaded-file.zip  path-to-extract-to
      path-to-extract-to\myexecutable.exe
</code>```
```<code># PowerShell
# Run a PowerShell script on Linux, macOS, or Windows
- task: PowerShell@2
  inputs:
    targetType: inline
    #filePath: # Required when targetType == FilePath
    #arguments: # Optional
    script: |
         Expand-archive -file path-to-downloaded-file.zip -Destinationpath path-to-extract-to
         & path-to-extract-to\myexecutable.exe
    #errorActionPreference: 'stop' # Optional. Options: default, stop, continue, silentlyContinue
    #warningPreference: 'default' # Optional. Options: default, stop, continue, silentlyContinue
    #informationPreference: 'default' # Optional. Options: default, stop, continue, silentlyContinue
    #verbosePreference: 'default' # Optional. Options: default, stop, continue, silentlyContinue
    #debugPreference: 'default' # Optional. Options: default, stop, continue, silentlyContinue
    #failOnStderr: false # Optional
    #ignoreLASTEXITCODE: false # Optional
    pwsh: true
    #workingDirectory: # Optional

</code>```

Then there's the built-in task:

```<code># Extract files
# Extract a variety of archive and compression files such as .7z, .rar, .tar.gz, and .zip
- task: ExtractFiles@1
  inputs:
    #archiveFilePatterns: '**/*.zip'
    destinationFolder:
    #cleanDestinationFolder: true
    #overwriteExistingFiles: false
    #pathToSevenZipTool:
</code>```

https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/utility/extract-files?view=azure-devops

Body:
I have an Azure Pipeline using a YAML that has one task that downloads a zipped secure file:

- task: DownloadSecureFile@1
  displayName: Download Testpipelineapp
  name: testPipelineapp
  inputs:
    secureFile: TestPipelineapp.zip

The download happens perfectly, but then I need to extract the contents because inside is an .EXE that I need to execute.

Any clue on how can I do this? I'm new to YAML and Azure Devops.

Body:
There are a couple of options, depending on what's installed in your agent.

The hosted agent comes with a recent enough version of PowerShell to be able to use the Expand-Archive PowerShell function. And it has 7z installed, so you could call that too.

- script: |
      7z x path-to-downloaded-file.zip  path-to-extract-to
      path-to-extract-to\myexecutable.exe

# PowerShell
# Run a PowerShell script on Linux, macOS, or Windows
- task: PowerShell@2
  inputs:
    targetType: inline
    #filePath: # Required when targetType == FilePath
    #arguments: # Optional
    script: |
         Expand-archive -file path-to-downloaded-file.zip -Destinationpath path-to-extract-to
         & path-to-extract-to\myexecutable.exe
    #errorActionPreference: 'stop' # Optional. Options: default, stop, continue, silentlyContinue
    #warningPreference: 'default' # Optional. Options: default, stop, continue, silentlyContinue
    #informationPreference: 'default' # Optional. Options: default, stop, continue, silentlyContinue
    #verbosePreference: 'default' # Optional. Options: default, stop, continue, silentlyContinue
    #debugPreference: 'default' # Optional. Options: default, stop, continue, silentlyContinue
    #failOnStderr: false # Optional
    #ignoreLASTEXITCODE: false # Optional
    pwsh: true
    #workingDirectory: # Optional

Then there's the built-in task:

# Extract files
# Extract a variety of archive and compression files such as .7z, .rar, .tar.gz, and .zip
- task: ExtractFiles@1
  inputs:
    #archiveFilePatterns: '**/*.zip'
    destinationFolder:
    #cleanDestinationFolder: true
    #overwriteExistingFiles: false
    #pathToSevenZipTool:

https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/utility/extract-files?view=azure-devops


问:
Bash - Update terminal title by running a second command
On my terminal in Ubuntu, I often run programs which keep running for a long time. And since there are a lot of these programs, I keep forgetting which terminal is for which program, unless I tab through all of those. So I wanted to find a way to update my terminal title to the program name, whenever I run a command. I don't want to do it manually. </p>

<p>I use gnome-terminal, but answer shouldn't really depend on that. Basically, If I'm able to run a second command, then I can simply use gconftool command to update the title. So I was hoping to find a way to capture the command in bash and update the title after every command. How do I do that? </p>

答:
Try this:

```<code>trap 'echo -ne "\033]2;$(history 1 | sed "s/^[ ]*[0-9]*[ ]*//g")\007"' DEBUG
</code>```

Thanks to the history 1 it works even with complicated expressions like:

```<code>true && (false); echo $? | cat
</code>```

For which approaches relying on $BASH_COMMAND or $@ fail. For example simon's displays:

```<code>true | echo $? | cat
</code>```

Thanks to Gilles and simon for providing inspiration.

ContentLicense: CC BY-SA 2.5

Body:
On my terminal in Ubuntu, I often run programs which keep running for a long time. And since there are a lot of these programs, I keep forgetting which terminal is for which program, unless I tab through all of those. So I wanted to find a way to update my terminal title to the program name, whenever I run a command. I don't want to do it manually.

I use gnome-terminal, but answer shouldn't really depend on that. Basically, If I'm able to run a second command, then I can simply use gconftool command to update the title. So I was hoping to find a way to capture the command in bash and update the title after every command. How do I do that?

Body:
Try this:

trap 'echo -ne "\033]2;$(history 1 | sed "s/^[ ]*[0-9]*[ ]*//g")\007"' DEBUG

Thanks to the history 1 it works even with complicated expressions like:

true && (false); echo $? | cat

For which approaches relying on $BASH_COMMAND or $@ fail. For example simon's displays:

true | echo $? | cat

Thanks to Gilles and simon for providing inspiration.

ContentLicense: CC BY-SA 3.0


问:
Running MacOS shortcuts shell command from node script
I am trying to run MacOS shortcuts via NodeJS script. To achieve that I created shortcuts in the MacOS Shortcuts app, which normally run in the terminal (ZSH) by typing shortcuts run shortcutname (Docs). They work fine when typing them directly into the terminal, but not when called from a NodeJS script.

My script looks like this:

```<code>
exec('shortcuts run shortcutname', (error, stdout, stderr) => {
    if (error) {
        console.log(`error: ${error.message}`);
        return;
    }
    if (stderr) {
        console.log(`stderr: ${stderr}`);
        return;
    }
    console.log(`stdout: ${stdout}`);
});
</code>```

When starting the script from the terminal node script.js it does nothing. It does not return anything nor does it finish. I tried replacing the command shortcuts run shortcutname by other commands the system should know. For example ls, or git. They  all work. Also when I leave out the shortcutname in the end, it complains about the missing parameter.

I was suspecting missing access rights, but apparently NodeJS runs as my normal user. Running whoami in script context returns my user name.

NODE_DEBUG=cluster,net,http,fs,tls,module,timers node script.js did not show anything unusual. I also tried using the full path of the binary. which shortcuts gave me /usr/bin/shortcuts. Which I used in my script /usr/bin/shortcuts run shortcutname.

What am I missing? Thanks in advance!

答:
Though I thought I tested it, I found the solution:
execSync instead of exec works

It’d be cool if someone could explain why exec wouldn’t work.

Cheers!

Body:
I am trying to run MacOS shortcuts via NodeJS script. To achieve that I created shortcuts in the MacOS Shortcuts app, which normally run in the terminal (ZSH) by typing shortcuts run shortcutname (Docs). They work fine when typing them directly into the terminal, but not when called from a NodeJS script.

My script looks like this:

exec('shortcuts run shortcutname', (error, stdout, stderr) => {
    if (error) {
        console.log(`error: ${error.message}`);
        return;
    }
    if (stderr) {
        console.log(`stderr: ${stderr}`);
        return;
    }
    console.log(`stdout: ${stdout}`);
});

When starting the script from the terminal node script.js it does nothing. It does not return anything nor does it finish. I tried replacing the command shortcuts run shortcutname by other commands the system should know. For example ls, or git. They  all work. Also when I leave out the shortcutname in the end, it complains about the missing parameter.

I was suspecting missing access rights, but apparently NodeJS runs as my normal user. Running whoami in script context returns my user name.

NODE_DEBUG=cluster,net,http,fs,tls,module,timers node script.js did not show anything unusual. I also tried using the full path of the binary. which shortcuts gave me /usr/bin/shortcuts. Which I used in my script /usr/bin/shortcuts run shortcutname.

What am I missing? Thanks in advance!


问:
jQuery - chaining a native function
Can anyone explain why I can chain a native JavaScript function to a jQuery function like so:

```<code>$('#search').val().replace("00:00:00", "")
</code>```

In this case, replace is the native JavaScript function.

http://www.w3schools.com/jsref/jsref_replace.asp

Thanks

答:
As Jamie said the functions get evaluated left to right. So val() returns a type string, which has the method replace.
The reason jquery functions are all chainable is because they return a reference to the original object created by the selector each time they return.
With the exceptions of val(), text(), html() and a few others.

Title: jQuery - chaining a native function

Body:
Can anyone explain why I can chain a native JavaScript function to a jQuery function like so:

$('#search').val().replace("00:00:00", "")

In this case, replace is the native JavaScript function.

http://www.w3schools.com/jsref/jsref_replace.asp

Thanks


问:
Why does hard-coding in numbers work, but using variables with the same values, doesn't?
I'm writing a program that is a game where you have to guess whichever random 4 digit integer that the computer generates. I'm having trouble with the input validation - more specifically, my isDigit() method, which aims to make sure all inputs from userGuess are digits 0 - 9:

```<code>    private static boolean isDigit(char indexPos) { // verifies if the input char is a digit 0-9 or not
        if(indexPos == 0 || indexPos == 1 || indexPos == 2 || indexPos == 3 || indexPos == 4 || indexPos == 5 || indexPos == 6 || indexPos == 7 || indexPos == 8 || indexPos == 9) {
            return true;
        }
        else {
            return false;
        }
    }
</code>```

If I hardcode in things like

```<code>isDigit(1)
</code>```

it evaluates as true, but if I plug in variables, it returns false. Mainly, this returns false, even when all index positions of userGuess are digits 0-9:

```<code>isDigit(userGuess.charAt(i)) // returns false even when index pos i is [0-9]
</code>```

I'm utterly confused and stumped as to why this happens. For context, here's the whole if and for loop situation for the validation:

```<code>numGuess++;
System.out.print("Guess " + numGuess + ": ");
userGuess = kbd.nextLine();
System.out.println("DEBUG: userGuess.length() : " + userGuess.length());

// validate that the input is a valid input (a 4 digit natural number, incl 0000)
if(userGuess.length() < 4 || userGuess.length() >= 5){
   System.out.println("Please enter a valid input, which is a 4 digit natural number (postive integer, including 0000).");
}
else if(userGuess.length() == 4) {
   for(int i = 0;  i <= 3; i++) {
     if(isDigit(userGuess.charAt(i)) == true) {
        validateCount++;
     }
}
</code>```

I also have, what I assume to be the same issue, on validating if userGuess.length() == 4. If I output userGuess.legnth() on the console, it provides the correct number, and when == 4, this if loop doesn't run, even though the condition is met:

```<code>if (userGuess.length() < 4 || userGuess.length() >= 5) {
   System.out.println("Please enter a valid input, which is a 4 digit natural number (postive integer, including 0000).");
} else if (userGuess.length() == 4) { // avoid out of bounds errors for inputs less than 4 digits
   for (int i = 0; i <= 3; i++) { // userGuess will never have an index above 3, as it is a 4 digit number
if (isDigit(userGuess.charAt(i)) == true && userGuess.length() == 4) { // verify that the userInput is a 4 digit integer
    validateCount++;
}
</code>```

答:
If you are really working with characters, then you could do this.

```<code>private static boolean isDigit(char indexPos) {
    return Character.isDigit(indexPos);
}
</code>```

But then, you don't really need a new method.  In any event I would suggest you work with actual ints as the argument name indexPos suggests.

Body:
I'm writing a program that is a game where you have to guess whichever random 4 digit integer that the computer generates. I'm having trouble with the input validation - more specifically, my isDigit() method, which aims to make sure all inputs from userGuess are digits 0 - 9:

    private static boolean isDigit(char indexPos) { // verifies if the input char is a digit 0-9 or not
        if(indexPos == 0 || indexPos == 1 || indexPos == 2 || indexPos == 3 || indexPos == 4 || indexPos == 5 || indexPos == 6 || indexPos == 7 || indexPos == 8 || indexPos == 9) {
            return true;
        }
        else {
            return false;
        }
    }

If I hardcode in things like

isDigit(1)

it evaluates as true, but if I plug in variables, it returns false. Mainly, this returns false, even when all index positions of userGuess are digits 0-9:

isDigit(userGuess.charAt(i)) // returns false even when index pos i is [0-9]

I'm utterly confused and stumped as to why this happens. For context, here's the whole if and for loop situation for the validation:

numGuess++;
System.out.print("Guess " + numGuess + ": ");
userGuess = kbd.nextLine();
System.out.println("DEBUG: userGuess.length() : " + userGuess.length());

// validate that the input is a valid input (a 4 digit natural number, incl 0000)
if(userGuess.length() < 4 || userGuess.length() >= 5){
   System.out.println("Please enter a valid input, which is a 4 digit natural number (postive integer, including 0000).");
}
else if(userGuess.length() == 4) {
   for(int i = 0;  i <= 3; i++) {
     if(isDigit(userGuess.charAt(i)) == true) {
        validateCount++;
     }
}

I also have, what I assume to be the same issue, on validating if userGuess.length() == 4. If I output userGuess.legnth() on the console, it provides the correct number, and when == 4, this if loop doesn't run, even though the condition is met:

if (userGuess.length() < 4 || userGuess.length() >= 5) {
   System.out.println("Please enter a valid input, which is a 4 digit natural number (postive integer, including 0000).");
} else if (userGuess.length() == 4) { // avoid out of bounds errors for inputs less than 4 digits
   for (int i = 0; i <= 3; i++) { // userGuess will never have an index above 3, as it is a 4 digit number
if (isDigit(userGuess.charAt(i)) == true && userGuess.length() == 4) { // verify that the userInput is a 4 digit integer
    validateCount++;
}

Body:
If you are really working with characters, then you could do this.

private static boolean isDigit(char indexPos) {
    return Character.isDigit(indexPos);
}

But then, you don't really need a new method.  In any event I would suggest you work with actual ints as the argument name indexPos suggests.


问:
SQLSTATE[HY000] [1045] Access denied for user 'username'@'localhost' (using password: YES)
In my Ubuntu VM, I kept getting

SQLSTATE[HY000] [1045] Access denied for user 'username'@'localhost' (using password: YES)

update

I have configured my database like this in my .env file

```<code>DB_HOST=45.55.88.57
DB_DATABASE=b-prod
DB_USERNAME=root
DB_PASSWORD=*********
UNIX_SOCKET=/var/run/mysqld/mysqld.sock
</code>```

It works perfectly.

But when I use

```<code>DB_HOST=45.55.88.57
DB_DATABASE=b-prod
DB_USERNAME=b <----------------------------------------------
DB_PASSWORD=*********
UNIX_SOCKET=/var/run/mysqld/mysqld.sock
</code>```

I didn't work.

What else I should look  into to prevent this ?

I have a feeling that I have the wrong password.

How do I test my database password ? DB_PASSWORD=********* ?

This is all user I have

```<code>mysql> SELECT User,Host FROM mysql.user;
+------------------+-------------+
| User             | Host        |
+------------------+-------------+
| root             | %           |
| root             | 127.0.0.1   |
| root             | 45.55.88.57 |
| root             | ::1         |
| root             | b       |
| b            | localhost   |
| debian-sys-maint | localhost   |
| root             | localhost   |
+------------------+-------------+
8 rows in set (0.00 sec)
</code>```

答:
I'm also faced this issue. ENV Variable should be with in the double quotes When we used complex characters of string on .env file. Such as passwords, secrets, key and so on.

```<code>DB_PASSWORD="FDXSCHVBGFFUOVIDVKTFUVIF++++++****"
</code>```

please first check this scenario.

Thank you..

Body:
In my Ubuntu VM, I kept getting

SQLSTATE[HY000] [1045] Access denied for user 'username'@'localhost' (using password: YES)

update

I have configured my database like this in my .env file

DB_HOST=45.55.88.57
DB_DATABASE=b-prod
DB_USERNAME=root
DB_PASSWORD=*********
UNIX_SOCKET=/var/run/mysqld/mysqld.sock

It works perfectly.

But when I use

DB_HOST=45.55.88.57
DB_DATABASE=b-prod
DB_USERNAME=b <----------------------------------------------
DB_PASSWORD=*********
UNIX_SOCKET=/var/run/mysqld/mysqld.sock

I didn't work.

What else I should look  into to prevent this ?

I have a feeling that I have the wrong password.

How do I test my database password ? DB_PASSWORD=********* ?

This is all user I have

mysql> SELECT User,Host FROM mysql.user;
+------------------+-------------+
| User             | Host        |
+------------------+-------------+
| root             | %           |
| root             | 127.0.0.1   |
| root             | 45.55.88.57 |
| root             | ::1         |
| root             | b       |
| b            | localhost   |
| debian-sys-maint | localhost   |
| root             | localhost   |
+------------------+-------------+
8 rows in set (0.00 sec)

Body:
I'm also faced this issue. ENV Variable should be with in the double quotes When we used complex characters of string on .env file. Such as passwords, secrets, key and so on.

DB_PASSWORD="FDXSCHVBGFFUOVIDVKTFUVIF++++++****"

please first check this scenario.

Thank you..


问:
Apply vector exponents to columns of matrix
In the cmprsk package one of the tests to call crr shows the following:

crr(ftime,fstatus,cov,cbind(cov[,1],cov[,1]),function(Uft) cbind(Uft,Uft^2))

It's the final inline function function(Uft) cbind(Uft,Uft^2) which I am interested in generalizing. This example call to crr above has cov1 as cov and cov2 as cbind(cov[,1],cov[,1]), essentially hardcoding the number of covariates. Hence the hardcoding of the function function(Uft) cbind(Uft,Uft^2) is sufficient.

I am working on some benchmarking code where I would like the number of covariates to be variable. So I generate a matrix cov2 which is has nobs rows and ncovs columns (rather than ncovs being pre-defined as 2 above).

My question is - how do I modify the inline function function(Uft) cbind(Uft,Uft^2) to take in a single column vector of length nobs and return a matrix of size nobs x ncovs where each column is simply the input vector raised to the column index?

Minimal reproducible example below. My call to z2 <- crr(...) is incorrect:

```<code>#!/usr/bin/env Rscript

library(cmprsk)

for(seed in c(1, 2)) {
    for(Nobs in c(10, 20)) {
        for(Ncovs in c(2, 3)) {
            set.seed(seed);
            ftime <- rexp(Nobs);
            fstatus <- sample(0:Ncovs,Nobs,replace=TRUE);
            cov1 <- matrix(runif(Nobs*Ncovs),nrow=Nobs);
            cov2 <- matrix(runif(Nobs*Ncovs),nrow=Nobs);
            df <- data.frame(ftime=ftime, fstatus=fstatus, cov1=cov1);

            z1 <- crr(ftime, fstatus, cov1, );
            z2 <- crr(ftime, fstatus, cov1, cov2, function(Uft) Uft^cbind(1:Ncovs));
        }
    }
}
</code>```

Body:
In the cmprsk package one of the tests to call crr shows the following:

crr(ftime,fstatus,cov,cbind(cov[,1],cov[,1]),function(Uft) cbind(Uft,Uft^2))

It's the final inline function function(Uft) cbind(Uft,Uft^2) which I am interested in generalizing. This example call to crr above has cov1 as cov and cov2 as cbind(cov[,1],cov[,1]), essentially hardcoding the number of covariates. Hence the hardcoding of the function function(Uft) cbind(Uft,Uft^2) is sufficient.

I am working on some benchmarking code where I would like the number of covariates to be variable. So I generate a matrix cov2 which is has nobs rows and ncovs columns (rather than ncovs being pre-defined as 2 above).

My question is - how do I modify the inline function function(Uft) cbind(Uft,Uft^2) to take in a single column vector of length nobs and return a matrix of size nobs x ncovs where each column is simply the input vector raised to the column index?

Minimal reproducible example below. My call to z2 <- crr(...) is incorrect:

#!/usr/bin/env Rscript

library(cmprsk)

for(seed in c(1, 2)) {
    for(Nobs in c(10, 20)) {
        for(Ncovs in c(2, 3)) {
            set.seed(seed);
            ftime <- rexp(Nobs);
            fstatus <- sample(0:Ncovs,Nobs,replace=TRUE);
            cov1 <- matrix(runif(Nobs*Ncovs),nrow=Nobs);
            cov2 <- matrix(runif(Nobs*Ncovs),nrow=Nobs);
            df <- data.frame(ftime=ftime, fstatus=fstatus, cov1=cov1);

            z1 <- crr(ftime, fstatus, cov1, );
            z2 <- crr(ftime, fstatus, cov1, cov2, function(Uft) Uft^cbind(1:Ncovs));
        }
    }
}

Body:
You can use sapply :

Uft <- 1:5
Ncovs <- 6
sapply(1:Ncovs, function(i) Uft^i)
#>      [,1] [,2] [,3] [,4] [,5]  [,6]
#> [1,]    1    1    1    1    1     1
#> [2,]    2    4    8   16   32    64
#> [3,]    3    9   27   81  243   729
#> [4,]    4   16   64  256 1024  4096
#> [5,]    5   25  125  625 3125 15625

In your code :

function(Uft) sapply(1:Ncovs, function(i) Uft^i)

A better alternative using outer :

function(Uft) outer(Uft, 1:Ncovs, "^")


问:
How do I get the current time?
How do I get the current time?</p>

答:
Gets the current time and converts it to string:</p>
```<code>from datetime import datetime
datetime.now().strftime('%Y-%m-%d %H:%M:%S')
</code>```

Title: How do I get the current time?

Body: How do I get the current time?

Body:
Gets the current time and converts it to string:

from datetime import datetime
datetime.now().strftime('%Y-%m-%d %H:%M:%S')


问:
record the computation time for each epoch during model.fit()
I am using the standard keras process to train a model:

```<code>model.compile(optimizer = 'adam', loss = 'mean_squared_error')
model.fit(x_train, y_train, epochs = 50)

</code>```

And the output is something like:

```<code>Epoch 1/50
52/52 [==============================] - 8s 90ms/step - loss: 0.0027
Epoch 2/50
52/52 [==============================] - 5s 90ms/step - loss: 0.0023
</code>```

How can I calculate elapsed time for each Epoch?

I will have more than one experiment so I want to compare times.

答:
The proper way to do it, would be to write your own training callback inheriting from the Callback class.

You then need to override the methods on_epoch_begin() and on_epoch_end() which are called by model.fit() during training. There you can start and end counters, and save the results to internal variables to access them later.

But wouldn't it be easier to simple measure the time of the whole training process and divide by the number of epochs? (Although, that would also take into account the validation time)

Body:
I am using the standard keras process to train a model:

model.compile(optimizer = 'adam', loss = 'mean_squared_error')
model.fit(x_train, y_train, epochs = 50)

And the output is something like:

Epoch 1/50
52/52 [==============================] - 8s 90ms/step - loss: 0.0027
Epoch 2/50
52/52 [==============================] - 5s 90ms/step - loss: 0.0023

How can I calculate elapsed time for each Epoch?

I will have more than one experiment so I want to compare times.


答:
It's because:

```<code>$('#search').val().replace("00:00:00", "")
</code>```

will evaluate to:

```<code>"some string".replace("00:00:00", "")
</code>```

which is nothing special. It basically always comes down to evaluating the functions from left to right, also in cases like:

```<code>$('#search').eq(0).val().replace("00:00:00", "")
<jQuery obj>.val().replace("00:00:00", "")
"some string".replace("00:00:00", "")
</code>```

Title: jQuery - chaining a native function

Body:
It's because:

$('#search').val().replace("00:00:00", "")

will evaluate to:

"some string".replace("00:00:00", "")

which is nothing special. It basically always comes down to evaluating the functions from left to right, also in cases like:

$('#search').eq(0).val().replace("00:00:00", "")
<jQuery obj>.val().replace("00:00:00", "")
"some string".replace("00:00:00", "")


问:
Android client only connecting once to server with LipeRMI
I have an Android client connecting to a Java server with LipeRMI (http://lipermi.sourceforge.net/).

To test this communication I have a button in my interface that when clicked sends a String "Test". It gets to the server and the server returns the String. It works fine, the problem is that it only works once. The server only accepts one time.

My Server code is the following:

```<code>public class TestServer implements TestService {

public TestServer() {
    try {
        CallHandler callHandler = new CallHandler();
        callHandler.registerGlobal(TestService.class, this);
        Server server = new Server();
        server.bind(7777, callHandler);
        server.addServerListener(new IServerListener() {

            @Override
            public void clientDisconnected(Socket socket) {
                System.out.println("Client Disconnected: " + socket.getInetAddress());
            }

            @Override
            public void clientConnected(Socket socket) {
                System.out.println("Client Connected: " + socket.getInetAddress());
            }
        });
        System.out.println("Server Listening");
    } catch (LipeRMIException | IOException e) {
        e.printStackTrace();
    }
}

@Override
public String getResponse(String data) {
    System.out.println("getResponse called");
    System.out.println("The information received was: " + data);

    return "Your data: " + data;
}
</code>```

And in the Android client, in my MainActivity I have the following:

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

private String serverIP = "192.168.3.8";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button btnGet = (Button) findViewById(R.id.send);
    btnGet.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            new Conn().execute();
        }
    });

}

class Conn extends AsyncTask<Void, Void, MainActivity> {

    @Override
    protected MainActivity doInBackground(Void... params) {
        Looper.prepare();
        try {
            CallHandler callHandler = new CallHandler();
            Client client = new Client(serverIP, 7777, callHandler);
            TestService testService = (TestService) client.getGlobal(TestService.class);

            String msg = testService.getResponse("Test");
            Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Looper.loop();
        return null;
    }
}
</code>```

They have the TestService interface in common so that I can use the methods from the server.

How can I change the server so that it can accept any number of times a call from the Android Client?

答: I had the same issue and I deleted the Looper.prepare() and Looper.loop() calls in the doInBackground method from AsyncTask. It solved the problem in my case.

Body:
I have an Android client connecting to a Java server with LipeRMI (http://lipermi.sourceforge.net/).

To test this communication I have a button in my interface that when clicked sends a String "Test". It gets to the server and the server returns the String. It works fine, the problem is that it only works once. The server only accepts one time.

My Server code is the following:

public class TestServer implements TestService {

public TestServer() {
    try {
        CallHandler callHandler = new CallHandler();
        callHandler.registerGlobal(TestService.class, this);
        Server server = new Server();
        server.bind(7777, callHandler);
        server.addServerListener(new IServerListener() {

            @Override
            public void clientDisconnected(Socket socket) {
                System.out.println("Client Disconnected: " + socket.getInetAddress());
            }

            @Override
            public void clientConnected(Socket socket) {
                System.out.println("Client Connected: " + socket.getInetAddress());
            }
        });
        System.out.println("Server Listening");
    } catch (LipeRMIException | IOException e) {
        e.printStackTrace();
    }
}

@Override
public String getResponse(String data) {
    System.out.println("getResponse called");
    System.out.println("The information received was: " + data);

    return "Your data: " + data;
}

And in the Android client, in my MainActivity I have the following:

public class MainActivity extends Activity {

private String serverIP = "192.168.3.8";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button btnGet = (Button) findViewById(R.id.send);
    btnGet.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            new Conn().execute();
        }
    });

}

class Conn extends AsyncTask<Void, Void, MainActivity> {

    @Override
    protected MainActivity doInBackground(Void... params) {
        Looper.prepare();
        try {
            CallHandler callHandler = new CallHandler();
            Client client = new Client(serverIP, 7777, callHandler);
            TestService testService = (TestService) client.getGlobal(TestService.class);

            String msg = testService.getResponse("Test");
            Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Looper.loop();
        return null;
    }
}

They have the TestService interface in common so that I can use the methods from the server.

How can I change the server so that it can accept any number of times a call from the Android Client?


问:
How to create Material UI Dialog with transparent background color?
I'm trying to create a loading status indicator using Material UI. But I want the background color of the dialogue box as none and also want to adjust the height. But I'm not able to do it with the style option provided by them. Any solution?

Now it looks like this..

Code looks like this:

```<code><Dialog
  open={true}
  style={{width: '200px', marginLeft: '40%', backgroundColor: 'transparent'}}
  title= 'Loading'
  titleStyle={{paddingTop: '0px', paddingLeft: '45px', fontSize: '15px', lineHeight: '40px'}}
>
    <RefreshIndicator
      style= {{display: 'inline-block'}}
      size={50}
      left={50}
      top={30}
      loadingColor="#FF9800"
      status="loading"
    />
</Dialog>
</code>```

答:
Another potential alternative for this (depends on what you want to achieve) is to avoid using a Paper component for the Dialog container. For example, if you use a Box component instead, it won't be visible to the user:

```<code><Dialog
  className="MyDialog"
  open={!!openProp}
  onClose={handleDialogClose}
  maxWidth="xl"
  PaperComponent={Box}
>
</code>```

Note that by default it will still contain an 'invisible' padding (or even cover most of the screen if you use the fullWidth prop), and this can be confusing for users, since the Dialog won't get closed when clicking within this invisible component.

Body:
I'm trying to create a loading status indicator using Material UI. But I want the background color of the dialogue box as none and also want to adjust the height. But I'm not able to do it with the style option provided by them. Any solution?

Now it looks like this..

Code looks like this:

<Dialog
  open={true}
  style={{width: '200px', marginLeft: '40%', backgroundColor: 'transparent'}}
  title= 'Loading'
  titleStyle={{paddingTop: '0px', paddingLeft: '45px', fontSize: '15px', lineHeight: '40px'}}
>
    <RefreshIndicator
      style= {{display: 'inline-block'}}
      size={50}
      left={50}
      top={30}
      loadingColor="#FF9800"
      status="loading"
    />
</Dialog>

Body:
Another potential alternative for this (depends on what you want to achieve) is to avoid using a Paper component for the Dialog container. For example, if you use a Box component instead, it won't be visible to the user:

<Dialog
  className="MyDialog"
  open={!!openProp}
  onClose={handleDialogClose}
  maxWidth="xl"
  PaperComponent={Box}
>

Note that by default it will still contain an 'invisible' padding (or even cover most of the screen if you use the fullWidth prop), and this can be confusing for users, since the Dialog won't get closed when clicking within this invisible component.


问:
What's an example of Ruby code that's "too clever"?
I was having a discussion with some programmer friends who said that they see Ruby programmers (in particular) producing a lot of code that's "too clever". So I'm wondering what would that look like? I'm referring to the unnecessary use of an obscure language feature in a context in which something straightforward would have worked just as well or better. Know any good Ruby examples of this?</p>

答: method_missing can be abused and it's one of those things that may cause you to pull your hair out when you have to fix a bug 3 months after you've written code.</p>

OwnerDisplayName: amsterdam

LastEditorDisplayName: amsterdam

OwnerDisplayName: qwertyuiop


问:
redirecting to thankyou.aspx page after survey
I am trying to direct after user click on "Finish" on a sharepoint survey. But the following code executes when user click on "Respond to this survey". Any idea what is happening.</p>

```<code><script type="text/javascript">
function redirect()
{
  var inputcCtrls = document.getElementsByTagName("input");
  for(var m=0; m<inputcCtrls.length; m++)
   if(inputcCtrls[m].type=='button'&&inputcCtrls[m].value=='Finish')
     var funcOnClick = inputcCtrls[m].onclick;
         inputcCtrls[m].onclick = window.location = "http://www.google.com/";
}
redirect();
</script>
</code>```

答:
It's easier to assign a unique class name to the button and use document.getElementsByClassName than it is to loop through all the inputs to get the right one.

```<code>var inputcCtrls = document.getElementsByClassName("finalButton");
inputcCtrls[0].onclick = function() {
    window.location = "http://www.google.com/";
}
</code>```

Body:
It's easier to assign a unique class name to the button and use document.getElementsByClassName than it is to loop through all the inputs to get the right one.

var inputcCtrls = document.getElementsByClassName("finalButton");
inputcCtrls[0].onclick = function() {
    window.location = "http://www.google.com/";
}


问:
Facebook Page Access Token
i want to bind the rating information from Facebook Page into my website.

First i get the Information from the Graph API Explorer, and that works well.

Know i have tried to programming this with javascript and i have problems with the page access token.

```<code>      FB.api('/{page-id}/ratings', function(response) {
          console.log(response);

      });
</code>```

The Stacktrace:

How can i include/programming the Page Access Token into the function?

答:
To access page specific data, first you need to obtain a page access token for the specific page and then call the api along with that token.</p>
```<code>//Load FB js SDK here

function getpages() {
    FB.api('/me/accounts', function(response) {
        console.log('page details');
        console.log(response);
        $.each(response.data,function(index, item){
            $("#fbpgs").append("<div class='row'>"+item.name+"<button onclick='getads("+item.id+",\""+item.access_token+"\")' >Show details</button></div>");
        });
    });
}

function get_page_data(pid,token) {
    $("#lead_forms").html("");
    $(".dv").removeClass("seldiv");
    $(dv).parent().parent().addClass("seldiv");
    FB.api("/"+pid+"/leadgen_forms",{access_token : token}, function(response) {
        console.log('page details');
        console.log(response);
    });
}

<button onclick='getpages()'>load pages</a>
<div class='fbpgs'></div>
</code>```

Title: Facebook Page Access Token

Body:
i want to bind the rating information from Facebook Page into my website.

First i get the Information from the Graph API Explorer, and that works well.

Know i have tried to programming this with javascript and i have problems with the page access token.

      FB.api('/{page-id}/ratings', function(response) {
          console.log(response);

      });

The Stacktrace:

How can i include/programming the Page Access Token into the function?

Body:
To access page specific data, first you need to obtain a page access token for the specific page and then call the api along with that token.

//Load FB js SDK here

function getpages() {
    FB.api('/me/accounts', function(response) {
        console.log('page details');
        console.log(response);
        $.each(response.data,function(index, item){
            $("#fbpgs").append("<div class='row'>"+item.name+"<button onclick='getads("+item.id+",\""+item.access_token+"\")' >Show details</button></div>");
        });
    });
}

function get_page_data(pid,token) {
    $("#lead_forms").html("");
    $(".dv").removeClass("seldiv");
    $(dv).parent().parent().addClass("seldiv");
    FB.api("/"+pid+"/leadgen_forms",{access_token : token}, function(response) {
        console.log('page details');
        console.log(response);
    });
}

<button onclick='getpages()'>load pages</a>
<div class='fbpgs'></div>


问:
Form generator with CRUD operations for Wicket
Some related questions have been posted on this topic, but for Wicket specifically they date back to almost a decade ago. What are some modern day solutions to creating a table (data pulled from a database) with CRUD operations in Wicket similarly to the screenshot below.

Note the above example was created using Wicket RAD which has not been updated since 2010

答:
Check Apache Isis.

In Isis you define a Pojo/Model and it generates both UI (Wicket) and REST (RestEasy) frontends for you. It is quite advanced but also it learning curve is a bit steep.


问:
Visual Studio 2022 version 17.0.0 - Browser Link refresh feature causes an error in the web browser dubug console
Getting acustomed with the latest Visual Studio.

In my NET Core 5 web app, each time I press the save button in VS, the browser automatically refreshes with the updated code (i.e. after making some modifications to javscript)

I get the error below in the debug console and see that VS has added some unexpected script to my page:

```<code><!-- Visual Studio Browser Link -->
<script type="text/javascript" src="https://localhost:44399/46dcd6a7a1bc4303ab72eae2b0033153/browserLink"
async="async" id="__browserLink_initializationData" data-requestId="c33a3fe85ae64c3391c704f430971956"
data-requestMappingFromServer="False"></script>
<!-- End Browser Link -->

<script src="/_framework/aspnetcore-browser-refresh.js"></script></body>
</code>```

I kinda like the new feature but I really dont want console errors when trying to test my app and code for stability. Is there a way to sort this error? expect its eomthig to do with the fact that I have cross-site scripting protection baked into the NET Core environment.

答: This went away for us when we switched off "Projects and Solutions > ASP.NET Core > CSS Hot Reload". But this may be unacceptable if you need hot reloading of CSS.</p>

Body:
Getting acustomed with the latest Visual Studio.

In my NET Core 5 web app, each time I press the save button in VS, the browser automatically refreshes with the updated code (i.e. after making some modifications to javscript)

I get the error below in the debug console and see that VS has added some unexpected script to my page:

I kinda like the new feature but I really dont want console errors when trying to test my app and code for stability. Is there a way to sort this error? expect its eomthig to do with the fact that I have cross-site scripting protection baked into the NET Core environment.


问:
Why are even lazy folds so eager?
This code:

```<code>import Data.Foldable
import Debug.Trace

factors :: [Bool]
factors = [True, True, False, True, True, True, True, True]

andy :: Bool -> Bool -> Bool
andy False _ = False
andy True False = False
andy True True = True

tandy :: Bool -> Bool -> Bool
tandy a b = let c = a `andy` b in trace (show a ++ " & " ++ show b ++ " = " ++ show c) c

wonder :: Bool
wonder = foldl tandy True factors

</code>```

says this when I evaluate wonder:

```<code>True & True = True
True & True = True
True & False = False
False & True = False
False & True = False
False & True = False
False & True = False
False & True = False
</code>```

but I would have preferred it to have stopped sooner. I've tried this with everything imaginable in place of the foldl and with && in place of andy but it never seems to get the hint.

It seems to me that the line andy False _ = False doesn't invite the compiler to evaluate the second parameter. I haven't forced any strictness. What's going on? Even C can do better.

答:
tandy is strict in both parameters, even though andy is not. This is because of the tracing. You ask it to show both inputs in the call to trace, so it has to evaluate both arguments.

Consider `tandy2':

```<code>tandy2 :: Bool -> Bool -> Bool
tandy2 False _ = trace ("False & anything = False") False
tandy2 True b = trace ("True & " ++ show b ++ " = False") b
</code>```

Instead of blindly evaluating both arguments in its tracing, it is careful to only evaluate the same arguments it would otherwise. This makes it actually reflect the same strictness properties as andy has.

Try using tandy2 with foldr and you'll see it stops evaluating as soon as it hits a False.

```<code>$ ghci
GHCi, version 9.2.1: https://www.haskell.org/ghc/  :? for help
ghci> import Debug.Trace
ghci> let tandy2 False _ = trace ("False & anything = False") False ; tandy2 True b = trace ("True & " ++ show b ++ " = False") b
ghci> foldr tandy2 True []
True
ghci> foldr tandy2 True [True]
True & True = False
True
ghci> foldr tandy2 True [True, False]
False & anything = False
True & False = False
False
ghci> foldr tandy2 True [True, False, True]
False & anything = False
True & False = False
False
</code>```

There you go. It never evaluates the False branch more than once.

Title: Why are even lazy folds so eager?

Body:
This code:

import Data.Foldable
import Debug.Trace

factors :: [Bool]
factors = [True, True, False, True, True, True, True, True]

andy :: Bool -> Bool -> Bool
andy False _ = False
andy True False = False
andy True True = True

tandy :: Bool -> Bool -> Bool
tandy a b = let c = a `andy` b in trace (show a ++ " & " ++ show b ++ " = " ++ show c) c

wonder :: Bool
wonder = foldl tandy True factors

says this when I evaluate wonder:

True & True = True
True & True = True
True & False = False
False & True = False
False & True = False
False & True = False
False & True = False
False & True = False

but I would have preferred it to have stopped sooner. I've tried this with everything imaginable in place of the foldl and with && in place of andy but it never seems to get the hint.

It seems to me that the line andy False _ = False doesn't invite the compiler to evaluate the second parameter. I haven't forced any strictness. What's going on? Even C can do better.

Body:
tandy is strict in both parameters, even though andy is not. This is because of the tracing. You ask it to show both inputs in the call to trace, so it has to evaluate both arguments.

Consider `tandy2':

tandy2 :: Bool -> Bool -> Bool
tandy2 False _ = trace ("False & anything = False") False
tandy2 True b = trace ("True & " ++ show b ++ " = False") b

Instead of blindly evaluating both arguments in its tracing, it is careful to only evaluate the same arguments it would otherwise. This makes it actually reflect the same strictness properties as andy has.

Try using tandy2 with foldr and you'll see it stops evaluating as soon as it hits a False.

$ ghci
GHCi, version 9.2.1: https://www.haskell.org/ghc/  :? for help
ghci> import Debug.Trace
ghci> let tandy2 False _ = trace ("False & anything = False") False ; tandy2 True b = trace ("True & " ++ show b ++ " = False") b
ghci> foldr tandy2 True []
True
ghci> foldr tandy2 True [True]
True & True = False
True
ghci> foldr tandy2 True [True, False]
False & anything = False
True & False = False
False
ghci> foldr tandy2 True [True, False, True]
False & anything = False
True & False = False
False

There you go. It never evaluates the False branch more than once.


问:
SwiftUI passing an observed object into a new view and getting updates
I am very new to swift working on my first app and having trouble having a view update. I am passing an object into a new view, however the new view does not update when there is change in the Firebase Database. Is there a way to get updates on the Gridview? I though by passing the observed object from the StyleboardView it would update the GridView however Gridview does not update. I am having trouble finding a way for the new Gridview to update and reload the images.</p>
```<code>struct StyleBoardView: View {

@State private var showingSheet = false
@ObservedObject var model = ApiModel()
@State var styleboardname = ""

let userEmail = Auth.auth().currentUser?.email

var body: some View {
    NavigationView {
        VStack {
            Text("Select Style Board")
            List (model.list) {item in
                Button(item.styleboardname) {
                            showingSheet.toggle()
                        }
                        .sheet(isPresented: $showingSheet) {
                            GridView(item: item)
                        }
            }

struct GridView: View {
var item: Todo
@ObservedObject var model = ApiModel()
@State var newImage = ""
@State var loc = ""
@State var shouldShowImagePicker = false
@State var image: UIImage?

var body: some View {
    NavigationView {
        var posts = item.styleboardimages

        VStack(alignment: .leading){
            Text(item.styleboardname)
                    GeometryReader{ geo in
                        LazyVGrid(columns: [
                            GridItem(.flexible()),
                            GridItem(.flexible()),
                            GridItem(.flexible())
                        ], spacing: 3 ){
                            ForEach(posts.sorted(by: <), id: \.key) { key, value in
                                if #available(iOS 15.0, *) {
                                    AsyncImage(url: URL(string: value), transaction: Transaction(animation: .spring())) { phase in
                                        switch phase {
                                        case .empty:
                                            Color.purple.opacity(0.1)

                                        case .success(let image):
                                            image
                                                .resizable()
                                                .scaledToFill()

                                        case .failure(_):
                                            Image(systemName: "exclamationmark.icloud")
                                                .resizable()
                                                .scaledToFit()

                                        @unknown default:
                                            Image(systemName: "exclamationmark.icloud")
                                        }
                                    }
                                    .frame(width: 100, height: 100)
                                    .cornerRadius(20)
</code>```

答:
The problem is that you're initializing the model in an ObservedObject, and passing it down to another initialized Observed Object.

What you actually wanna do is use an @StateObject for where you initialize the model. And then use @ObservedObject with the type of the model you're passing down so that:

struct StyleBoardView: View {
@StateObject var model = ApiModel()

/** Code **/

struct GridView: View {
@ObservedObject var model: ApiModel
```

Notice the difference, an @ObservedObject should never initialize the model, it should only "inherit" (@ObservedObject var model: ApiModel) a model from a parent View, in this case, ApiModel.

Body:
I am very new to swift working on my first app and having trouble having a view update. I am passing an object into a new view, however the new view does not update when there is change in the Firebase Database. Is there a way to get updates on the Gridview? I though by passing the observed object from the StyleboardView it would update the GridView however Gridview does not update. I am having trouble finding a way for the new Gridview to update and reload the images.

struct StyleBoardView: View {

@State private var showingSheet = false
@ObservedObject var model = ApiModel()
@State var styleboardname = ""

let userEmail = Auth.auth().currentUser?.email

var body: some View {
    NavigationView {
        VStack {
            Text("Select Style Board")
            List (model.list) {item in
                Button(item.styleboardname) {
                            showingSheet.toggle()
                        }
                        .sheet(isPresented: $showingSheet) {
                            GridView(item: item)
                        }
            }

struct GridView: View {
var item: Todo
@ObservedObject var model = ApiModel()
@State var newImage = ""
@State var loc = ""
@State var shouldShowImagePicker = false
@State var image: UIImage?

var body: some View {
    NavigationView {
        var posts = item.styleboardimages

        VStack(alignment: .leading){
            Text(item.styleboardname)
                    GeometryReader{ geo in
                        LazyVGrid(columns: [
                            GridItem(.flexible()),
                            GridItem(.flexible()),
                            GridItem(.flexible())
                        ], spacing: 3 ){
                            ForEach(posts.sorted(by: <), id: \.key) { key, value in
                                if #available(iOS 15.0, *) {
                                    AsyncImage(url: URL(string: value), transaction: Transaction(animation: .spring())) { phase in
                                        switch phase {
                                        case .empty:
                                            Color.purple.opacity(0.1)

                                        case .success(let image):
                                            image
                                                .resizable()
                                                .scaledToFill()

                                        case .failure(_):
                                            Image(systemName: "exclamationmark.icloud")
                                                .resizable()
                                                .scaledToFit()

                                        @unknown default:
                                            Image(systemName: "exclamationmark.icloud")
                                        }
                                    }
                                    .frame(width: 100, height: 100)
                                    .cornerRadius(20)

Body:
The problem is that you're initializing the model in an ObservedObject, and passing it down to another initialized Observed Object.

What you actually wanna do is use an @StateObject for where you initialize the model. And then use @ObservedObject with the type of the model you're passing down so that:

struct StyleBoardView: View {
@StateObject var model = ApiModel()

/** Code **/

struct GridView: View {
@ObservedObject var model: ApiModel

Notice the difference, an @ObservedObject should never initialize the model, it should only "inherit" (@ObservedObject var model: ApiModel) a model from a parent View, in this case, ApiModel.