问:
why i am getting an error of incorrect integer value on age? while i am using the correct data type and values in it?
```<code>insert into  `patient` ( `pat_f_name`, `pat_l_name`, `pat_gender`, `pat_age`, `pat_dob`, `pat_blood_grp`, `pat_weight`, `pat_contact_no`, `pat_address` )
    ->  VALUES
    ->  ('$user_fname','$user_lname','$user_gender','$user_age','$user_dob','$user_bg','$user_weight','$user_contact_no','$user_address');
</code>```

ERROR 1366 (HY000): Incorrect integer value: '$user_age' for column 'pat_age' at row 1

the table looks like

```<code>+----------------+-------------+------+-----+---------+----------------+
| Field          | Type        | Null | Key | Default | Extra          |
+----------------+-------------+------+-----+---------+----------------+
| pat_id         | int(50)     | NO   | PRI | NULL    | auto_increment |
| dr_id          | int(50)     | NO   |     | NULL    |                |
| pat_f_name     | char(20)    | NO   |     | NULL    |                |
| pat_l_name     | char(20)    | NO   |     | NULL    |                |
| pat_gender     | char(20)    | NO   |     | NULL    |                |
| pat_age        | int(20)     | NO   |     | NULL    |                |
| pat_dob        | date        | NO   |     | NULL    |                |
| pat_blood_grp  | varchar(10) | NO   |     | NULL    |                |
| pat_weight     | int(10)     | NO   |     | NULL    |                |
| pat_contact_no | varchar(12) | NO   |     | NULL    |                |
| pat_address    | varchar(20) | NO   |     | NULL    |                |
+----------------+-------------+------+-----+---------+----------------+
</code>```

答:
```<code>$sql = "INSERT INTO patient(pat_f_name, pat_l_name, pat_gender, pat_age, pat_dob, pat_blood_grp, pat_weight, pat_contact_no, pat_address) VALUES ('$user_fname','$user_lname','$user_gender','$user_age','$user_dob','$user_bg','$user_weight','$user_contact_no','$user_address')";
</code>```

Body:
insert into  `patient` ( `pat_f_name`, `pat_l_name`, `pat_gender`, `pat_age`, `pat_dob`, `pat_blood_grp`, `pat_weight`, `pat_contact_no`, `pat_address` )
    ->  VALUES
    ->  ('$user_fname','$user_lname','$user_gender','$user_age','$user_dob','$user_bg','$user_weight','$user_contact_no','$user_address');

ERROR 1366 (HY000): Incorrect integer value: '$user_age' for column 'pat_age' at row 1

the table looks like

+----------------+-------------+------+-----+---------+----------------+
| Field          | Type        | Null | Key | Default | Extra          |
+----------------+-------------+------+-----+---------+----------------+
| pat_id         | int(50)     | NO   | PRI | NULL    | auto_increment |
| dr_id          | int(50)     | NO   |     | NULL    |                |
| pat_f_name     | char(20)    | NO   |     | NULL    |                |
| pat_l_name     | char(20)    | NO   |     | NULL    |                |
| pat_gender     | char(20)    | NO   |     | NULL    |                |
| pat_age        | int(20)     | NO   |     | NULL    |                |
| pat_dob        | date        | NO   |     | NULL    |                |
| pat_blood_grp  | varchar(10) | NO   |     | NULL    |                |
| pat_weight     | int(10)     | NO   |     | NULL    |                |
| pat_contact_no | varchar(12) | NO   |     | NULL    |                |
| pat_address    | varchar(20) | NO   |     | NULL    |                |
+----------------+-------------+------+-----+---------+----------------+


来源: stackexchange

问:
How can I populate a choice box with an array of objects in Java?
I have a choice box in my GUI

```<code>Choice choice = new Choice();
choice.setBounds(75, 11, 93, 20);
panel.add(choice);
</code>```

I also have this array of objects:

```<code>public Planet[] planetList;
</code>```

every

Planet

has a name field. I'd like to populate the choice box with my planetList and display the name field, so when the users choice the planet by name, it selects the Object Planet that has that name.

If it's easier, I could use a combobox or whatever I could use as a dropdown list of my array.

答:
To create java.awt.Choice:

```<code>Choice fruitChoice = new Choice();
</code>```

To fill in the choices:

```<code>  fruitChoice.add("Apple");
  fruitChoice.add("Grapes");
  fruitChoice.add("Mango");
  fruitChoice.add("Peer");
</code>```

To get the selected item:

```<code>String fruit = fruitChoice.getItem(fruitChoice.getSelectedIndex());
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a choice box in my GUI

Choice choice = new Choice();
choice.setBounds(75, 11, 93, 20);
panel.add(choice);

I also have this array of objects:

public Planet[] planetList;

every

Planet

has a name field. I'd like to populate the choice box with my planetList and display the name field, so when the users choice the planet by name, it selects the Object Planet that has that name.

If it's easier, I could use a combobox or whatever I could use as a dropdown list of my array.

Body:
To create java.awt.Choice:

Choice fruitChoice = new Choice();

To fill in the choices:

  fruitChoice.add("Apple");
  fruitChoice.add("Grapes");
  fruitChoice.add("Mango");
  fruitChoice.add("Peer");

To get the selected item:

String fruit = fruitChoice.getItem(fruitChoice.getSelectedIndex());


问:
Creation of PDF file using itextSharp
Hi
 I am creating an ASP.net website where some articles can be uploaded. I need that my users can get PDF version of it by clicking on a button. For this functionality I am using itextSharp.
    I am considering the following two options.
1. I will create the PDF file once(on first request) and reuse it always by checking for the existence of it.
2. I will create it on the fly and delete it as soon as the PDF file is delivered to the client.
The first approach will lead to faster PDF delivery where as the second approach will lead to saving space. Can anyone please tell me which of the options is better?

I am also wondering if this can be possible without saving the PDF on the server in the first place. So can anyone reply me as soon as possible.

Thanks
Dipa

答:
If you are using iTextSharp it can't be possible to create it on the fly. So the second option seems to be good. If you want to reduce the server space used you can run some windows service which will delete all /  the less used PDFs from the server.

It can solve both of your problem i think.

ContentLicense: CC BY-SA 2.5

Title: Creation of PDF file using itextSharp


问:
Apply all filter functions to a value
I have a function that looks like this:

```<code>def createBuilder(builder: InitialBuilder, name: Option[String], useCache: Boolean, timeout: Option[Long]): Builder = {
    val filters: List[Builder => Option[Builder]] = List(
      b => name.map(b.withName),
      b => if (useCache) Some(b.withCache) else None,
      b => timeout.map(b.withTimeout))

    filters.foldLeft(builder)((b,filter) => filter(b).getOrElse(b))
}
</code>```

It defines 3 filter functions from Builder => Option[Builder] (converting from optional parameters). I want to apply them to an existing builder value, so in case of a None, I can return itself, unchanged.

The code above is the best I could come up with, but it feels that I should somehow be able to do this with a Monoid - return the identity in case of a None.

Unfortunately, I can't figure out how to define one that makes sense. Or, if there's a better/different way of doing this?

I'm using Cats, if that matters. Any ideas?

答:
I think in your case A => M[A] structure is a bit superfluous. The filter functions you use in the example are actually equivalent to Option[Builder => Builder]. That's because you don't use their Builder argument to decide whether the result should be Some or None. And you can further simplify the functions to Builder => Builder with .getOrElse(identity).

Here are 2 implementations that use this idea. They don't even really rely on cats.

```<code>def createBuilder(
  builder: InitialBuilder, name: Option[String], useCache: Boolean, timeout: Option[Long]
): Builder = {
  def builderStage[T](param: Option[T])(modify: T => Builder => Builder): Builder => Builder =
    param.fold(identity[Builder](_))(modify)

  val stages: List[Builder => Builder] = List(
    builderStage(name)(n => _ withName n),
    // `Boolean` is equivalent to `Option[Unit]`, and we convert it to that representation
    // Haskell has a special function to do such a conversion `guard`.
    // In Scalaz you can use an extension method `useCache.option(())`.
    // In cats a similar `option` is provided in Mouse library.
    // But you can just write this manually or define your own extension
    builderStage(if (useCache) ().some else none)(_ => _.withCache),
    builderStage(timeout)(t => _ withTimeout t)
  )

  // It should be possible to use `foldK` method in cats, to do a similar thing.
  // The problems are that it may be more esoteric and harder to understand,
  // it seems you have to provide type arguments even with -Ypartial-unification,
  // it folds starting from the last function, because it's based on `compose`.
  // Anyway, `reduceLeft(_ andThen _)` works fine for a list of plain functions.
  stages.reduceLeft(_ andThen _)(builder)
}
</code>```

Another possibility is to flatten the List of Options, which simply removes Nones without coercing them to identity:

```<code>def createBuilder2(
  builder: InitialBuilder, name: Option[String], useCache: Boolean, timeout: Option[Long]
): Builder = {
  val stages: List[Option[Builder => Builder]] = List(
    name.map(n => _ withName n),
    if (useCache) Some(_.withCache) else None,
    timeout.map(t => _ withTimeout t)
  )

  stages.flatten.reduceLeft(_ andThen _)(builder)
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Apply all filter functions to a value

Body:
I have a function that looks like this:

def createBuilder(builder: InitialBuilder, name: Option[String], useCache: Boolean, timeout: Option[Long]): Builder = {
    val filters: List[Builder => Option[Builder]] = List(
      b => name.map(b.withName),
      b => if (useCache) Some(b.withCache) else None,
      b => timeout.map(b.withTimeout))

    filters.foldLeft(builder)((b,filter) => filter(b).getOrElse(b))
}

It defines 3 filter functions from Builder => Option[Builder] (converting from optional parameters). I want to apply them to an existing builder value, so in case of a None, I can return itself, unchanged.

The code above is the best I could come up with, but it feels that I should somehow be able to do this with a Monoid - return the identity in case of a None.

Unfortunately, I can't figure out how to define one that makes sense. Or, if there's a better/different way of doing this?

I'm using Cats, if that matters. Any ideas?

Body:
I think in your case A => M[A] structure is a bit superfluous. The filter functions you use in the example are actually equivalent to Option[Builder => Builder]. That's because you don't use their Builder argument to decide whether the result should be Some or None. And you can further simplify the functions to Builder => Builder with .getOrElse(identity).

Here are 2 implementations that use this idea. They don't even really rely on cats.

def createBuilder(
  builder: InitialBuilder, name: Option[String], useCache: Boolean, timeout: Option[Long]
): Builder = {
  def builderStage[T](param: Option[T])(modify: T => Builder => Builder): Builder => Builder =
    param.fold(identity[Builder](_))(modify)

  val stages: List[Builder => Builder] = List(
    builderStage(name)(n => _ withName n),
    // `Boolean` is equivalent to `Option[Unit]`, and we convert it to that representation
    // Haskell has a special function to do such a conversion `guard`.
    // In Scalaz you can use an extension method `useCache.option(())`.
    // In cats a similar `option` is provided in Mouse library.
    // But you can just write this manually or define your own extension
    builderStage(if (useCache) ().some else none)(_ => _.withCache),
    builderStage(timeout)(t => _ withTimeout t)
  )

  // It should be possible to use `foldK` method in cats, to do a similar thing.
  // The problems are that it may be more esoteric and harder to understand,
  // it seems you have to provide type arguments even with -Ypartial-unification,
  // it folds starting from the last function, because it's based on `compose`.
  // Anyway, `reduceLeft(_ andThen _)` works fine for a list of plain functions.
  stages.reduceLeft(_ andThen _)(builder)
}

Another possibility is to flatten the List of Options, which simply removes Nones without coercing them to identity:

def createBuilder2(
  builder: InitialBuilder, name: Option[String], useCache: Boolean, timeout: Option[Long]
): Builder = {
  val stages: List[Option[Builder => Builder]] = List(
    name.map(n => _ withName n),
    if (useCache) Some(_.withCache) else None,
    timeout.map(t => _ withTimeout t)
  )

  stages.flatten.reduceLeft(_ andThen _)(builder)
}


问:
Text expands outside the div it's inside?
I've got this code:

```<code><html>
<head>
<style type="text/css">

body {
    text-align: center;
}

#content {
    width: 60em;
    margin: 0, auto;
    background-color: #CCC;
}

</style>
</head>

<body>
<center>
<div id="content">kdsjlglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgkhlglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgklglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgklglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgklglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgklglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgklglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgklglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgkkjdghkdsfjgksdjfhg</div>
</center>
</body>

</html>
</code>```

Why does the text not stay inside the div, but go in a single line until it ends? I want it to have line breaks relative to the div it's inside. How can I do this?

答:
Example on jsFiddle

```<code>#content { word-wrap: break-word; }
</code>```

Body:
I've got this code:

kdsjlglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgkhlglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgklglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgklglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgklglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgklglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgklglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgklglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgkkjdghkdsfjgksdjfhg

Why does the text not stay inside the div, but go in a single line until it ends? I want it to have line breaks relative to the div it's inside. How can I do this?

Body:
Example on jsFiddle

#content { word-wrap: break-word; }


问:
c# mvc form: how to build view for simple feedback form leveraging the benefit of using html.editorfor?
I have simple input form (basically for feedback) with following fields:
Name, Gender, Mobile-Number, Complaint text. (To simplify I am not mentioning any POST action OR submit button on the form)

Currently, I have created following MVC structure:

```<code>public class ComplaintController
{
    [HttpGet]
    public ActionResult Index()
    {
       return View(); //This view displays the complaint form with all above fields
    }
}
</code>```

I read this and several other links where they suggest to use @Html.EditorFor as it creates UI based on model data-type.

Currently, I am not passing any model to the [HttpGet] view. If I want to use @Html.EditorFor, I need to pass my model to [HttpGet] Index View, how can I do that? What is best pratise to create such MVC forms?

答:
Your Controller:

```<code>    public ActionResult Index()
    {
        whateverModel d = new whateverModel();
        return View(d);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Index(whateverModel m)
    {

        if (ModelState.IsValid)
        {

           //its valid, update your database or do soemthing useful here
           return RedirectToAction("Success");
        }
        //its not valid reload the page and let data annotations show the error
        return View(m);
    }
</code>```

Once you have your code in the controller then you can have visual studio auto-create your view. In your controller, right click the "d" in return View(d); and select "Add View." Change the Template to "create" and Model class to your Model (whateverModel in this example). It will auto generate the chtml page for you with the model imported and the editors already generated for you. Example auto generated view below. The you can work on styling and such.

cshtml:

```<code>    @model YourSolution.Models.whateverModel

    @{
        ViewBag.Title = "Whatever";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }

    <h2>Whatever</h2>

    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()

        <div class="form-horizontal">
            <h4>Whatever</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.FriendlyName, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.FriendlyName, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.FriendlyName, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.Order, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Order, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Order, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Create" class="btn btn-default" />
                </div>
            </div>
        </div>
    }

    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
</code>```

Body:
I have simple input form (basically for feedback) with following fields:
Name, Gender, Mobile-Number, Complaint text. (To simplify I am not mentioning any POST action OR submit button on the form)

Currently, I have created following MVC structure:

public class ComplaintController
{
    [HttpGet]
    public ActionResult Index()
    {
       return View(); //This view displays the complaint form with all above fields
    }
}

I read this and several other links where they suggest to use @Html.EditorFor as it creates UI based on model data-type.

Currently, I am not passing any model to the [HttpGet] view. If I want to use @Html.EditorFor, I need to pass my model to [HttpGet] Index View, how can I do that? What is best pratise to create such MVC forms?

Body:
Your Controller:

    public ActionResult Index()
    {
        whateverModel d = new whateverModel();
        return View(d);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Index(whateverModel m)
    {

        if (ModelState.IsValid)
        {

           //its valid, update your database or do soemthing useful here
           return RedirectToAction("Success");
        }
        //its not valid reload the page and let data annotations show the error
        return View(m);
    }

Once you have your code in the controller then you can have visual studio auto-create your view. In your controller, right click the "d" in return View(d); and select "Add View." Change the Template to "create" and Model class to your Model (whateverModel in this example). It will auto generate the chtml page for you with the model imported and the editors already generated for you. Example auto generated view below. The you can work on styling and such.

cshtml:

    @model YourSolution.Models.whateverModel

    @{
        ViewBag.Title = "Whatever";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }

    <h2>Whatever</h2>

    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()

        <div class="form-horizontal">
            <h4>Whatever</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.FriendlyName, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.FriendlyName, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.FriendlyName, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.Order, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Order, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Order, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Create" class="btn btn-default" />
                </div>
            </div>
        </div>
    }

    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>


问:
Routes not working after setting up HTTPS with Express
Im trying to set up my app with an HTTPS connection. After setting it up, Express stop routing requests that were coming in.

```<code>var path = require('path');
var express = require('express');
var https = require('https');
var fs = require('fs');

var options = {
  key: fs.readFileSync('ssl-key.pem'),
  cert: fs.readFileSync('ssl-cert.pem')
}

var app = express();
var port = process.env.PORT || 3000;

https.createServer(options, app).listen(port, function() {
  console.log('listening on port ' + port);
});

app.get('*', function(req, res) {
  console.log('test');
  res.send('hello world')
});
</code>```

I keep getting ERR_EMPTY_RESPONSE

Does anyone know why this is?

Thank you for your time!

答: The issue comes, because you use http://127.0.0.1:3000/ or (http://127.0.0.1:3000/), but you need to use https protocol (https://localhost:3000/) certificate for it, to make node.js catch this request

Body:
Im trying to set up my app with an HTTPS connection. After setting it up, Express stop routing requests that were coming in.

var path = require('path');
var express = require('express');
var https = require('https');
var fs = require('fs');

var options = {
  key: fs.readFileSync('ssl-key.pem'),
  cert: fs.readFileSync('ssl-cert.pem')
}

var app = express();
var port = process.env.PORT || 3000;

https.createServer(options, app).listen(port, function() {
  console.log('listening on port ' + port);
});

app.get('*', function(req, res) {
  console.log('test');
  res.send('hello world')
});

I keep getting ERR_EMPTY_RESPONSE

Does anyone know why this is?

Thank you for your time!


问:
Express res.redirect shows content but not downloads
I have and API link what automatically starts downloading file if I follow it in address bar. Let's call it my-third-party-downloading-link-com.

But when in Express framework I set res.redirect(my-third-party-downloading-link-com). I get status code 301 and can see file content in Preview tab in developer tools. But I can't make Browser downloading this file.

My appropriate request handler is following:

```<code>downloadFeed(req, res) {
  const { jobId, platform, fileName } = req.query;
  const host = platform === 'production' ? configs.prodHost :
  configs.stageHost;
  const downloadLink = `${host}/api/v1/feedfile/${jobId}`;

  // I also tried with these headers
  // res.setHeader('Content-disposition', 'attachment;
  //   filename=${fileName}.gz');
  // res.setHeader('Content-Type', 'application/x-gzip');

  res.redirect(downloadLink)
}
</code>```

P.S Now, to solve this problem, I build my-third-party-downloading-link-com on back-end, send it with res.end and then:

```<code>window.open(**my-third-party-downloading-link-com**, '_blank').
</code>```

But I don't like this solution. How can I tell browser to start downloading content form this third-party API ?

答:
According to the documentation, you should use res.download() to force a browser to prompt the user for download.

http://expressjs.com/es/api.html#res.download

Body:
I have and API link what automatically starts downloading file if I follow it in address bar. Let's call it my-third-party-downloading-link-com.

But when in Express framework I set res.redirect(my-third-party-downloading-link-com). I get status code 301 and can see file content in Preview tab in developer tools. But I can't make Browser downloading this file.

My appropriate request handler is following:

downloadFeed(req, res) {
  const { jobId, platform, fileName } = req.query;
  const host = platform === 'production' ? configs.prodHost :
  configs.stageHost;
  const downloadLink = `${host}/api/v1/feedfile/${jobId}`;

  // I also tried with these headers
  // res.setHeader('Content-disposition', 'attachment;
  //   filename=${fileName}.gz');
  // res.setHeader('Content-Type', 'application/x-gzip');

  res.redirect(downloadLink)
}

P.S Now, to solve this problem, I build my-third-party-downloading-link-com on back-end, send it with res.end and then:

window.open(**my-third-party-downloading-link-com**, '_blank').

But I don't like this solution. How can I tell browser to start downloading content form this third-party API ?


问:
Measure Volatility or Stability Of Lists of Floating Point Numbers
Wonder if anyone can help.

I have a set of lists of numbers, around 300 lists in the set, each list of around 200 numbers. What I wish to calculate is the "relative stability" of each list.

For example:

List A: 100,101,103,99,98 - the range is v small - so stable.

List B: 0.3, 0.1, -0.2, 0.1 - again, v small range, so stable.

List C: 0.00003, 0.00002, 0.00007, 0.00008 - stable.

Now, I could use standard deviation - but the values returned by the standard deviation will be relative to the values within each list. So std for list C would be tiny in comparison to std for list A - and therefore numerically not give me a comparable measure of stability/volatility enabling me to meaningfully ask: if list A more or less stable than list C?

So, I wondered if anyone had any suggestions for a measure that will be comparable across such lists?

Many thanks for any help.
R

答:
You could use the standard deviation of the list divided by the mean of the list.

Those measures have the same units so their quotient will be a pure number, without a unit. This scales the variability (standard deviation) to the size of the numbers (mean).

The main difficulty with this is for lists that have both positive and negative numbers, like your List B. The mean could end up being an order of magnitude less that the numbers, exaggerating the stability measure. Worse, the mean could end up being zero, making the measure undefined. I cannot think of any correction that would work well in all cases. The "stability" of a list with both positive and negative numbers is very doubtful and would depend on the context, so I doubt that any general stability measure would work well in all such cases. You would need a variety for different situations.


问:
Very different getopts results with different shells
I did some option parsing in a shell script meant to be insourced in dash and bash, and I got some weird results in bash, so I put the essence of the script in:

./getopts :

```<code>fn()
{
    local verbose opt
    while getopts "v" opt; do
        case "$opt" in v) verbose=1;; ?) return 1;; esac
    done; shift $((OPTIND - 1))
    echo -n "'$verbose' "
}
fn -v; fn -v; fn -v; printf '\n'
</code>```

and ran this with different (local-supporting) shells:

```<code>for sh in bash dash posh zsh; do echo SH=$sh; $sh ./getopts; done
</code>```

The results I got are:

```<code>SH=bash
'1' '' ''
SH=dash
'1' '1' '1'
SH=posh
'1' '' '1'
SH=zsh
'1' '1' '1'
</code>```

What are the reasons for these discrepancies? Is the problem with bash and posh or my script?

答:
You need to set OPTIND back to 1 before the getopts loop, so it will start from the first argument.

In bash, OPTIND is initialized automatically only when the script starts, in zsh and dash it's initialized when entering a function, and restored to its old value when returning from the function. I'm not sure what posh does.

According to the zsh documentation, you can make it act similar to bash by setting the POSIX_BUILTINS option. From the name, I assume the bash behavior is consistent with POSIX requirements, and zsh and dash are conflicting.

Body:
I did some option parsing in a shell script meant to be insourced in dash and bash, and I got some weird results in bash, so I put the essence of the script in:

./getopts :

fn()
{
    local verbose opt
    while getopts "v" opt; do
        case "$opt" in v) verbose=1;; ?) return 1;; esac
    done; shift $((OPTIND - 1))
    echo -n "'$verbose' "
}
fn -v; fn -v; fn -v; printf '\n'

and ran this with different (local-supporting) shells:

for sh in bash dash posh zsh; do echo SH=$sh; $sh ./getopts; done

The results I got are:

SH=bash
'1' '' ''
SH=dash
'1' '1' '1'
SH=posh
'1' '' '1'
SH=zsh
'1' '1' '1'

What are the reasons for these discrepancies? Is the problem with bash and posh or my script?


问:
Handle dynamic parameters in URL in Golang
currently am working on an API Rest in Golang. I have the process to CRUD all the tables. Now someone is asking me to develop an endpoint to search in one of that tables based on the parameters send in the URL. Let's say that this is my struct for that table:

```<code>type Media struct {
    ID                         uint
    Key                   string
    RecordKey           string
    RecordID            string
    SystemMediaKey      string
    MediaObjectID       string
    ChangedByID         string
    ChangedByKey        string
    MediaCategory              string
    MimeType                   string
    ShortDescription           string
    LongDescription            string
    EntryTimestamp             time.Time
    ModificationTimestamp      time.Time
    DeletedAtTimestamp         *time.Time
    MediaModificationTimestamp time.Time
    MediaURL                   string
    MediaHTML                  string
    Order                      int
    Group                      string
    Width                      int
    Height                     int
    ImageSize                  string
    ResourceName               string
    ClassName                  string
    Permission                 *string
    MediaStatus                string
}
</code>```

Now, he can send me all or some of that fields in the URL, the I need to assign that values to my struct to be able to search in the database based on the data assigned to the object.

I am using Gorm to handle everything with the database, gorilla/schema to assign the values on the POST requests and the Julien Schmidt Router. Now,my questions are:

What should I configure in the route to accept dynamic parameters?

How can I assign the values that comes in the URL to the a type Media object?
Thank you!

答:
You could use the reflect package to iterate over the fields and set them by name. Be aware that the reflect package is arduous to use and comes with some dangers of panics if not used properly.

Also be aware that url.Values.Get only returns the first value (see https://godoc.org/net/url#Values.Get for details)

EDIT: I added code to account for the pointers in the struct. They are handled differently.

https://play.golang.org/p/AO4lYx7xka

```<code>package main

import (
    "fmt"
    "net/url"
    "reflect"
    "time"
)

type Media struct {
    ID                         uint
    Key                        string
    RecordKey                  string
    RecordID                   string
    SystemMediaKey             string
    MediaObjectID              string
    ChangedByID                string
    ChangedByKey               string
    MediaCategory              string
    MimeType                   string
    ShortDescription           string
    LongDescription            string
    EntryTimestamp             time.Time
    ModificationTimestamp      time.Time
    DeletedAtTimestamp         *time.Time
    MediaModificationTimestamp time.Time
    MediaURL                   string
    MediaHTML                  string
    Order                      int
    Group                      string
    Width                      int
    Height                     int
    ImageSize                  string
    ResourceName               string
    ClassName                  string
    Permission                 *string
    MediaStatus                string
}

func main() {

    testUrl := "www.example.com/test?MimeType=themimetype&Key=thekey&Permission=admin"

    u, err := url.Parse(testUrl)
    if err != nil {
        fmt.Println(err)
        return
    }

    params := u.Query()

    media := &Media{}

    val := reflect.ValueOf(media)

    for i := 0; i < val.Elem().NumField(); i++ {
        // get the reflect.StructField so we can get the Name
        f := val.Elem().Type().Field(i)

        // check if URL.Values contains the field
        if v := params.Get(f.Name); v != "" {
            // get the reflect.Value associated with the Field
            field := val.Elem().FieldByName(f.Name)

            kind := field.Kind()

            // you must switch for each reflect.Kind (associated with the type in your struct)
            // so you know which Set... method to call
            switch kind {
            case reflect.String:
                field.SetString(v)
            case reflect.Ptr:
                // pointers are a special case that must be handled manually unfortunately.
                // because they default to nil, calling Elem() won't reveal the underlying type
                // so you must simply string match the struct values that are pointers.
                switch f.Name {
                case "Permission":
                    newVal := reflect.New(reflect.TypeOf(v))
                    newVal.Elem().SetString(v)
                    field.Set(newVal.Elem().Addr())
                case "DeletedAtTimestamp":
                }
            }

        }
    }

    fmt.Printf("%#v\n", media)
    fmt.Println(*media.Permission)
}
</code>```

Body:
currently am working on an API Rest in Golang. I have the process to CRUD all the tables. Now someone is asking me to develop an endpoint to search in one of that tables based on the parameters send in the URL. Let's say that this is my struct for that table:

type Media struct {
    ID                         uint
    Key                   string
    RecordKey           string
    RecordID            string
    SystemMediaKey      string
    MediaObjectID       string
    ChangedByID         string
    ChangedByKey        string
    MediaCategory              string
    MimeType                   string
    ShortDescription           string
    LongDescription            string
    EntryTimestamp             time.Time
    ModificationTimestamp      time.Time
    DeletedAtTimestamp         *time.Time
    MediaModificationTimestamp time.Time
    MediaURL                   string
    MediaHTML                  string
    Order                      int
    Group                      string
    Width                      int
    Height                     int
    ImageSize                  string
    ResourceName               string
    ClassName                  string
    Permission                 *string
    MediaStatus                string
}

Now, he can send me all or some of that fields in the URL, the I need to assign that values to my struct to be able to search in the database based on the data assigned to the object.

I am using Gorm to handle everything with the database, gorilla/schema to assign the values on the POST requests and the Julien Schmidt Router. Now,my questions are:

What should I configure in the route to accept dynamic parameters?

How can I assign the values that comes in the URL to the a type Media object?
Thank you!

Body:
You could use the reflect package to iterate over the fields and set them by name. Be aware that the reflect package is arduous to use and comes with some dangers of panics if not used properly.

Also be aware that url.Values.Get only returns the first value (see https://godoc.org/net/url#Values.Get for details)

EDIT: I added code to account for the pointers in the struct. They are handled differently.

https://play.golang.org/p/AO4lYx7xka

package main

import (
    "fmt"
    "net/url"
    "reflect"
    "time"
)

type Media struct {
    ID                         uint
    Key                        string
    RecordKey                  string
    RecordID                   string
    SystemMediaKey             string
    MediaObjectID              string
    ChangedByID                string
    ChangedByKey               string
    MediaCategory              string
    MimeType                   string
    ShortDescription           string
    LongDescription            string
    EntryTimestamp             time.Time
    ModificationTimestamp      time.Time
    DeletedAtTimestamp         *time.Time
    MediaModificationTimestamp time.Time
    MediaURL                   string
    MediaHTML                  string
    Order                      int
    Group                      string
    Width                      int
    Height                     int
    ImageSize                  string
    ResourceName               string
    ClassName                  string
    Permission                 *string
    MediaStatus                string
}

func main() {

    testUrl := "www.example.com/test?MimeType=themimetype&Key=thekey&Permission=admin"

    u, err := url.Parse(testUrl)
    if err != nil {
        fmt.Println(err)
        return
    }

    params := u.Query()

    media := &Media{}

    val := reflect.ValueOf(media)

    for i := 0; i < val.Elem().NumField(); i++ {
        // get the reflect.StructField so we can get the Name
        f := val.Elem().Type().Field(i)

        // check if URL.Values contains the field
        if v := params.Get(f.Name); v != "" {
            // get the reflect.Value associated with the Field
            field := val.Elem().FieldByName(f.Name)

            kind := field.Kind()

            // you must switch for each reflect.Kind (associated with the type in your struct)
            // so you know which Set... method to call
            switch kind {
            case reflect.String:
                field.SetString(v)
            case reflect.Ptr:
                // pointers are a special case that must be handled manually unfortunately.
                // because they default to nil, calling Elem() won't reveal the underlying type
                // so you must simply string match the struct values that are pointers.
                switch f.Name {
                case "Permission":
                    newVal := reflect.New(reflect.TypeOf(v))
                    newVal.Elem().SetString(v)
                    field.Set(newVal.Elem().Addr())
                case "DeletedAtTimestamp":
                }
            }

        }
    }

    fmt.Printf("%#v\n", media)
    fmt.Println(*media.Permission)
}


问:
Raspberry pi camera module enable "Raspistill"
I want to use Raspberry PI's system command raspistillto take images in a c program, the program line is: system("raspistill -q 5 -vf -hf -o pic1.jpg -t 1 -th 0:0:0");

However, when I run the program sometimes error occurs,
it shows that:

mmal_vc_component_enable- failed to enable component- ENOSPC
    mmal- camera component couldn't be enabled
    mmal- main- Failed to create camera component
    mmal- Failed to run camera app. Please check for firmware updatesckquote

And I have tried to add some parameters into /boot/config.txt:

gpu_mem=128   start_file=start_x.elf   fixup_file=fixup_x.dat

  disable_camera_led=1   cam_lwm=16   cam_hwm=32   cam_offline_start=16

However the error still always occurs sometimes (sometimes ok). I really want to solve this problem in order to continue my project. What should I do?

答:
Stop any other processes using the camera (e.g.raspimjpeg)

```<code>$ ps -aux
</code>```

// locate the process pid and kill it using the pid number (e.g. 764)

```<code>$ sudo kill 764
</code>```

Note: You might have more than one process running so be sure to kill them all before trying again.

Body:
Stop any other processes using the camera (e.g.raspimjpeg)

$ ps -aux

// locate the process pid and kill it using the pid number (e.g. 764)

$ sudo kill 764

Note: You might have more than one process running so be sure to kill them all before trying again.


问:
iOS Web App not working properly
I'm trying to make an extremely basic web app for iOS. apple-mobile-web-app-capable does not allow my app to be run in standalone mode. I've followed Apple's own tutorial to set this up and have been surfing the web for a solution for too long at this point. I've tried clearing the cache and re-adding the app. I also tried removing the meta tag and altering it and then setting it back along with removing the bookmark, which was mentioned in another answer and it did nothing for me.

Anybody have a solution?

```<code><DOCTYPE! html>
<html>
  <head>
    <title>Test App</title>
    <meta name="apple-mobile-web-app-title" content="Test App">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <style>
      #testButton {
        -webkit-appearance: none;
        font-size: 500%;
        font-weight: bold;
        width: 100%;
        height: 100%;
      }
    </style>
  </head>
  <body>
    <script>
      function output(){
        alert("window.navigator.standalone = " +  window.navigator.standalone);
      }
    </script>
    <button id="testButton" onclick="output()">Test</button>
  </body>
</html>
</code>```

答:
I've encountered the same issue as you in the past. Apparently web apps don't work as expected since iOS 9 (i believe); however, I've found you can solve it with the tag:

```<code><meta name="viewport" content="width=device-width, initial-scale=1.0, minimal-ui">
<meta name="apple-mobile-app-capable" content="yes">
</code>```

It worked for me, hope it does as well for you ;)

Title: iOS Web App not working properly

Body:
I'm trying to make an extremely basic web app for iOS. apple-mobile-web-app-capable does not allow my app to be run in standalone mode. I've followed Apple's own tutorial to set this up and have been surfing the web for a solution for too long at this point. I've tried clearing the cache and re-adding the app. I also tried removing the meta tag and altering it and then setting it back along with removing the bookmark, which was mentioned in another answer and it did nothing for me.

Anybody have a solution?

<DOCTYPE! html>

    <title>Test App</title>
    <meta name="apple-mobile-web-app-title" content="Test App">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">

    <button id="testButton" onclick="output()">Test</button>

Body:
I've encountered the same issue as you in the past. Apparently web apps don't work as expected since iOS 9 (i believe); however, I've found you can solve it with the tag:

<meta name="viewport" content="width=device-width, initial-scale=1.0, minimal-ui">
<meta name="apple-mobile-app-capable" content="yes">

It worked for me, hope it does as well for you ;)


问:
Understanding methods syntax in Objective-C and Objective-J
I've a simple question about objective-c / objective-j syntax.

This is a method dataForItemsAtIndexes and it gets as parameters a CPIndextSet and CPString.
It should return a CPData object. However I don't understand what's (CPCollectionView)aCollectionView.

```<code>- (CPData)collectionView:(CPCollectionView)aCollectionView
   dataForItemsAtIndexes:(CPIndexSet)indices
                 forType:(CPString)aType
</code>```

Thanks

答: That identifies the CPCollectionView which your implementing data source corresponds to. This is useful in case your view or window has multiple CPCollectionViews, whose data sources are the same object, so it knows which view to provide which data to.

Body:
I've a simple question about objective-c / objective-j syntax.

This is a method dataForItemsAtIndexes and it gets as parameters a CPIndextSet and CPString.
It should return a CPData object. However I don't understand what's (CPCollectionView)aCollectionView.

- (CPData)collectionView:(CPCollectionView)aCollectionView
   dataForItemsAtIndexes:(CPIndexSet)indices
                 forType:(CPString)aType

Thanks


问:
memtier benchmark understanding the output
Hi I am very new to using memtier benchmarking tool for redis. I have ran basic examples and not able to understand the output. Can someone help me to understand the below output.

```<code>Command: memtier_benchmark -s 172.25.1.100 -p 6380 -c 50 -t 100 -n 1000 -d 1000000 --ratio=1:1 --pipeline=1 --key-pattern S:S -P redis
</code>```

Output:

```<code>100       Threads
50        Connections per thread
1000      Requests per thread
Type        Ops/sec     Hits/sec   Misses/sec      Latency       KB/sec
------------------------------------------------------------------------
Sets         748.28          ---          ---   6475.61800    730780.68
Gets         748.28         0.00       748.28    208.12400        22.57
Waits          0.00          ---          ---      0.00000          ---
Totals      1496.57         0.00       748.28   3341.87100    730803.25
</code>```

答:
The output you have posted means that

You used 100 threads (-t specifies the number of threads used)

Each thread used 50 connections to the redis db (-c 50)

Each connection sent 1000 requests (-n 1000)

You redis server can perform 748.28 SET and GET operations.

The size of the requests is specified on the right and shows that
the SET requests are quite large and have a very high latency (in milli seconds) compared to the GET requests.

In total you can run 1496.57 ops/sec against your redis server.

If this doesn't answer your question then be specific with what you couldn't understand.

Body:
Hi I am very new to using memtier benchmarking tool for redis. I have ran basic examples and not able to understand the output. Can someone help me to understand the below output.

Command: memtier_benchmark -s 172.25.1.100 -p 6380 -c 50 -t 100 -n 1000 -d 1000000 --ratio=1:1 --pipeline=1 --key-pattern S:S -P redis

Output:

100       Threads
50        Connections per thread
1000      Requests per thread
Type        Ops/sec     Hits/sec   Misses/sec      Latency       KB/sec
------------------------------------------------------------------------
Sets         748.28          ---          ---   6475.61800    730780.68
Gets         748.28         0.00       748.28    208.12400        22.57
Waits          0.00          ---          ---      0.00000          ---
Totals      1496.57         0.00       748.28   3341.87100    730803.25


问:
hrefs with anchor scroll inside a dropdown
I have a drop-down like so:

```<code><div class="dropdown">
        <select>
            <option ng-repeat="i in sc.cl" value="{{i.deptname"}}><a ng-href="#{{i.id}}">{{i.deptname}}</a></option>
        </select>
</div>
</code>```

Basically, the dropdown element's name is inside an array and there are divs inside the html having the id as i.id like this:

```<code><div class="right-bar">
                <section class="contact-block" ng-repeat="i in sc.cl" id="{{i.id}}">
                    <div class="description">{{i.deptname}}</div>
                    <div class="inner-block">
                        <div ng-repeat="j in i.cgs">
                            <img class="vertical-image" src="frame.png">
                            <img class="horizontal-image" src="mobileframe.png">
                        </div>
                    </div>
                </section>
            </div>
</code>```

whenever I click the dropdown element, I want it to scroll to the particular section. But nothing happens when I do so. Why does this happen? And when I tried inspect element in chrome, it doesn't even show the  tags in the ng-repeat dropdown.

答:
You should use Angular's $anchorScroll.

Please, take a look at this similar question: How to handle anchor hash linking in AngularJS

Body:
I have a drop-down like so:

        <select>
            <option ng-repeat="i in sc.cl" value="{{i.deptname"}}>{{i.deptname}}</option>
        </select>

Basically, the dropdown element's name is inside an array and there are divs inside the html having the id as i.id like this:

{{i.deptname}}

whenever I click the dropdown element, I want it to scroll to the particular section. But nothing happens when I do so. Why does this happen? And when I tried inspect element in chrome, it doesn't even show the  tags in the ng-repeat dropdown.


问:
Spring Boot, define timezone for Json and java.time.* globally
I'm using Spring Boot 1.5.3, Spring Data REST, HATEOAS to create a REST service.
I use java.time.* date/times in my application and I'm storing that in UTC format in the database.
I want to follow best practice and return UTC dates in my REST endpoints.

Using @JsonFormat I'm able to accomplish to that:

```<code>@JsonFormat(timezone = "UTC", pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ")
@LastModifiedDate
private LocalDateTime lastModifiedDate;
</code>```

I would like to avoid to annotate all my beans with that, and I would prefer to have a global configuration.
According to this enhancemente request, I was able to solve 50% of my problem with this configuration:

```<code>@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
    return new Jackson2ObjectMapperBuilderCustomizer() {

        @Override
        public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
            jacksonObjectMapperBuilder.serializers(
                    new LocalDateTimeSerializer(new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd'T'HH:mm:ss").toFormatter()));
            jacksonObjectMapperBuilder.serializers(new ZonedDateTimeSerializer(
                    new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ").toFormatter()));
        }

    };
}
</code>```

This fix the pattern problem but not the timezone problem. My timezone continue to remain the local timezone.
Is there a graceful way to set the timezone of JSON serializer to UTC like the property spring.jackson.time-zone=UTC that unfortunately work just for java.util.time?

答:
I think you need to set the timezone of your formatter.

See https://github.com/jhipster/generator-jhipster/blob/09f0957b3ac9711fb9dd86f77ad69c549401074f/generators/server/templates/src/main/java/package/config/_JacksonConfiguration.java

```<code>@Configuration
public class JacksonConfiguration {

    public static final DateTimeFormatter ISO_FIXED_FORMAT =
        DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneId.of("Z"));

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jacksonCustomizer() {
        return new Jackson2ObjectMapperBuilderCustomizer() {
            @Override
            public void customize(Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder) {
                jackson2ObjectMapperBuilder.serializers(new ZonedDateTimeSerializer(ISO_FIXED_FORMAT));
            }
        };
    }
}
</code>```

Body:
I'm using Spring Boot 1.5.3, Spring Data REST, HATEOAS to create a REST service.
I use java.time.* date/times in my application and I'm storing that in UTC format in the database.
I want to follow best practice and return UTC dates in my REST endpoints.

Using @JsonFormat I'm able to accomplish to that:

@JsonFormat(timezone = "UTC", pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ")
@LastModifiedDate
private LocalDateTime lastModifiedDate;

I would like to avoid to annotate all my beans with that, and I would prefer to have a global configuration.
According to this enhancemente request, I was able to solve 50% of my problem with this configuration:

@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
    return new Jackson2ObjectMapperBuilderCustomizer() {

        @Override
        public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
            jacksonObjectMapperBuilder.serializers(
                    new LocalDateTimeSerializer(new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd'T'HH:mm:ss").toFormatter()));
            jacksonObjectMapperBuilder.serializers(new ZonedDateTimeSerializer(
                    new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ").toFormatter()));
        }

    };
}

This fix the pattern problem but not the timezone problem. My timezone continue to remain the local timezone.
Is there a graceful way to set the timezone of JSON serializer to UTC like the property spring.jackson.time-zone=UTC that unfortunately work just for java.util.time?

Body:
I think you need to set the timezone of your formatter.

See https://github.com/jhipster/generator-jhipster/blob/09f0957b3ac9711fb9dd86f77ad69c549401074f/generators/server/templates/src/main/java/package/config/_JacksonConfiguration.java

@Configuration
public class JacksonConfiguration {

    public static final DateTimeFormatter ISO_FIXED_FORMAT =
        DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneId.of("Z"));

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jacksonCustomizer() {
        return new Jackson2ObjectMapperBuilderCustomizer() {
            @Override
            public void customize(Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder) {
                jackson2ObjectMapperBuilder.serializers(new ZonedDateTimeSerializer(ISO_FIXED_FORMAT));
            }
        };
    }
}


问:
How to add two json data together in javascript
I have Json Curl Data representing Post and Comments and I  have  successfully retrieved and displayed them one after the other. below is the code for Retrieving Post and comments

```<code>function loadPost(){
    $.post(
        'post.json',
        function(response){
            $.each(JSON.parse(response).items, function(i,v){
                $('.info').append('<li><div class="msg-lhs"><span>'+v.post_id+'</span> <span>'+v.courses+'</span> </div></li>');
            });
        }
   );

   function loadComment(){
       $.post(
           'comment.json',
           function(response){
               $.each(JSON.parse(response).items, function(i,v){
                   $('.info').append('<li><div class="msg-lhs"><span>'+v.post_id+'</span> <span>'+v.comment+'</span> </div></li>');
               });
           }
       );
</code>```

below is the Json Format output for post and comment

```<code>{"items":[{"post_id":"101","courses":"physics"},
{"post_id":"102","courses":"Biology"},
{"post_id":"103","courses":"Chemistry"},
{"post_id":"104","courses":"Geophysics"},
{"post_id":"105","courses":"GeoChemistry"}]}

{"items":[{"post_id":"101","comment":"This  physcis is cool"},
{"post_id":"101","comment":"love this course on physics"},
{"post_id":"102","comment":"Biology is the scientific study of living things"},
{"post_id":"103","comment":"chemistry is good"},
{"post_id":"103","comment":"chemistry is the study of matter and compounds etc"}]}
</code>```

Now my problem is how can I append comments directly under posts with same post_id
when displaying json contents in javascript. can someone help me fix that.

Thanks

答:
Try to combine your posts and comments to one data set before appending them to the list element.

Here is an example without using jQuery, but jQuery has similar methods like filter, map and extend. I'm sure you'll get the idea.

var posts = '{"items":[{"post_id":"101","courses":"physics"},{"post_id":"102","courses":"Biology"},{"post_id":"103","courses":"Chemistry"},{"post_id":"104","courses":"Geophysics"},{"post_id":"105","courses":"GeoChemistry"}]}';
var comments = '{"items":[{"post_id":"101","comment":"This  physcis is cool"},{"post_id":"101","comment":"love this course on physics"},{"post_id":"102","comment":"Biology is the scientific study of living things"},{"post_id":"103","comment":"chemistry is good"},{"post_id":"103","comment":"chemistry is the study of matter and compounds etc"}]}';

var list = document.getElementById('info')
// assuming that you have your posts and comments json data
var comments = JSON.parse( comments ).items;
var posts = JSON.parse( posts ).items;

// check if a post has comments
var postHasComments = ( comments, post ) => comments
  .some( comment => comment.post_id === post.post_id )

// get comments for specifig post
var getComments = ( comments, post ) => comments
  .filter( comment => comment.post_id === post.post_id )
  .map( comment => `<span>${ comment.comment }</span>` )

// combine posts with comments
posts.map( post => ( Object.assign( {}, { post_id, courses } = post,
    { comments: ( postHasComments( comments, post ) ) ? getComments( comments, post ) : [] } ) )
)
// append posts with their comments to list
.forEach( item => { list.innerHTML += `

    ${ item.post_id }
    ${ item.courses }
    ${ ( item.comments.length ) ? `<br />${ item.comments.join('<br />') }` : '' }

`
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul id="info"></ul></code>```

Body:
I have Json Curl Data representing Post and Comments and I  have  successfully retrieved and displayed them one after the other. below is the code for Retrieving Post and comments

function loadPost(){
    $.post(
        'post.json',
        function(response){
            $.each(JSON.parse(response).items, function(i,v){
                $('.info').append('

'+v.post_id+' '+v.courses+'

');
            });
        }
   );

   function loadComment(){
       $.post(
           'comment.json',
           function(response){
               $.each(JSON.parse(response).items, function(i,v){
                   $('.info').append('

'+v.post_id+' '+v.comment+'

');
               });
           }
       );

below is the Json Format output for post and comment

{"items":[{"post_id":"101","courses":"physics"},
{"post_id":"102","courses":"Biology"},
{"post_id":"103","courses":"Chemistry"},
{"post_id":"104","courses":"Geophysics"},
{"post_id":"105","courses":"GeoChemistry"}]}

{"items":[{"post_id":"101","comment":"This  physcis is cool"},
{"post_id":"101","comment":"love this course on physics"},
{"post_id":"102","comment":"Biology is the scientific study of living things"},
{"post_id":"103","comment":"chemistry is good"},
{"post_id":"103","comment":"chemistry is the study of matter and compounds etc"}]}

Now my problem is how can I append comments directly under posts with same post_id
when displaying json contents in javascript. can someone help me fix that.

Thanks

Body:
Try to combine your posts and comments to one data set before appending them to the list element.

Here is an example without using jQuery, but jQuery has similar methods like filter, map and extend. I'm sure you'll get the idea.

var posts = '{"items":[{"post_id":"101","courses":"physics"},{"post_id":"102","courses":"Biology"},{"post_id":"103","courses":"Chemistry"},{"post_id":"104","courses":"Geophysics"},{"post_id":"105","courses":"GeoChemistry"}]}';
var comments = '{"items":[{"post_id":"101","comment":"This  physcis is cool"},{"post_id":"101","comment":"love this course on physics"},{"post_id":"102","comment":"Biology is the scientific study of living things"},{"post_id":"103","comment":"chemistry is good"},{"post_id":"103","comment":"chemistry is the study of matter and compounds etc"}]}';

var list = document.getElementById('info')
// assuming that you have your posts and comments json data
var comments = JSON.parse( comments ).items;
var posts = JSON.parse( posts ).items;

// check if a post has comments
var postHasComments = ( comments, post ) => comments
  .some( comment => comment.post_id === post.post_id )

// get comments for specifig post
var getComments = ( comments, post ) => comments
  .filter( comment => comment.post_id === post.post_id )
  .map( comment => `<span>${ comment.comment }</span>` )

// combine posts with comments
posts.map( post => ( Object.assign( {}, { post_id, courses } = post,
    { comments: ( postHasComments( comments, post ) ) ? getComments( comments, post ) : [] } ) )
)
// append posts with their comments to list
.forEach( item => { list.innerHTML += `
<li>
  <div class="msg-lhs" id="${ item.post_id }">
    <span>${ item.post_id }</span>
    <span>${ item.courses }</span>
    ${ ( item.comments.length ) ? `<br />${ item.comments.join('<br />') }` : '' }
  </div>
</li>`
})

<ul id="info"></ul>


问:
Msg 9402, Level 16, State 1, Line 9 XML parsing: line 1, character 38, unable to switch the encoding
A piece of T-SQL doesn't behave the same from Production to Test environment. When the code below is executed on prod it brings back data

```<code>SELECT [col1xml]
FROM [DBName].[dbo].[Table1] (NOLOCK)
WHERE (cast([col1xml] as xml).value('(/Payment/****/trn1)[1]','nvarchar(20)') ='123456'))
</code>```

However that same code brings back the below error when ran in Test.

Msg 9402, Level 16, State 1, Line 9
XML parsing: line 1, character 38, unable to switch the encoding

I have seen the fix provided by this site of conversion of UTF and this works in both prod and test. See below. However I need to provide an answer to the developers of why this behavior is occurring and a rationale why they should change their code(if that is the case)

```<code>WHERE CAST(
REPLACE(CAST(col1xml AS VARCHAR(MAX)), 'encoding="utf-16"', 'encoding="utf-8"')
AS XML).value('(/Payment/****/trn1)[1]','NVARCHAR(max)') ='123456')
</code>```

I have compared both DB's and looked for anything obvious such as ANSI nulls and ANSI padding. Everything is the same and the version of SQL Server. This is SQL Server 2012 11.0.5388 version. Data between environments is different but the table schema is identical and the data type for col1xml is ntext.

答:
In SQL Server you should store XML in a column typed XML. This native type has a got a lot of advantages. It is much faster and has implicit validity checks.

From your question I take, that you store your XML in NTEXT. This type is deprecated for centuries and will not be supported in future versions! You ought to change this soon!

SQL Server knows two kinds of strings:

1 byte strings (CHAR or VARCHAR), which is extended ASCII

Important: This is not UTF-8! Native UTF-8 support will be part of a coming version.

2 byte string (NCHAR or NVARCHAR), which is UTF-16 (UCS-2)

If the XML has a leading declaration with an encoding (in most cases this is utf-8 or utf-16) you can get into trouble.

If the XML is stored as 2-byte-string (at least the NTEXT tells me this), the declaration has to be utf-16. With a 1-byte-string it should be utf-8.

The best (and easiest) was to omit the declaration completely. You do not need it. Storing the XML in the appropriate type will kill this declaration automatically.

What you should do: Create a new column of type XML and shuffle all your XMLs to this column. Get rid of any TEXT, NTEXT and IMAGE columns you might have!

The next step is: Be happy and enjoy the fast and easy going with the native XML type.

UPDATE Differences in environment

Data between environments is different

The error happens here:

```<code>cast([col1xml] as xml)
</code>```

If your column would store the XML in the native type, you would not need a cast (which is very expensive!!) at all. But in your case this cast depends on the actual XML. As this is stored in NTEXT it is 2-byte-string. If your XML starts with a declaration stating a non-supported encoding (in most cases utf-8), this will fail.

Try this which works:

```<code>DECLARE @xml2Byte_UTF16 NVARCHAR(100)='<?xml version="1.0" encoding="utf-16"?><root>test1</root>';
SELECT CAST(@xml2Byte_UTF16 AS XML);

DECLARE @xml1Byte_UTF8 VARCHAR(100)='<?xml version="1.0" encoding="utf-8"?><root>test2</root>';
SELECT CAST(@xml1Byte_UTF8 AS XML);
</code>```

This fails

```<code>DECLARE @xml2Byte_UTF8 NVARCHAR(100)='<?xml version="1.0" encoding="utf-8"?><root>test3</root>';
SELECT CAST(@xml2Byte_UTF8 AS XML);

DECLARE @xml1Byte_UTF16 VARCHAR(100)='<?xml version="1.0" encoding="utf-16"?><root>test4</root>';
SELECT CAST(@xml1Byte_UTF16 AS XML);
</code>```

Play around with VARCHAR and NVARCHAR and utf-8 and utf-16...

Body:
A piece of T-SQL doesn't behave the same from Production to Test environment. When the code below is executed on prod it brings back data

SELECT [col1xml]
FROM [DBName].[dbo].[Table1] (NOLOCK)
WHERE (cast([col1xml] as xml).value('(/Payment/****/trn1)[1]','nvarchar(20)') ='123456'))

However that same code brings back the below error when ran in Test.

Msg 9402, Level 16, State 1, Line 9
XML parsing: line 1, character 38, unable to switch the encoding

I have seen the fix provided by this site of conversion of UTF and this works in both prod and test. See below. However I need to provide an answer to the developers of why this behavior is occurring and a rationale why they should change their code(if that is the case)

WHERE CAST(
REPLACE(CAST(col1xml AS VARCHAR(MAX)), 'encoding="utf-16"', 'encoding="utf-8"')
AS XML).value('(/Payment/****/trn1)[1]','NVARCHAR(max)') ='123456')

I have compared both DB's and looked for anything obvious such as ANSI nulls and ANSI padding. Everything is the same and the version of SQL Server. This is SQL Server 2012 11.0.5388 version. Data between environments is different but the table schema is identical and the data type for col1xml is ntext.

Body:
In SQL Server you should store XML in a column typed XML. This native type has a got a lot of advantages. It is much faster and has implicit validity checks.

From your question I take, that you store your XML in NTEXT. This type is deprecated for centuries and will not be supported in future versions! You ought to change this soon!

SQL Server knows two kinds of strings:

1 byte strings (CHAR or VARCHAR), which is extended ASCII

Important: This is not UTF-8! Native UTF-8 support will be part of a coming version.

2 byte string (NCHAR or NVARCHAR), which is UTF-16 (UCS-2)

If the XML has a leading declaration with an encoding (in most cases this is utf-8 or utf-16) you can get into trouble.

If the XML is stored as 2-byte-string (at least the NTEXT tells me this), the declaration has to be utf-16. With a 1-byte-string it should be utf-8.

The best (and easiest) was to omit the declaration completely. You do not need it. Storing the XML in the appropriate type will kill this declaration automatically.

What you should do: Create a new column of type XML and shuffle all your XMLs to this column. Get rid of any TEXT, NTEXT and IMAGE columns you might have!

The next step is: Be happy and enjoy the fast and easy going with the native XML type.

UPDATE Differences in environment

Data between environments is different

The error happens here:

cast([col1xml] as xml)

If your column would store the XML in the native type, you would not need a cast (which is very expensive!!) at all. But in your case this cast depends on the actual XML. As this is stored in NTEXT it is 2-byte-string. If your XML starts with a declaration stating a non-supported encoding (in most cases utf-8), this will fail.

Try this which works:

DECLARE @xml2Byte_UTF16 NVARCHAR(100)='<?xml version="1.0" encoding="utf-16"?><root>test1</root>';
SELECT CAST(@xml2Byte_UTF16 AS XML);

DECLARE @xml1Byte_UTF8 VARCHAR(100)='<?xml version="1.0" encoding="utf-8"?><root>test2</root>';
SELECT CAST(@xml1Byte_UTF8 AS XML);

This fails

DECLARE @xml2Byte_UTF8 NVARCHAR(100)='<?xml version="1.0" encoding="utf-8"?><root>test3</root>';
SELECT CAST(@xml2Byte_UTF8 AS XML);

DECLARE @xml1Byte_UTF16 VARCHAR(100)='<?xml version="1.0" encoding="utf-16"?><root>test4</root>';
SELECT CAST(@xml1Byte_UTF16 AS XML);

Play around with VARCHAR and NVARCHAR and utf-8 and utf-16...


问:
Adding two numbers given (digits in Linked List) using Strings
I am trying to add two non negative numbers, the digits of which are stored in reverse order in two separate linked lists. The answer should also be a linked list with digits reversed and no trailing zeros.

I understand that there is a way to solve this question by adding digits and maintaining a carry each time, but I am trying to solve it by using addition operation on numbers.

Here's my code:

```<code>    /**
     * Definition for singly-linked list.
     * class ListNode {
     *     public int val;
     *     public ListNode next;
     *     ListNode(int x) { val = x; next = null; }
     * }
     */
    public class Solution {
        public ListNode addTwoNumbers(ListNode a, ListNode b) {
            if(a==null || b==null){
                return null;

}
        String num1 = "";
        String num2 = "";
        ListNode temp1 = a;
        ListNode temp2 = b;
        while(temp1!=null){
            num1 = num1+Integer.toString(temp1.val);
            temp1 = temp1.next;
        }
        new StringBuilder(num1).reverse().toString();
        double value1 = Double.parseDouble(num1);
        while(temp2!=null){
            num2 = num2+Integer.toString(temp2.val);
            temp2 = temp2.next;
        }
        new StringBuilder(num2).reverse().toString();
        double value2 = Double.parseDouble(num2);
        double result = value1+value2;
        String res = String.format("%.0f",result);
        ListNode first_node =  new ListNode(Character.getNumericValue(res.charAt(0)));
        ListNode ans  = first_node;
        for(int j=1;j<res.length();j++){
            ListNode node = new ListNode(Character.getNumericValue(res.charAt(j)));
            add(node,ans);
        }
        return ans;
    }
    public void add(ListNode node, ListNode ans){
        ListNode temp;
        temp = ans;
        ans  = node;
        ans.next = temp;
    }
}
</code>```

My code has been giving wrong answers. Can anyone point out the errors?

答:
Your approach is not straightforward and wouldn't give you expected results.

Here is a simple approach which wouldn't require much explanation as the addition is simple integer by integer.

Do note that i carry forward when the sum of two integers is greater than 9 else continue with the sum of next integers from both the list.

```<code>class Node {
    private Object data;
    private Node next;
    public Object getData() { return data; }
    public void setData(Object data) {  this.data = data; }
    public Node getNext() { return next; }
    public void setNext(Node next) { this.next = next; }
    public Node(final Object data, final Node next) {
        this.data = data;
        this.next = next;
    }
    @Override
    public String toString() { return "Node:[Data=" + data + "]"; }
}

class SinglyLinkedList {
    Node start;
    public SinglyLinkedList() { start = null; }

    public void addFront(final Object data) {
        // create a reference to the start node with new data
        Node node = new Node(data, start);

        // assign our start to a new node
        start = node;
    }

    public void addRear(final Object data) {
        Node node = new Node(data, null);
        Node current = start;

        if (current != null) {
            while (current.getNext() != null) {
                current = current.getNext();
            }
            current.setNext(node);
        } else {
            addFront(data);
        }
    }

    public void deleteNode(final Object data) {
        Node previous = start;

        if (previous == null) {
            return;
        }

        Node current = previous.getNext();

        if (previous != null && previous.getData().equals(data)) {
            start = previous.getNext();
            previous = current;
            current = previous.getNext();
            return;
        }

        while (current != null) {
            if (current.getData().equals(data)) {
                previous.setNext(current.getNext());
                current = previous.getNext();
            } else {
                previous = previous.getNext();
                current = previous.getNext();
            }
        }
    }

    public Object getFront() {
        if (start != null) {
            return start.getData();
        } else {
            return null;
        }
    }

    public void print() {
        Node current = start;

        if (current == null) {
            System.out.println("SingleLinkedList is Empty");
        }

        while (current != null) {
            System.out.print(current);
            current = current.getNext();
            if (current != null) {
                System.out.print(", ");
            }
        }
    }

    public int size() {
        int size = 0;

        Node current = start;

        while (current != null) {
            current = current.getNext();
            size++;
        }
        return size;
    }

    public Node getStart() {
        return this.start;
    }

    public Node getRear() {
        Node current = start;
        Node previous = current;
        while (current != null) {
            previous = current;
            current = current.getNext();
        }
        return previous;
    }
}

public class AddNumbersInSinglyLinkedList {
    public static void main(String[] args) {
        SinglyLinkedList listOne = new SinglyLinkedList();
        SinglyLinkedList listTwo = new SinglyLinkedList();
        listOne.addFront(5);
        listOne.addFront(1);
        listOne.addFront(3);
        listOne.print();
        System.out.println();
        listTwo.addFront(2);
        listTwo.addFront(9);
        listTwo.addFront(5);
        listTwo.print();
        SinglyLinkedList listThree = add(listOne, listTwo);
        System.out.println();
        listThree.print();
    }

    private static SinglyLinkedList add(SinglyLinkedList listOne, SinglyLinkedList listTwo) {
        SinglyLinkedList result = new SinglyLinkedList();
        Node startOne = listOne.getStart();
        Node startTwo = listTwo.getStart();
        int carry = 0;
        while (startOne != null || startTwo != null) {
            int one = 0;
            int two = 0;
            if (startOne != null) {
                one = (Integer) startOne.getData();
                startOne = startOne.getNext();
            }
            if (startTwo != null) {
                two = (Integer) startTwo.getData();
                startTwo = startTwo.getNext();
            }
            int sum = carry + one + two;
            carry = 0;
            if (sum > 9) {
                carry = sum / 10;
                result.addRear(sum % 10);
            } else {
                result.addRear(sum);
            }
        }
        return result;
    }
}
</code>```

Sample Run

```<code>Node:[Data=3], Node:[Data=1], Node:[Data=5]
Node:[Data=5], Node:[Data=9], Node:[Data=2]
Node:[Data=8], Node:[Data=0], Node:[Data=8]
</code>```

Body:
I am trying to add two non negative numbers, the digits of which are stored in reverse order in two separate linked lists. The answer should also be a linked list with digits reversed and no trailing zeros.

I understand that there is a way to solve this question by adding digits and maintaining a carry each time, but I am trying to solve it by using addition operation on numbers.

Here's my code:

    /**
     * Definition for singly-linked list.
     * class ListNode {
     *     public int val;
     *     public ListNode next;
     *     ListNode(int x) { val = x; next = null; }
     * }
     */
    public class Solution {
        public ListNode addTwoNumbers(ListNode a, ListNode b) {
            if(a==null || b==null){
                return null;

}
        String num1 = "";
        String num2 = "";
        ListNode temp1 = a;
        ListNode temp2 = b;
        while(temp1!=null){
            num1 = num1+Integer.toString(temp1.val);
            temp1 = temp1.next;
        }
        new StringBuilder(num1).reverse().toString();
        double value1 = Double.parseDouble(num1);
        while(temp2!=null){
            num2 = num2+Integer.toString(temp2.val);
            temp2 = temp2.next;
        }
        new StringBuilder(num2).reverse().toString();
        double value2 = Double.parseDouble(num2);
        double result = value1+value2;
        String res = String.format("%.0f",result);
        ListNode first_node =  new ListNode(Character.getNumericValue(res.charAt(0)));
        ListNode ans  = first_node;
        for(int j=1;j<res.length();j++){
            ListNode node = new ListNode(Character.getNumericValue(res.charAt(j)));
            add(node,ans);
        }
        return ans;
    }
    public void add(ListNode node, ListNode ans){
        ListNode temp;
        temp = ans;
        ans  = node;
        ans.next = temp;
    }
}

My code has been giving wrong answers. Can anyone point out the errors?

Body:
Your approach is not straightforward and wouldn't give you expected results.

Here is a simple approach which wouldn't require much explanation as the addition is simple integer by integer.

Do note that i carry forward when the sum of two integers is greater than 9 else continue with the sum of next integers from both the list.

class Node {
    private Object data;
    private Node next;
    public Object getData() { return data; }
    public void setData(Object data) {  this.data = data; }
    public Node getNext() { return next; }
    public void setNext(Node next) { this.next = next; }
    public Node(final Object data, final Node next) {
        this.data = data;
        this.next = next;
    }
    @Override
    public String toString() { return "Node:[Data=" + data + "]"; }
}

class SinglyLinkedList {
    Node start;
    public SinglyLinkedList() { start = null; }

    public void addFront(final Object data) {
        // create a reference to the start node with new data
        Node node = new Node(data, start);

        // assign our start to a new node
        start = node;
    }

    public void addRear(final Object data) {
        Node node = new Node(data, null);
        Node current = start;

        if (current != null) {
            while (current.getNext() != null) {
                current = current.getNext();
            }
            current.setNext(node);
        } else {
            addFront(data);
        }
    }

    public void deleteNode(final Object data) {
        Node previous = start;

        if (previous == null) {
            return;
        }

        Node current = previous.getNext();

        if (previous != null && previous.getData().equals(data)) {
            start = previous.getNext();
            previous = current;
            current = previous.getNext();
            return;
        }

        while (current != null) {
            if (current.getData().equals(data)) {
                previous.setNext(current.getNext());
                current = previous.getNext();
            } else {
                previous = previous.getNext();
                current = previous.getNext();
            }
        }
    }

    public Object getFront() {
        if (start != null) {
            return start.getData();
        } else {
            return null;
        }
    }

    public void print() {
        Node current = start;

        if (current == null) {
            System.out.println("SingleLinkedList is Empty");
        }

        while (current != null) {
            System.out.print(current);
            current = current.getNext();
            if (current != null) {
                System.out.print(", ");
            }
        }
    }

    public int size() {
        int size = 0;

        Node current = start;

        while (current != null) {
            current = current.getNext();
            size++;
        }
        return size;
    }

    public Node getStart() {
        return this.start;
    }

    public Node getRear() {
        Node current = start;
        Node previous = current;
        while (current != null) {
            previous = current;
            current = current.getNext();
        }
        return previous;
    }
}

public class AddNumbersInSinglyLinkedList {
    public static void main(String[] args) {
        SinglyLinkedList listOne = new SinglyLinkedList();
        SinglyLinkedList listTwo = new SinglyLinkedList();
        listOne.addFront(5);
        listOne.addFront(1);
        listOne.addFront(3);
        listOne.print();
        System.out.println();
        listTwo.addFront(2);
        listTwo.addFront(9);
        listTwo.addFront(5);
        listTwo.print();
        SinglyLinkedList listThree = add(listOne, listTwo);
        System.out.println();
        listThree.print();
    }

    private static SinglyLinkedList add(SinglyLinkedList listOne, SinglyLinkedList listTwo) {
        SinglyLinkedList result = new SinglyLinkedList();
        Node startOne = listOne.getStart();
        Node startTwo = listTwo.getStart();
        int carry = 0;
        while (startOne != null || startTwo != null) {
            int one = 0;
            int two = 0;
            if (startOne != null) {
                one = (Integer) startOne.getData();
                startOne = startOne.getNext();
            }
            if (startTwo != null) {
                two = (Integer) startTwo.getData();
                startTwo = startTwo.getNext();
            }
            int sum = carry + one + two;
            carry = 0;
            if (sum > 9) {
                carry = sum / 10;
                result.addRear(sum % 10);
            } else {
                result.addRear(sum);
            }
        }
        return result;
    }
}

Sample Run

Node:[Data=3], Node:[Data=1], Node:[Data=5]
Node:[Data=5], Node:[Data=9], Node:[Data=2]
Node:[Data=8], Node:[Data=0], Node:[Data=8]


问:
Issues using regular expression match in the IF statement in powershell
Input File content is at the bottom. The image shows better the file format.

As you can see from my input file it comes with lots of lines that I don´t need, so I´m trying to tell Powershell to read the content when line matches this pattern (see below). But it´s returning False and not doing what I´d like which is to copy all the content between the regex and the - sign which indicates where the block ends.

Any idea of what I´m doing wrong?

```<code>$InputFile = gc "D:\input_file.txt"
$Dest = "D:\Desktop\Final_file.txt"

#PATTERN I´M LOOKING FOR:
 0000 00XKDPMBBRAXXX00000
 1965 81PWSLKDTRUGXX00000

#REGEX I´VE CREATED BASED ON ABOVE CONTENT
$re = [regex]'(\d{4}\s\d{2}\[a-z]{12}\d{5})'

$file_line_num = 0
$mesg_line_num = 0
$Dest_count     = 0

foreach ($line in $Input_File) {
  $file_line_num = $file_line_num + 1

  # Find where message starts, any other lines are ignored
  if ($line -match $re) {

     [void]$foreach.MoveNext() # skip lines not needed

     $msg_line_num = 0

     do {
        [void]$foreach.MoveNext()
        $line = $foreach.current
        $msg_line_num = $msg_line_num + 1

        if ($msg_line_num -lt 3) {

           $header = $line.substring(7,8) + $line.substring(16, 3)
           add-content $Dest $header

        } else {
           add-content $Dest $line
        }

     } until ($line -eq "-" -or $line -eq $null)
  }
}
Exit
</code>```

```<code>text
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------
TEXTHERE TEXTHERE TEXTHERE
TEXTHERE
.TEXTHERE TEXTHERE TEXTHERE
TEXTHERE TEXTHERE
0000 00XKDPMBBRAXXX00000
1965 81PWSLKDTRUGXX00000
123 99
TEXTHERE
TEXTHERE//TEXTHERE
TEXTHERE
TEXTHERE
TEXTHERE
TEXTHERE//TEXTHERE
TEXTHERE//TEXTHERE
TEXTHERE TEXTHERE
TEXTHERE TEXTHERE
TEXTHERE TEXTHERE
-
=TEXTHERE TEXTHERE
=TEXTHERE TEXTHERE

NNNN++++++++++++++++++++++++++++++++++++
+                                      +
+     -- =TEXTHERE TEXTHERE            +
+      =TEXTHERE TEXTHERE              +
+                                      +
++++++++++++++++++++++++++++++++++++++++

TEXTHERE TEXTHERE TEXTHERE
TEXTHERE
.TEXTHERE TEXTHERE TEXTHERE
TEXTHERE TEXTHERE
0000 00XKDPMBBRAXXX00000
1965 81PWSLKDTRUGXX00000
123 99
TEXTHERE
TEXTHERE//TEXTHERE
TEXTHERE
TEXTHERE
TEXTHERE
TEXTHERE//TEXTHERE
TEXTHERE//TEXTHERE
TEXTHERE TEXTHERE
TEXTHERE TEXTHERE
TEXTHERE TEXTHERE
-
=TEXTHERE TEXTHERE
=TEXTHERE TEXTHERE

NNNN++++++++++++++++++++++++++++++++++++
+                                      +
+     -- =TEXTHERE TEXTHERE            +
+      =TEXTHERE TEXTHERE              +
+                                      +
++++++++++++++++++++++++++++++++++++++++
</code>```

答:
```<code>> select-string .\input_file.txt -Pattern '(\d{4})\s(\d{2}[a-z]{12}\d{5})'

input_file.txt:8:0000 00XKDPMBBRAXXX00000
input_file.txt:9:1965 81PWSLKDTRUGXX00000
input_file.txt:38:0000 00XKDPMBBRAXXX00000
input_file.txt:39:1965 81PWSLKDTRUGXX00000
</code>```

```<code>> select-string .\input_file.txt -Pattern '(\d{4})\s(\d{2}[a-z]{12}\d{5})'|%{$_.matches.captures.value}
0000 00XKDPMBBRAXXX00000
1965 81PWSLKDTRUGXX00000
0000 00XKDPMBBRAXXX00000
1965 81PWSLKDTRUGXX00000
</code>```

```<code>> select-string .\input_file.txt -Pattern '(\d{4})\s(\d{2}[a-z]{12}\d{5})'|%{$_.matches.groups[1,2].value}
0000
00XKDPMBBRAXXX00000
1965
81PWSLKDTRUGXX00000
0000
00XKDPMBBRAXXX00000
1965
81PWSLKDTRUGXX00000
</code>```

Body:
Input File content is at the bottom. The image shows better the file format.

As you can see from my input file it comes with lots of lines that I don´t need, so I´m trying to tell Powershell to read the content when line matches this pattern (see below). But it´s returning False and not doing what I´d like which is to copy all the content between the regex and the - sign which indicates where the block ends.

Any idea of what I´m doing wrong?

$InputFile = gc "D:\input_file.txt"
$Dest = "D:\Desktop\Final_file.txt"

#PATTERN I´M LOOKING FOR:
 0000 00XKDPMBBRAXXX00000
 1965 81PWSLKDTRUGXX00000

#REGEX I´VE CREATED BASED ON ABOVE CONTENT
$re = [regex]'(\d{4}\s\d{2}\[a-z]{12}\d{5})'

$file_line_num = 0
$mesg_line_num = 0
$Dest_count     = 0

foreach ($line in $Input_File) {
  $file_line_num = $file_line_num + 1

  # Find where message starts, any other lines are ignored
  if ($line -match $re) {

     [void]$foreach.MoveNext() # skip lines not needed

     $msg_line_num = 0

     do {
        [void]$foreach.MoveNext()
        $line = $foreach.current
        $msg_line_num = $msg_line_num + 1

        if ($msg_line_num -lt 3) {

           $header = $line.substring(7,8) + $line.substring(16, 3)
           add-content $Dest $header

        } else {
           add-content $Dest $line
        }

     } until ($line -eq "-" -or $line -eq $null)
  }
}
Exit

text
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------
TEXTHERE TEXTHERE TEXTHERE
TEXTHERE
.TEXTHERE TEXTHERE TEXTHERE
TEXTHERE TEXTHERE
0000 00XKDPMBBRAXXX00000
1965 81PWSLKDTRUGXX00000
123 99
TEXTHERE
TEXTHERE//TEXTHERE
TEXTHERE
TEXTHERE
TEXTHERE
TEXTHERE//TEXTHERE
TEXTHERE//TEXTHERE
TEXTHERE TEXTHERE
TEXTHERE TEXTHERE
TEXTHERE TEXTHERE
-
=TEXTHERE TEXTHERE
=TEXTHERE TEXTHERE

NNNN++++++++++++++++++++++++++++++++++++
+                                      +
+     -- =TEXTHERE TEXTHERE            +
+      =TEXTHERE TEXTHERE              +
+                                      +
++++++++++++++++++++++++++++++++++++++++

TEXTHERE TEXTHERE TEXTHERE
TEXTHERE
.TEXTHERE TEXTHERE TEXTHERE
TEXTHERE TEXTHERE
0000 00XKDPMBBRAXXX00000
1965 81PWSLKDTRUGXX00000
123 99
TEXTHERE
TEXTHERE//TEXTHERE
TEXTHERE
TEXTHERE
TEXTHERE
TEXTHERE//TEXTHERE
TEXTHERE//TEXTHERE
TEXTHERE TEXTHERE
TEXTHERE TEXTHERE
TEXTHERE TEXTHERE
-
=TEXTHERE TEXTHERE
=TEXTHERE TEXTHERE

NNNN++++++++++++++++++++++++++++++++++++
+                                      +
+     -- =TEXTHERE TEXTHERE            +
+      =TEXTHERE TEXTHERE              +
+                                      +
++++++++++++++++++++++++++++++++++++++++

Body:
> select-string .\input_file.txt -Pattern '(\d{4})\s(\d{2}[a-z]{12}\d{5})'

input_file.txt:8:0000 00XKDPMBBRAXXX00000
input_file.txt:9:1965 81PWSLKDTRUGXX00000
input_file.txt:38:0000 00XKDPMBBRAXXX00000
input_file.txt:39:1965 81PWSLKDTRUGXX00000

> select-string .\input_file.txt -Pattern '(\d{4})\s(\d{2}[a-z]{12}\d{5})'|%{$_.matches.captures.value}
0000 00XKDPMBBRAXXX00000
1965 81PWSLKDTRUGXX00000
0000 00XKDPMBBRAXXX00000
1965 81PWSLKDTRUGXX00000

> select-string .\input_file.txt -Pattern '(\d{4})\s(\d{2}[a-z]{12}\d{5})'|%{$_.matches.groups[1,2].value}
0000
00XKDPMBBRAXXX00000
1965
81PWSLKDTRUGXX00000
0000
00XKDPMBBRAXXX00000
1965
81PWSLKDTRUGXX00000


问:
Close window when graphics.py object has reached the edge of window
Referring to John Zelle's graphics.py, I want the GraphWin to close right after the Circle object has reached the edge of the window and is out of sight.

Following code creates a circle and moves it:

```<code>win = GraphWin("My Circle", 100, 100)
c = Circle(Point(50,50), 10)
c.draw(win)
    for i in range(40):
      c.move(30, 0) #speed=30
      time.sleep(1)
      #c should move until the end of the windows(100),
win.close() # then windows of title "My Circle" should close immediately
</code>```

Is there any way to do this instead of using range and counting its exact number of 'steps'?

答:
Compare the x position of the left side of the circle against the right side of the window:

```<code>from graphics import *

WIDTH, HEIGHT = 300, 300

RADIUS = 10

SPEED = 30

win = GraphWin("My Circle", WIDTH, HEIGHT)

c = Circle(Point(50, 50), RADIUS)

c.draw(win)

while c.getCenter().x - RADIUS < WIDTH:
    c.move(SPEED, 0)
    time.sleep(1)

win.close() # then windows of title "My Circle" should close immediately
</code>```

In a speedier loop, we might move RADIUS to the other side of the equation and make a new constant of WIDTH + RADIUS.

If it was an Image object, how would you suggest to get the leftmost
  position of the object to compare it to the width of the window?

An Image object would work similarly, using it's anchor, instead of center, and using its width instead of its radius:

```<code>from graphics import *

WIDTH, HEIGHT = 300, 300

SPEED = 30

win = GraphWin("My Image", WIDTH, HEIGHT)

image = Image(Point(50, 50), "file.gif")

image.draw(win)

image_half_width = image.getWidth() / 2

while image.getAnchor().x - image_half_width < WIDTH:
    image.move(SPEED, 0)
    time.sleep(1)

win.close() # the window of title "My Image" should close immediately
</code>```

Body:
Referring to John Zelle's graphics.py, I want the GraphWin to close right after the Circle object has reached the edge of the window and is out of sight.

Following code creates a circle and moves it:

win = GraphWin("My Circle", 100, 100)
c = Circle(Point(50,50), 10)
c.draw(win)
    for i in range(40):
      c.move(30, 0) #speed=30
      time.sleep(1)
      #c should move until the end of the windows(100),
win.close() # then windows of title "My Circle" should close immediately

Is there any way to do this instead of using range and counting its exact number of 'steps'?

Body:
Compare the x position of the left side of the circle against the right side of the window:

from graphics import *

WIDTH, HEIGHT = 300, 300

RADIUS = 10

SPEED = 30

win = GraphWin("My Circle", WIDTH, HEIGHT)

c = Circle(Point(50, 50), RADIUS)

c.draw(win)

while c.getCenter().x - RADIUS < WIDTH:
    c.move(SPEED, 0)
    time.sleep(1)

win.close() # then windows of title "My Circle" should close immediately

In a speedier loop, we might move RADIUS to the other side of the equation and make a new constant of WIDTH + RADIUS.

If it was an Image object, how would you suggest to get the leftmost
  position of the object to compare it to the width of the window?

An Image object would work similarly, using it's anchor, instead of center, and using its width instead of its radius:

from graphics import *

WIDTH, HEIGHT = 300, 300

SPEED = 30

win = GraphWin("My Image", WIDTH, HEIGHT)

image = Image(Point(50, 50), "file.gif")

image.draw(win)

image_half_width = image.getWidth() / 2

while image.getAnchor().x - image_half_width < WIDTH:
    image.move(SPEED, 0)
    time.sleep(1)

win.close() # the window of title "My Image" should close immediately


问:
Create New Column using selected substring(s) from multi-value field
I've got a pretty large (800 rows) OpenRefine dataset. One cell contains multiple values that vary, but with a consistent structure (see example below) with data split by commas similar to a json array. I want to create a new multi-value column that just contains the elements from a specific category such as Creator or Subject. In the example below, I'd like to create a new column called Item Creator that would include only Dana M. Ashley and John Smith, the two that are found in the text. So far I've tried the expression forEach(value.split(","), v, v.contains("Creator:")) and I get an array that recognizes the segments that include Creator, but I don't yet understand how to extract that string text into the new column. Help would be much appreciated.

Publisher: American Federation of Teachers, Creator:  Dana M. Ashley, Creator:  John Smith, Subject:     Prosocial behavior, Subject: Program development, Subject: Behavior problems, Subject: Classroom techniques, Subject: Student behavior, Subject: School culture, Subject: Educational environment, Subject: Positive Behavior Supports, Resource Type: Text, Language: English, Audience: Educator, Format: pdf

答:
To put this value in a new column use the dropdown menu in your current column (that contains the combined data) and choose "Edit Column -> Add column based on this column"

If you replace the 'forEach' expression with a 'filter' expression in the GREL formula you've got here and you get the list of creators (in an array). To store these in a cell, you can join the array into a string:

```<code>filter(value.split(","), v, v.contains("Creator:")).join("|")
</code>```

This should get you the new column with a list of creators - it will need some more tidying up to remove the "Creator: " bit to get just a list of names

Body:
To put this value in a new column use the dropdown menu in your current column (that contains the combined data) and choose "Edit Column -> Add column based on this column"

If you replace the 'forEach' expression with a 'filter' expression in the GREL formula you've got here and you get the list of creators (in an array). To store these in a cell, you can join the array into a string:

filter(value.split(","), v, v.contains("Creator:")).join("|")

This should get you the new column with a list of creators - it will need some more tidying up to remove the "Creator: " bit to get just a list of names


问:
Obtaining total number of records from .tfrecords file in Tensorflow
Is it possible for obtain the total number of records from a .tfrecords file ? Related to this, how does one generally keep track of the number of epochs that have elapsed while training models? While it is possible for us to specify the batch_size and num_of_epochs, I am not sure if it is straightforward to obtain values such as current epoch, number of batches per epoch etc - just so that I could have more control of how the training is progressing. Currently, I'm just using a dirty hack to compute this as I know before hand how many records there are in my .tfrecords file and the size of my minibatches. Appreciate any help..

答:
No it is not possible. TFRecord does not store any metadata about the data being stored inside. This file

represents a sequence of (binary) strings. The format is not random
  access, so it is suitable for streaming large amounts of data but not
  suitable if fast sharding or other non-sequential access is desired.

If you want, you can store this metadata manually or use a record_iterator to get the number (you will need to iterate through all the records that you have:

```<code>sum(1 for _ in tf.python_io.tf_record_iterator(file_name))
</code>```

If you want to know the current epoch, you can do this either from tensorboard or by printing the number from the loop.

Body:
No it is not possible. TFRecord does not store any metadata about the data being stored inside. This file

represents a sequence of (binary) strings. The format is not random
  access, so it is suitable for streaming large amounts of data but not
  suitable if fast sharding or other non-sequential access is desired.

If you want, you can store this metadata manually or use a record_iterator to get the number (you will need to iterate through all the records that you have:

sum(1 for _ in tf.python_io.tf_record_iterator(file_name))

If you want to know the current epoch, you can do this either from tensorboard or by printing the number from the loop.