问:
Error callback not used for chained then() with ssh2-sftp-client in node.js lambda
I'm very new to node and lambda, so I'm probably making some dumb mistakes. I've created a node.js aws lambda function which grabs a file from an s3 event. If the file is gzip it decompresses, uploads it to a sftp server, then creates and uploads a sig file to the same sftp server. It works when everything goes well, but it doesn't seem to correctly trigger errors.

The sftp commands are chained using then, so I would expect any error to fail the subsequent thens.  For example, if I turn off my sftp server, the sftp client will generate a timeout error, but lambda never sees the callback error, only success. The log does show the error output to the console, but it appears to use the success callback after following the rest of the .then() items. Is the connection not correctly recorded as a promise?

Sample log:

```<code>...
Starting SFTP
Connected to sftp, starting sftp put for lastsub2.dat file.
{ Error: Timed out while waiting for handshake
    at Timeout._onTimeout (/var/task/node_modules/ssh2/lib/client.js:687:19)
    at ontimeout (timers.js:386:14)
    at tryOnTimeout (timers.js:250:5)
    at Timer.listOnTimeout (timers.js:214:5) level: 'client-timeout' } 'Error occured during sftp relay.'
END
</code>```

Example code:

```<code>console.log('Loading function');
const aws = require('aws-sdk');
const s3 = new aws.S3({
    apiVersion: '2006-03-01'
  });
const zlib = require('zlib');
const fs = require("fs");
const connSettings = {
  host: 'xxx',
  port: '22',
  username: 'xxx',
  password: 'xxx'
};

exports.handler = function (event, context, callback) {
  console.log('Received event:', JSON.stringify(event, null, 2));
  console.log('Bucket Name: ' + event.Records[0].s3.bucket.name);
  console.log('Object Key: ' + decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')));
  const bucket = event.Records[0].s3.bucket.name;
  const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
  const params = {
    Bucket: bucket,
    Key: key,
  };

  s3.getObject(params, (err, data) => {
    if (err) {
      console.log(err);
      const message = 'Error getting object ${key} from bucket ${bucket}. Make sure they exist and your bucket is in the same region as this function.';
      console.log(message);
      callback(message);
    } else {
      if (data.ContentType == 'application/x-gzip') {
        console.log('CONTENT TYPE is application/x-gzip');
        var dataStream = s3.getObject(params).createReadStream().pipe(zlib.Unzip());
        console.log('Created unzip datastream');
        console.log('Starting SFTP');
        let Client = require('ssh2-sftp-client');
        let sftp = new Client();
        sftp.connect(connSettings)
        .then(console.log('Connected to sftp, starting sftp put for ' + key.replace('.gz', '.dat') + ' file.'))
        .then(() => {
            console.log('Finished sftp put for ' + key.replace('.gz', '.dat') + ' file.');
            return sftp.put(dataStream, key.replace('.gz', '.dat'), true, 'utf-8');
        }).then(() => {
          var sigFileName = key.replace('.gz', '.sig');
          var sigStream = fs.createWriteStream('/tmp/' + sigFileName);
          sigStream.end();
          console.log('Created ' + sigFileName + ' sig file.');
          var readStream = fs.createReadStream('/tmp/' + sigFileName);
          console.log('Uploaded ' + sigFileName + ' sig file.');
          return sftp.put(readStream, sigFileName, true, 'utf-8');
        }).then(() => {
            console.log('Ended sftp connection.');
            return sftp.end();
        })
        .then(callback(null, 'Success'))
        .catch ((err) => {
          console.log(err, 'Error occured during sftp relay.');
          callback('Error', err);
        });
      } else {
        callback(null, 'Uploaded file not in gzip format, will not be processed.');
      }
    }
  });
};
</code>```

答:
The problem you are having is happening because you are not returning anything from the then()s. The result is that each then() is executed immediately without waiting for any of the async sftp functions to return because it resolves immediately to undefined.

You didn't mention what sftp library you're using, but assuming it returns a promise, you should be able to simply return those promises from the the then()s.

For example:

```<code>.then(() => {
      console.log('Finished sftp put for ' + key.replace('.gz', '.dat') + ' file.');
      // assumes stfp.put returns a promise, just return it into the chain
      return sftp.put(dataStream, key.replace('.gz', '.dat'), true, 'utf-8');
    })
</code>```

EDIT based on comments:

You should be able to call the callback from the then()s.  Looking at the log output now in your edit, isn't this almost what you are expecting when there's an error — it jumps to the catch. You are getting the console output, 'Connected to sftp…' because of the way you are calling that then. Instead of:

```<code>.then(console.log('Connected to sftp, starting sftp put for ' + key.replace('.gz', '.dat') + ' file.'))
</code>```

it should probably be:

```<code>.then(() => console.log('Connected to sftp, starting sftp put for ' + key.replace('.gz', '.dat') + ' file.'))
</code>```

The way you have it, the console will log before the error returns from sftp.

Body:
I'm very new to node and lambda, so I'm probably making some dumb mistakes. I've created a node.js aws lambda function which grabs a file from an s3 event. If the file is gzip it decompresses, uploads it to a sftp server, then creates and uploads a sig file to the same sftp server. It works when everything goes well, but it doesn't seem to correctly trigger errors.

The sftp commands are chained using then, so I would expect any error to fail the subsequent thens.  For example, if I turn off my sftp server, the sftp client will generate a timeout error, but lambda never sees the callback error, only success. The log does show the error output to the console, but it appears to use the success callback after following the rest of the .then() items. Is the connection not correctly recorded as a promise?

Sample log:

...
Starting SFTP
Connected to sftp, starting sftp put for lastsub2.dat file.
{ Error: Timed out while waiting for handshake
    at Timeout._onTimeout (/var/task/node_modules/ssh2/lib/client.js:687:19)
    at ontimeout (timers.js:386:14)
    at tryOnTimeout (timers.js:250:5)
    at Timer.listOnTimeout (timers.js:214:5) level: 'client-timeout' } 'Error occured during sftp relay.'
END

Example code:

console.log('Loading function');
const aws = require('aws-sdk');
const s3 = new aws.S3({
    apiVersion: '2006-03-01'
  });
const zlib = require('zlib');
const fs = require("fs");
const connSettings = {
  host: 'xxx',
  port: '22',
  username: 'xxx',
  password: 'xxx'
};

exports.handler = function (event, context, callback) {
  console.log('Received event:', JSON.stringify(event, null, 2));
  console.log('Bucket Name: ' + event.Records[0].s3.bucket.name);
  console.log('Object Key: ' + decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')));
  const bucket = event.Records[0].s3.bucket.name;
  const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
  const params = {
    Bucket: bucket,
    Key: key,
  };

  s3.getObject(params, (err, data) => {
    if (err) {
      console.log(err);
      const message = 'Error getting object ${key} from bucket ${bucket}. Make sure they exist and your bucket is in the same region as this function.';
      console.log(message);
      callback(message);
    } else {
      if (data.ContentType == 'application/x-gzip') {
        console.log('CONTENT TYPE is application/x-gzip');
        var dataStream = s3.getObject(params).createReadStream().pipe(zlib.Unzip());
        console.log('Created unzip datastream');
        console.log('Starting SFTP');
        let Client = require('ssh2-sftp-client');
        let sftp = new Client();
        sftp.connect(connSettings)
        .then(console.log('Connected to sftp, starting sftp put for ' + key.replace('.gz', '.dat') + ' file.'))
        .then(() => {
            console.log('Finished sftp put for ' + key.replace('.gz', '.dat') + ' file.');
            return sftp.put(dataStream, key.replace('.gz', '.dat'), true, 'utf-8');
        }).then(() => {
          var sigFileName = key.replace('.gz', '.sig');
          var sigStream = fs.createWriteStream('/tmp/' + sigFileName);
          sigStream.end();
          console.log('Created ' + sigFileName + ' sig file.');
          var readStream = fs.createReadStream('/tmp/' + sigFileName);
          console.log('Uploaded ' + sigFileName + ' sig file.');
          return sftp.put(readStream, sigFileName, true, 'utf-8');
        }).then(() => {
            console.log('Ended sftp connection.');
            return sftp.end();
        })
        .then(callback(null, 'Success'))
        .catch ((err) => {
          console.log(err, 'Error occured during sftp relay.');
          callback('Error', err);
        });
      } else {
        callback(null, 'Uploaded file not in gzip format, will not be processed.');
      }
    }
  });
};

Body:
The problem you are having is happening because you are not returning anything from the then()s. The result is that each then() is executed immediately without waiting for any of the async sftp functions to return because it resolves immediately to undefined.

You didn't mention what sftp library you're using, but assuming it returns a promise, you should be able to simply return those promises from the the then()s.

For example:

.then(() => {
      console.log('Finished sftp put for ' + key.replace('.gz', '.dat') + ' file.');
      // assumes stfp.put returns a promise, just return it into the chain
      return sftp.put(dataStream, key.replace('.gz', '.dat'), true, 'utf-8');
    })

EDIT based on comments:

You should be able to call the callback from the then()s.  Looking at the log output now in your edit, isn't this almost what you are expecting when there's an error — it jumps to the catch. You are getting the console output, 'Connected to sftp…' because of the way you are calling that then. Instead of:

.then(console.log('Connected to sftp, starting sftp put for ' + key.replace('.gz', '.dat') + ' file.'))

it should probably be:

.then(() => console.log('Connected to sftp, starting sftp put for ' + key.replace('.gz', '.dat') + ' file.'))

The way you have it, the console will log before the error returns from sftp.


来源: stackexchange

问:
Does phoenix have a schema dump equivalent of Rails' schema.rb?
Rails' schema.rb was a very convenient way to have a reference of the state of the database.  I can go straight to the pg or mysql client and describe tables to get the same info, but it's much less convenient.

Does Elixir / Ecto have a similar feature or way to generate a schema representation?

答:
You can use the ecto.dump mix task:

mix ecto.dump

ContentLicense: CC BY-SA 3.0


问:
Getting Internal Error in Subcommand Bukkit
I've been facing a problem lately with bukkit coding. When I launch the plugin and just type /akitz   command label or name it pops up with an Internal Error but when I type /akitz {subcommand} it works fine! everything here basically works fine but just the /akitz   <-- alone when i type it, an error pops up!   here's the code:

```<code>package me.frostgamersa;

import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;

public class Main extends JavaPlugin {
@Override
public void onEnable() {

}

@Override
public void onDisable() {

}

@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
    if (label.equalsIgnoreCase("akitz")) {
        Player player = (Player) sender;

        if (args.length == 0 || args.length < 2) {
            player.sendMessage("§cIncorrect Arguments");

            if (args[0].equalsIgnoreCase("legend")) {
                player.sendMessage("§bYou have been Granted §3Legend §bKit!");
                CustomItems.givela(player);
                CustomItems.givels(player);
                player.getInventory().addItem(new ItemStack(Material.GOLDEN_APPLE, 64));
                return true;
            }
            if (args[0].equalsIgnoreCase("god")) {
                player.sendMessage("§bYou have been Granted §3God §bKit!");
                CustomItems.givega(player);
                CustomItems.givegs(player);
                player.getInventory().addItem(new ItemStack(Material.GOLDEN_APPLE, 64));
                return true;
            } else {
                player.sendMessage("§cIncorrect Arguments!");
                return true;
            }
        }
</code>```

答:
Spoonfeed incoming:

```<code>package me.frostgamersa;

import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;

public class Main extends JavaPlugin {
@Override
public void onEnable() {

}

@Override
public void onDisable() {

}

@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
    if (label.equalsIgnoreCase("akitz")) {
        Player player = (Player) sender;

        if (args.length < 2) {
            player.sendMessage("§cIncorrect Arguments");
        } else {
            if (args[0].equalsIgnoreCase("legend")) {
                player.sendMessage("§bYou have been Granted §3Legend §bKit!");
                CustomItems.givela(player);
                CustomItems.givels(player);
                player.getInventory().addItem(new ItemStack(Material.GOLDEN_APPLE, 64));
                return true;
            }

            if (args[0].equalsIgnoreCase("god")) {
                player.sendMessage("§bYou have been Granted §3God §bKit!");
                CustomItems.givega(player);
                CustomItems.givegs(player);
                player.getInventory().addItem(new ItemStack(Material.GOLDEN_APPLE, 64));
                return true;
            } else {
                player.sendMessage("§cIncorrect Arguments!");
                return true;
            }
        }
    }
}
</code>```

I would also recommend you remove onEnable and onDisable, as those are not required, and since you have nothing in them, it's just using up space that it doesn't need to.

Also, you should check if the sender is a player before casting it, as that could create errors when console executes a command.

ContentLicense: CC BY-SA 4.0

Body:
I've been facing a problem lately with bukkit coding. When I launch the plugin and just type /akitz   command label or name it pops up with an Internal Error but when I type /akitz {subcommand} it works fine! everything here basically works fine but just the /akitz   <-- alone when i type it, an error pops up!   here's the code:

package me.frostgamersa;

import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;

public class Main extends JavaPlugin {
@Override
public void onEnable() {

}

@Override
public void onDisable() {

}

@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
    if (label.equalsIgnoreCase("akitz")) {
        Player player = (Player) sender;

        if (args.length == 0 || args.length < 2) {
            player.sendMessage("§cIncorrect Arguments");

            if (args[0].equalsIgnoreCase("legend")) {
                player.sendMessage("§bYou have been Granted §3Legend §bKit!");
                CustomItems.givela(player);
                CustomItems.givels(player);
                player.getInventory().addItem(new ItemStack(Material.GOLDEN_APPLE, 64));
                return true;
            }
            if (args[0].equalsIgnoreCase("god")) {
                player.sendMessage("§bYou have been Granted §3God §bKit!");
                CustomItems.givega(player);
                CustomItems.givegs(player);
                player.getInventory().addItem(new ItemStack(Material.GOLDEN_APPLE, 64));
                return true;
            } else {
                player.sendMessage("§cIncorrect Arguments!");
                return true;
            }
        }

Body:
Spoonfeed incoming:

package me.frostgamersa;

import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;

public class Main extends JavaPlugin {
@Override
public void onEnable() {

}

@Override
public void onDisable() {

}

@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
    if (label.equalsIgnoreCase("akitz")) {
        Player player = (Player) sender;

        if (args.length < 2) {
            player.sendMessage("§cIncorrect Arguments");
        } else {
            if (args[0].equalsIgnoreCase("legend")) {
                player.sendMessage("§bYou have been Granted §3Legend §bKit!");
                CustomItems.givela(player);
                CustomItems.givels(player);
                player.getInventory().addItem(new ItemStack(Material.GOLDEN_APPLE, 64));
                return true;
            }

            if (args[0].equalsIgnoreCase("god")) {
                player.sendMessage("§bYou have been Granted §3God §bKit!");
                CustomItems.givega(player);
                CustomItems.givegs(player);
                player.getInventory().addItem(new ItemStack(Material.GOLDEN_APPLE, 64));
                return true;
            } else {
                player.sendMessage("§cIncorrect Arguments!");
                return true;
            }
        }
    }
}

I would also recommend you remove onEnable and onDisable, as those are not required, and since you have nothing in them, it's just using up space that it doesn't need to.

Also, you should check if the sender is a player before casting it, as that could create errors when console executes a command.


问:
How to change image button on click then get back
I have an image button and I would like to do that if I click to the img button it is changed, then if I click again to the button it change back to the default image.

I have this script but it doesnt change back. Anybody can help me?

```<code><script>
  function VOR2(img)
  {
    if(img.src.match(/blank/))
    {
      img.src = "VOR.gif";
    }
    else
    {
      img.src = "VOR2.gif";
    }
  }
</script>
<img src="VOR.gif" id="VOR2" onclick=VOR2
</code>```

答:
You could do it this way :

JS :

```<code>function VOR2(img) {
  if (img.src == "VOR2.gif") {
    img.src = "VOR.gif";
  } else {
    img.src = "VOR2.gif";
  }

  console.log(img.src);
}
</code>```

HTML :

```<code><img src="VOR.gif" id="VOR2" onclick="VOR2(this)" />
</code>```

Body:
I have an image button and I would like to do that if I click to the img button it is changed, then if I click again to the button it change back to the default image.

I have this script but it doesnt change back. Anybody can help me?

<img src="VOR.gif" id="VOR2" onclick=VOR2

Body:
You could do it this way :

JS :

function VOR2(img) {
  if (img.src == "VOR2.gif") {
    img.src = "VOR.gif";
  } else {
    img.src = "VOR2.gif";
  }

  console.log(img.src);
}

HTML :

<img src="VOR.gif" id="VOR2" onclick="VOR2(this)" />


问:
How can I remove border lines when using geom_sf?
I tried doing the following:

```<code>ggplot(geography) + geom_sf(aes(fill=rate, color = NULL))
</code>```

but that didn't get rid of the border lines.

答:
Without a reproducible example it is difficult to know exactly what you are looking for.  However, I will take a guess that your are looking for a way to suppress the lines marking boundaries between different polygons (regions), e.g., suppress the lines showing country borders on a map of the world.  If that is so then here is a solution.

Use lwd = 0 in the geom_sf call.

Example (you might need to download the developmental version of ggplot2)

```<code># devtools::install_github("tidyverse/ggplot2")
library(ggplot2)
library(maps)
library(maptools)
library(rgeos)
library(sf)

world1 <- sf::st_as_sf(map('world', plot = FALSE, fill = TRUE))

with_boundary <-
  ggplot() +
    geom_sf(data = world1, mapping = aes(fill = ID)) +
  theme(legend.position = "none") +
  ggtitle("With Country Boundaries")

without_boundary <-
  ggplot() +
    geom_sf(data = world1, mapping = aes(fill = ID), lwd = 0) +
  theme(legend.position = "none") +
  ggtitle("Without Country Boundaries")
</code>```

Body:
I tried doing the following:

ggplot(geography) + geom_sf(aes(fill=rate, color = NULL))

but that didn't get rid of the border lines.

Body:
Without a reproducible example it is difficult to know exactly what you are looking for.  However, I will take a guess that your are looking for a way to suppress the lines marking boundaries between different polygons (regions), e.g., suppress the lines showing country borders on a map of the world.  If that is so then here is a solution.

Use lwd = 0 in the geom_sf call.

Example (you might need to download the developmental version of ggplot2)

# devtools::install_github("tidyverse/ggplot2")
library(ggplot2)
library(maps)
library(maptools)
library(rgeos)
library(sf)

world1 <- sf::st_as_sf(map('world', plot = FALSE, fill = TRUE))

with_boundary <-
  ggplot() +
    geom_sf(data = world1, mapping = aes(fill = ID)) +
  theme(legend.position = "none") +
  ggtitle("With Country Boundaries")

without_boundary <-
  ggplot() +
    geom_sf(data = world1, mapping = aes(fill = ID), lwd = 0) +
  theme(legend.position = "none") +
  ggtitle("Without Country Boundaries")


问:
CodeEffects RuleEditor not rendering in MVC dialog
Currently we have a full page that renders the RuleEditor without issue in the view. I've ran into an issue in getting this to render properly on a dialog.

I'm using the same exact logic to load the objects between the full view and the dialog view.

Here is what the RuleEditor looks like in the full view with an example rule:
RuleEditor Full view

Here is the RuleEditor display (bad rendering) for the same rule
RuleEditor within dialog
The div content within this dialog is:

```<code><div id="ruleModel" name="ruleModel">
    <input type="hidden" id="ruleModelData" name="ruleModel">
    <a href="http://codeeffects.com" ce002="false">.</a>
</div>
</code>```

There are no html/javascript console errors. Any thoughts on why this is happening?

Thanks!

*******UPDATE*****
Here is the .cshtml content for the dialog:

```<code>@model RuleViewModel

<link href="@Url.Content("~/Content/Common.css")" rel="stylesheet"
type="text/css" />

@{
    ViewBag.Title = "Edit Rule1";
    Layout = null;
    Html.CodeEffects().Styles()
        .SetTheme(ThemeType.Gray)
        .Render();
}

@using (Html.BeginSecureForm("Save", "Rule"))
{
    @Html.ValidationSummary(true)
    <br />
    <b>Rule Name:</b> @Html.TextBoxFor(m => m.RuleName, new { id =
"RuleName", @class = "form-control" })

    <fieldset>
        <div class="main">
            <div class="area">
                <div style="margin-top:10px;">
                    @{
                        Html.CodeEffects().RuleEditor()
                                        .Id("ruleModel")
                                        .ShowToolBar(false)
                                        .Mode(RuleType.Evaluation)
                                        .Rule(ViewBag.Rule)
                                        .DataSources(Model.DataSources)
                                        .ContextMenuRules(Model.Rules)
                                        .Render();

                    }
                    @{
                        Html.CodeEffects().Scripts().Render();
                    }
                </div>
                <div class="modal-footer">
                    <input class="btn btn-default" submit" type="submit"
value="Save" />
                    <button type="button" class="btn btn-
default">Cancel</button>
                </div>
            </div>
        </div>
    </fieldset>
}
</code>```

UPDATE #2
I took from the AJAX example and did all the RuleEditor settings via the AJAX post/controller methods. That seems to work better, but now the context menu seems disconnected. (See area in Red Circle)RuleEditor In Dialog, Context Menu behind

答: Most likely your dialog is "disconnected" from the main editor's script and all json settings it receives from the server on load. Another possibility is that your dialog tries to render the editor before those json setting values gets to the client.</p>

Body:
Currently we have a full page that renders the RuleEditor without issue in the view. I've ran into an issue in getting this to render properly on a dialog.

I'm using the same exact logic to load the objects between the full view and the dialog view.

Here is what the RuleEditor looks like in the full view with an example rule:
RuleEditor Full view

Here is the RuleEditor display (bad rendering) for the same rule
RuleEditor within dialog
The div content within this dialog is:

    <input type="hidden" id="ruleModelData" name="ruleModel">
    .

There are no html/javascript console errors. Any thoughts on why this is happening?

Thanks!

*******UPDATE*****
Here is the .cshtml content for the dialog:

@model RuleViewModel

<link href="@Url.Content("~/Content/Common.css")" rel="stylesheet"
type="text/css" />

@{
    ViewBag.Title = "Edit Rule1";
    Layout = null;
    Html.CodeEffects().Styles()
        .SetTheme(ThemeType.Gray)
        .Render();
}

@using (Html.BeginSecureForm("Save", "Rule"))
{
    @Html.ValidationSummary(true)

    Rule Name: @Html.TextBoxFor(m => m.RuleName, new { id =
"RuleName", @class = "form-control" })

    <fieldset>

                    @{
                        Html.CodeEffects().RuleEditor()
                                        .Id("ruleModel")
                                        .ShowToolBar(false)
                                        .Mode(RuleType.Evaluation)
                                        .Rule(ViewBag.Rule)
                                        .DataSources(Model.DataSources)
                                        .ContextMenuRules(Model.Rules)
                                        .Render();

                    }
                    @{
                        Html.CodeEffects().Scripts().Render();
                    }

                    <input class="btn btn-default" submit" type="submit"
value="Save" />
                    <button type="button" class="btn btn-
default">Cancel</button>

    </fieldset>
}

UPDATE #2
I took from the AJAX example and did all the RuleEditor settings via the AJAX post/controller methods. That seems to work better, but now the context menu seems disconnected. (See area in Red Circle)RuleEditor In Dialog, Context Menu behind


问:
How to format my time display to show daylight savings label?
my time is showing like this

moment(date).tz(TimeZone).format('h:mm a z')

1:02 p.m. EST

what I would like it for it to say

1:02 p.m. EDT

how can i change it to daylight savings time

答:
I can't do that in moment

```<code>jun.tz('America/New_York').format('ha z'); // 8am EDT
dec.tz('America/New_York').format('ha z'); // 7am EST
</code>```

in the winter its always est i think

Body:
I can't do that in moment

jun.tz('America/New_York').format('ha z'); // 8am EDT
dec.tz('America/New_York').format('ha z'); // 7am EST

in the winter its always est i think


问:
ASP.NET -- IIS7 -- IBM DB2 Issue
I'm working on a ASP.NET website that calls a DB2 database.  I have Visual Studio installed on a Windows 2008 server where the site will be hosted.  When I debug the site in Visual Studio, using the integrated web server, I can connect to the database and the site runs fine.  When I set the site up in IIS7, on the same server, I cannot access the site or the database because of the following error.

Here are the technical details:

```<code>Windows 2008 Server
IIS 7
Visual Studio 2010 Premium
DB2 v9.5.301.436

Could not load file or assembly 'IBM.Data.DB2' or one of its dependencies. An attempt was made to load a program with an incorrect format.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.BadImageFormatException: Could not load file or assembly 'IBM.Data.DB2' or one of its dependencies. An attempt was made to load a program with an incorrect format.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Assembly Load Trace: The following information can be helpful to determine why the assembly 'IBM.Data.DB2' could not be loaded.

WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].

Stack Trace:

[BadImageFormatException: Could not load file or assembly 'IBM.Data.DB2' or one of its dependencies. An attempt was made to load a program with an incorrect format.]
   System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0
   System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection, Boolean suppressSecurityChecks) +567
   System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +192
   System.Reflection.Assembly.Load(String assemblyString) +35
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +118

[ConfigurationErrorsException: Could not load file or assembly 'IBM.Data.DB2' or one of its dependencies. An attempt was made to load a program with an incorrect format.]
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +11424435
   System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +484
   System.Web.Configuration.AssemblyInfo.get_AssemblyInternal() +127
   System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +334
   System.Web.Compilation.BuildManager.CallPreStartInitMethods() +280
   System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +1167

[HttpException (0x80004005): Could not load file or assembly 'IBM.Data.DB2' or one of its dependencies. An attempt was made to load a program with an incorrect format.]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +11556592
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +141
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +4813333
</code>```

I don't understand how the site can run fine using the Visual Studio web server and not work in IIS.  I don't know if it's an IIS issue or and issue with the version of IMB.Data.DB2.dll I'm using.  If anyone has a solution or any ideas, they would be greatly appreciated.

Thank you.

答:
In Visual Studio: right click the Reference in question and change Copy Local to "False"
https://i.stack.imgur.com/y0Dre.png

More info:
IBM DB2 issue--System.BadImageFormatException: Could not load file or assembly IBM.DB2.DLL or one of its dependencies

Title: ASP.NET -- IIS7 -- IBM DB2 Issue

Body:
I'm working on a ASP.NET website that calls a DB2 database.  I have Visual Studio installed on a Windows 2008 server where the site will be hosted.  When I debug the site in Visual Studio, using the integrated web server, I can connect to the database and the site runs fine.  When I set the site up in IIS7, on the same server, I cannot access the site or the database because of the following error.

Here are the technical details:

Windows 2008 Server
IIS 7
Visual Studio 2010 Premium
DB2 v9.5.301.436

Could not load file or assembly 'IBM.Data.DB2' or one of its dependencies. An attempt was made to load a program with an incorrect format.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.BadImageFormatException: Could not load file or assembly 'IBM.Data.DB2' or one of its dependencies. An attempt was made to load a program with an incorrect format.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Assembly Load Trace: The following information can be helpful to determine why the assembly 'IBM.Data.DB2' could not be loaded.

WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].

Stack Trace:

[BadImageFormatException: Could not load file or assembly 'IBM.Data.DB2' or one of its dependencies. An attempt was made to load a program with an incorrect format.]
   System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0
   System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection, Boolean suppressSecurityChecks) +567
   System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +192
   System.Reflection.Assembly.Load(String assemblyString) +35
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +118

[ConfigurationErrorsException: Could not load file or assembly 'IBM.Data.DB2' or one of its dependencies. An attempt was made to load a program with an incorrect format.]
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +11424435
   System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +484
   System.Web.Configuration.AssemblyInfo.get_AssemblyInternal() +127
   System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +334
   System.Web.Compilation.BuildManager.CallPreStartInitMethods() +280
   System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +1167

[HttpException (0x80004005): Could not load file or assembly 'IBM.Data.DB2' or one of its dependencies. An attempt was made to load a program with an incorrect format.]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +11556592
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +141
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +4813333

I don't understand how the site can run fine using the Visual Studio web server and not work in IIS.  I don't know if it's an IIS issue or and issue with the version of IMB.Data.DB2.dll I'm using.  If anyone has a solution or any ideas, they would be greatly appreciated.

Thank you.


问:
Trouble adding PHP modules to Apache 2.2 Server
I run a Windows 7 x64 machine with apache 2.2 and PHP 5.2.17

Whenever I try to add the PHP dll to the httpd.conf file, apache will not start.

this is how it is being put into httpd.conf

```<code>LoadModule php5_module "C:/php/php5apache2_2.dll"
AddType application/x-httpd-php .php
PHPIniDir "C:/php"
</code>```

I have successfully managed to setup and run a Apache server with PHP before, so I'm not new to this, but I'm fairly certain that this is right.

答: If everything that's being output on launch is the DNS error, Apache is launching just fine. FQDN resolution is a warning, not an error.</p>

ContentLicense: CC BY-SA 2.5

Body:
I run a Windows 7 x64 machine with apache 2.2 and PHP 5.2.17

Whenever I try to add the PHP dll to the httpd.conf file, apache will not start.

this is how it is being put into httpd.conf

LoadModule php5_module "C:/php/php5apache2_2.dll"
AddType application/x-httpd-php .php
PHPIniDir "C:/php"

I have successfully managed to setup and run a Apache server with PHP before, so I'm not new to this, but I'm fairly certain that this is right.


问:
SQL How to SELECT all rows with repeated id's but not the first of each one?
I have a database with repeated IDs, and I want to change the names of this repeated IDs.

So, I have a database of Vehicles and in columns I have the License number (id), the type of vehicle, the colour and also the make.

All the ids are repeated in the database, and I want to SELECT all of them except the first row of each different ID (something like a "DISTINCT id" but inverse...).

EDIT 2:

I have created this table

```<code>DROP TABLE IF EXISTS Proces1 CASCADE;
CREATE TABLE Proces1 AS
(
    SELECT id_importat AS id_aux, driver_city AS city_aux, driver_state AS state_aux, gender AS g_aux, race AS r_aux
    FROM ImportaViolations
    WHERE id_importat IN (
        SELECT id_importat
        FROM ImportaViolations
        GROUP BY id_importat
        HAVING (COUNT(*) > 1))
    GROUP BY id_importat, driver_city, driver_state, gender, race
);
</code>```

And in this table I have repeated id's but with different information in the columns.

Something like:

```<code>id_aux   city_aux      state_aux     g_aux     r_aux
1        London        England        M        WHITE
1        London        England        F        BLACK
2        Madrid        Spain          M        BLACK
2        London        England        F        WHITE
2        London        England        M        WHITE
...
</code>```

So now, I want to SELECT all the rows with repeated id_aux except for the first one of each different id_aux. So I want to have this final result (in this example):

```<code>id_aux   city_aux      state_aux      g_aux    r_aux
1        London        England        F        BLACK
2        London        England        F        WHITE
2        London        England        M        WHITE
...
</code>```

答:
I've simply modified the answer to this question to better fit your needs:
Select first row in each GROUP BY group?

Essentially, rather than selecting the first of each group using rk = 1, I've changed it to be rk > 1 and switched the column names around to match yours.

```<code>WITH MyTable AS (
    SELECT p.Id,
           p.Column1,
           p.Column2,
           ROW_NUMBER() OVER(PARTITION BY p.Column1
                             ORDER BY p.Column2 DESC) AS rk
      FROM MyTable p)
SELECT s.*
  FROM MyTable t
 WHERE s.rk > 1
</code>```

EDIT: Changed rk = 2 to rk > 1 to select all but the first rather than just the second.

Body:
I have a database with repeated IDs, and I want to change the names of this repeated IDs.

So, I have a database of Vehicles and in columns I have the License number (id), the type of vehicle, the colour and also the make.

All the ids are repeated in the database, and I want to SELECT all of them except the first row of each different ID (something like a "DISTINCT id" but inverse...).

EDIT 2:

I have created this table

DROP TABLE IF EXISTS Proces1 CASCADE;
CREATE TABLE Proces1 AS
(
    SELECT id_importat AS id_aux, driver_city AS city_aux, driver_state AS state_aux, gender AS g_aux, race AS r_aux
    FROM ImportaViolations
    WHERE id_importat IN (
        SELECT id_importat
        FROM ImportaViolations
        GROUP BY id_importat
        HAVING (COUNT(*) > 1))
    GROUP BY id_importat, driver_city, driver_state, gender, race
);

And in this table I have repeated id's but with different information in the columns.

Something like:

id_aux   city_aux      state_aux     g_aux     r_aux
1        London        England        M        WHITE
1        London        England        F        BLACK
2        Madrid        Spain          M        BLACK
2        London        England        F        WHITE
2        London        England        M        WHITE
...

So now, I want to SELECT all the rows with repeated id_aux except for the first one of each different id_aux. So I want to have this final result (in this example):

id_aux   city_aux      state_aux      g_aux    r_aux
1        London        England        F        BLACK
2        London        England        F        WHITE
2        London        England        M        WHITE
...

Body:
I've simply modified the answer to this question to better fit your needs:
Select first row in each GROUP BY group?

Essentially, rather than selecting the first of each group using rk = 1, I've changed it to be rk > 1 and switched the column names around to match yours.

WITH MyTable AS (
    SELECT p.Id,
           p.Column1,
           p.Column2,
           ROW_NUMBER() OVER(PARTITION BY p.Column1
                             ORDER BY p.Column2 DESC) AS rk
      FROM MyTable p)
SELECT s.*
  FROM MyTable t
 WHERE s.rk > 1

EDIT: Changed rk = 2 to rk > 1 to select all but the first rather than just the second.


问:
How to apply play-evolutions when running tests in play-framework?
I have problems with evolutions when running tests in play framework using

playframework v2.6.6 for scala

play-slick v3.0.2

play-slick-evolutions v3.0.2

The test looks like this:

```<code>class TestFooController extends PlaySpec with GuiceOneServerPerSuite {
  "foo endpoint should store some data" in {
    val wsClient = app.injector.instanceOf[WSClient]
    val url = s"http://localhost:$port/foo"
    val requestData = Json.obj("foo" -> "bar")
    val response = await(wsClient.url(url).post(requestData))
    response.status mustBe OK
  }
}
</code>```

The database configuration looks like this:

```<code>slick.dbs.default.driver="slick.driver.H2Driver$"
slick.dbs.default.db.driver="org.h2.Driver"
slick.dbs.default.db.url="jdbc:h2:mem:play"
</code>```

Asume there is an evolution script which creates the table foos and this script is working fine in dev mode.

When running the test the following error is thrown:

play.api.http.HttpErrorHandlerExceptions$$anon$1: Execution exception[[JdbcSQLException: Table "foos" not found;

The table foos could not be found so I assume that database evolutions have not been applied.

Then I changed the database configuration to postgresql which is used in dev mode.

```<code>slick.dbs.default.driver = "slick.driver.PostgresDriver$"
slick.dbs.default.db.driver = "org.postgresql.Driver"
slick.dbs.default.db.url = "jdbc:postgresql://localhost:5432/foo-test"
slick.dbs.default.db.user = "user"
slick.dbs.default.db.password = "password"
</code>```

With this configuration the test work fine and data are stored in the database, so database evolutions ran just fine.

Now the problem is, that the database is not cleaned up after tests. I'd like to run each test suite with a clean database.

To sum up. With H2Db evolutions are not applied, with postgresql evolutions are applied but not cleaned up.

Even if this explicitly defined in application.test.conf

```<code>play.evolutions.autoApply=true
play.evolutions.autoApplyDowns=true
</code>```

I also tried

```<code>play.evolutions.db.default.autoApply=true
play.evolutions.db.default.autoApplyDowns=true
</code>```

no effect.

Then I tried to do this manually via:

```<code>  def withManagedDatabase[T](block: Database => T): Unit = {
    val dbapi    = app.injector.instanceOf[DBApi]
    val database = dbapi.database("default")
    Evolutions.applyEvolutions(database)
    block(database)
    Evolutions.cleanupEvolutions(database)
  }
</code>```

and then changing the test to:

```<code>  "foo endpoint should store some data" in withManagedDatabase { _ =>
    ...
  }
</code>```

For the H2 database configuration it has no effect, the same error that table foos can not be found is thrown. For the postgresql database configuration an evolution exceptions is thrown

play.api.db.evolutions.InconsistentDatabase: Database 'default' is in an inconsistent state![An evolution has not been applied properly. Please check the problem and resolve it manually before marking it as resolved.]

I want evolution ups running before and evolution downs running after each test suite. How can this be achieved?

答:
This is working for me:</p>

```<code>class DAOSpec extends PlaySpec with GuiceOneAppPerSuite {

  val dbUrl = sys.env.getOrElse("DATABASE_URL", "postgres://foo:password@localhost:5432/foo")

  val testConfig = Map("db.default.url" -> dbUrl)

  implicit override def fakeApplication() = new GuiceApplicationBuilder().configure(testConfig).build()

  lazy val database = app.injector.instanceOf[Database]
  lazy val dao = app.injector.instanceOf[DAO]

  "create" must {
    "work" in Evolutions.withEvolutions(database) {
      val foo = await(dao.create("foo"))
      foo.id must not be null
    }
  }

}
</code>```

Body:
I have problems with evolutions when running tests in play framework using

playframework v2.6.6 for scala

play-slick v3.0.2

play-slick-evolutions v3.0.2

The test looks like this:

class TestFooController extends PlaySpec with GuiceOneServerPerSuite {
  "foo endpoint should store some data" in {
    val wsClient = app.injector.instanceOf[WSClient]
    val url = s"http://localhost:$port/foo"
    val requestData = Json.obj("foo" -> "bar")
    val response = await(wsClient.url(url).post(requestData))
    response.status mustBe OK
  }
}

The database configuration looks like this:

slick.dbs.default.driver="slick.driver.H2Driver$"
slick.dbs.default.db.driver="org.h2.Driver"
slick.dbs.default.db.url="jdbc:h2:mem:play"

Asume there is an evolution script which creates the table foos and this script is working fine in dev mode.

When running the test the following error is thrown:

play.api.http.HttpErrorHandlerExceptions$$anon$1: Execution exception[[JdbcSQLException: Table "foos" not found;

The table foos could not be found so I assume that database evolutions have not been applied.

Then I changed the database configuration to postgresql which is used in dev mode.

slick.dbs.default.driver = "slick.driver.PostgresDriver$"
slick.dbs.default.db.driver = "org.postgresql.Driver"
slick.dbs.default.db.url = "jdbc:postgresql://localhost:5432/foo-test"
slick.dbs.default.db.user = "user"
slick.dbs.default.db.password = "password"

With this configuration the test work fine and data are stored in the database, so database evolutions ran just fine.

Now the problem is, that the database is not cleaned up after tests. I'd like to run each test suite with a clean database.

To sum up. With H2Db evolutions are not applied, with postgresql evolutions are applied but not cleaned up.

Even if this explicitly defined in application.test.conf

play.evolutions.autoApply=true
play.evolutions.autoApplyDowns=true

I also tried

play.evolutions.db.default.autoApply=true
play.evolutions.db.default.autoApplyDowns=true

no effect.

Then I tried to do this manually via:

  def withManagedDatabase[T](block: Database => T): Unit = {
    val dbapi    = app.injector.instanceOf[DBApi]
    val database = dbapi.database("default")
    Evolutions.applyEvolutions(database)
    block(database)
    Evolutions.cleanupEvolutions(database)
  }

and then changing the test to:

  "foo endpoint should store some data" in withManagedDatabase { _ =>
    ...
  }

For the H2 database configuration it has no effect, the same error that table foos can not be found is thrown. For the postgresql database configuration an evolution exceptions is thrown

play.api.db.evolutions.InconsistentDatabase: Database 'default' is in an inconsistent state![An evolution has not been applied properly. Please check the problem and resolve it manually before marking it as resolved.]

I want evolution ups running before and evolution downs running after each test suite. How can this be achieved?

Body:
This is working for me:

class DAOSpec extends PlaySpec with GuiceOneAppPerSuite {

  val dbUrl = sys.env.getOrElse("DATABASE_URL", "postgres://foo:password@localhost:5432/foo")

  val testConfig = Map("db.default.url" -> dbUrl)

  implicit override def fakeApplication() = new GuiceApplicationBuilder().configure(testConfig).build()

  lazy val database = app.injector.instanceOf[Database]
  lazy val dao = app.injector.instanceOf[DAO]

  "create" must {
    "work" in Evolutions.withEvolutions(database) {
      val foo = await(dao.create("foo"))
      foo.id must not be null
    }
  }

}


答:
The answer depends how you insert the  content into your files.

If you manually copy the a .svg  file's content and have to manually use the steps you did above to minify the HTML, then there's definitely a better way: store your main .svgs in one folder called svgs, and call a script that minifies those .svgs into another folder called svgsminified. That way everytime you manually copy the  markup, you would use the minified version in svgsminified folder.

If your IDE adds the .svg file's markup for you, then hopefully there's a scripting function in the IDE that allows you to call an external script to pre-minify the incoming <svg> markup .

If you're using Powershell (which works on *nix and Windows), a minifying script to minify all .svgs in a folder would look something like:

```<code># All .svgs in $svg_dir will be minified into $svg_minified_dir
$svg_dir = 'D:/svg'
$svg_minified_dir = 'D:/svgs_minified'
Get-ChildItem $svg_dir -Filter *.svg | ForEach-Object {
    $svg_content = Get-Content $_.FullName -Raw
    $svg_minified = $svg_content -replace '(\.[0-9]{2})([0-9]{1,5})', '${1}'
    $svg_minified.Trim() | Out-File "$svg_minified_dir/$($_.Name)" -Encoding utf8 -NoNewline
}
</code>```

Title: Trim Decimal Places from Numbers in a Text Editor

Body:
I have a set of SVG definition exported from Inkspace and as anyone who has done this themselves will know the resulting definition often contains far more accuracy that is actually justified. For example for a 32 x32 icon definition shown below, Inkspace has generated 6 (or more!) decimal places of accuracy per pixel. Now I know that means it will scale but in my case I would rather save space in my app which requires input of hundreds of such icon definitions.

<svg width="32" height="32"><path d="M 14.576172 5.453125 L 13.78125 8.8222656 L 12.464844 9.3691406 L 9.5625 7.5898438 L 7.5898438 9.5351562 L 9.3691406 12.576172 L 8.8222656 13.78125 L 5.4785156 14.630859 L 5.4785156 17.369141 L 8.8496094 18.246094 L 9.3691406 19.507812 L 7.5625 22.464844 L 9.5351562 24.410156 L 12.548828 22.658203 L 13.808594 23.177734 L 14.603516 26.494141 L 17.396484 26.521484 L 18.191406 23.177734 L 19.505859 22.658203 L 22.410156 24.410156 L 24.355469 22.410156 L 22.658203 19.451172 L 23.150391 18.191406 L 26.492188 17.369141 L 26.492188 14.630859 L 23.123047 13.726562 L 22.630859 12.521484 L 24.410156 9.5351562 L 22.410156 7.5898438 L 19.451172 9.3417969 L 18.246094 8.8222656 L 17.396484 5.453125 L 14.576172 5.453125 z M 15.984375 12.082031 A 3.9078221 3.9078221 0 0 1 19.892578 15.988281 A 3.9078221 3.9078221 0 0 1 15.984375 19.896484 A 3.9078221 3.9078221 0 0 1 12.078125 15.988281 A 3.9078221 3.9078221 0 0 1 15.984375 12.082031 Z" fill="#f9f9f9" /></svg>

So my question is how can I trim the definitions using a text editor to say 2 decimal places.

I have found that by using TextWrangler with the following grep search and replace string

(\.[0-9][0-9])([0-9][0-9][0-9][0-9][0-9][0-9])
\1

that I can search for all 6 decimal places strings and replace them with 2 decimal places. Then I can change the search and replace to

(\.[0-9][0-9])([0-9][0-9][0-9][0-9][0-9])
\1

and then to

(\.[0-9][0-9])([0-9][0-9][0-9][0-9])
\1

and finally to

(\.[0-9][0-9])([0-9][0-9][0-9])
\1

and this works.

However if someone with slightly (or a lot) more brain pixels than me, could show me how to do all of the above with just one search and replace operation, I would be very happy.

Body:
The answer depends how you insert the  content into your files.

If you manually copy the a .svg  file's content and have to manually use the steps you did above to minify the HTML, then there's definitely a better way: store your main .svgs in one folder called svgs, and call a script that minifies those .svgs into another folder called svgsminified. That way everytime you manually copy the  markup, you would use the minified version in svgsminified folder.

If your IDE adds the .svg file's markup for you, then hopefully there's a scripting function in the IDE that allows you to call an external script to pre-minify the incoming <svg> markup .

If you're using Powershell (which works on *nix and Windows), a minifying script to minify all .svgs in a folder would look something like:

# All .svgs in $svg_dir will be minified into $svg_minified_dir
$svg_dir = 'D:/svg'
$svg_minified_dir = 'D:/svgs_minified'
Get-ChildItem $svg_dir -Filter *.svg | ForEach-Object {
    $svg_content = Get-Content $_.FullName -Raw
    $svg_minified = $svg_content -replace '(\.[0-9]{2})([0-9]{1,5})', '${1}'
    $svg_minified.Trim() | Out-File "$svg_minified_dir/$($_.Name)" -Encoding utf8 -NoNewline
}


问:
How to create variable dimension image viewer with vtk and itk
I want to create image viewer with itk and vtk.But I have to define image dimension like 2D 3D.I don't want to do it.All I want is that when I read the image from harddisk ,program detect th dimension of image by itself.In other words, my program may read both 2D and 3D images and it gives me what the dimension is.
What are your suggestions about it ?</p>

答: When you read an image in itk, you have to specify with the template the type of pixel and the dimension, example : typedef itk::Image ImageType; You cannot use a fitall dimension or reader. You should declare the image and reader for both 2D and 3D. It is not a "clean" solution but you could do a "try" on both and take the working one.</p>


问:
How are data sources used in Terraform?
The Terraform Data Sources documentation tells me what a data source is, but I do not quite understand it. Can somebody give me a use case of data source? What is the difference between it and configuring something using variables?</p>

答:
Data sources can be used for a number of reasons; but their goal is to do something and then give you data.

Let's take the example from their documentation:

```<code># Find the latest available AMI that is tagged with Component = web
data "aws_ami" "web" {
  filter {
    name   = "state"
    values = ["available"]
  }

  filter {
    name   = "tag:Component"
    values = ["web"]
  }

  most_recent = true
}
</code>```

This uses the aws_ami data source - this is different than a resource! It will instead just give you information, and not create anything. This example in particular will call out to the describe-images AWS API call, pass in a few --filter options as specified, and return an object that you can get information from - take a look at these attributes!

name

owner_id

description

image_id

... The list goes on. This is really useful if I were, let's say - always wanting to pull the latest AMI matching some tags, and keep a launch configuration up to date with it. I could use this data provider rather than always have to update a variable or hard-code the ID.

Data source can be used for other reasons as well; one of my favorites is the template provider.

Good luck!

Title: How are data sources used in Terraform?

Body:
Data sources can be used for a number of reasons; but their goal is to do something and then give you data.

Let's take the example from their documentation:

# Find the latest available AMI that is tagged with Component = web
data "aws_ami" "web" {
  filter {
    name   = "state"
    values = ["available"]
  }

  filter {
    name   = "tag:Component"
    values = ["web"]
  }

  most_recent = true
}

This uses the aws_ami data source - this is different than a resource! It will instead just give you information, and not create anything. This example in particular will call out to the describe-images AWS API call, pass in a few --filter options as specified, and return an object that you can get information from - take a look at these attributes!

name

owner_id

description

image_id

... The list goes on. This is really useful if I were, let's say - always wanting to pull the latest AMI matching some tags, and keep a launch configuration up to date with it. I could use this data provider rather than always have to update a variable or hard-code the ID.

Data source can be used for other reasons as well; one of my favorites is the template provider.

Good luck!


问:
Suggestions for Python debugging tools?
Yesterday I made a simulation using Python. I had a few difficulties with variables and debugging.

Is there any software for Python, which provides a decent debugger?

Related question: What is the best way to debug my Python code?

答:
Winpdb (archived link / SourceForge.net / Google Code Archive) is a platform independent graphical GPL Python debugger with support for remote debugging over a network, multiple threads, namespace modification, embedded debugging, encrypted communication and is up to 20 times faster than pdb.

Features:

GPL license. Winpdb is Free Software.

Compatible with CPython 2.3 through 2.6 and Python 3000

Compatible with wxPython 2.6 through 2.8

Platform independent, and tested on Ubuntu Gutsy and Windows XP.

User Interfaces: rpdb2 is console based, while winpdb requires wxPython 2.6 or later.

Alternative: Fork of the official winpdb (winpdb-reborn · PyPI / GitHub)

(source: winpdb.org)

OwnerDisplayName: Masi

Title: Suggestions for Python debugging tools?

LastEditorDisplayName: J.F. Sebastian

OwnerDisplayName: nosklo


问:
Is there a way I can get Intellij to underline Groovy errors?
With some groovy errors, Intellij reports the errors in the messages window, but doesn't underline the code in red in the editor.  Is there a way to get it to do this?

Example:

```<code>static boolean example(){ x = 5 }
</code>```

With that code, when I try to compile the messages window gives an error Apparent variable 'x' was found in a static scope but doesn't refer to a local variable, static field or class.

Is it possible for IntelliJ to also underline the error in the editor (and maybe the project window to show what file the error is in too)?

答:
While IDEA on-the-fly code analyzer can detect 99% errors in the Java code without even running a compiler, it's much harder to do for dynamic languages like Groovy. So, you have to actually build your project in order to see all the compilation errors (use Build | Make).

Analyzer may be improved and will start to detect more errors in the future updates.

Body:
With some groovy errors, Intellij reports the errors in the messages window, but doesn't underline the code in red in the editor.  Is there a way to get it to do this?

Example:

static boolean example(){ x = 5 }

With that code, when I try to compile the messages window gives an error Apparent variable 'x' was found in a static scope but doesn't refer to a local variable, static field or class.

Is it possible for IntelliJ to also underline the error in the editor (and maybe the project window to show what file the error is in too)?


问:
Simplify overlapping And condition statements
I'm trying to figure out the best way to simplify conditional statements that are of the form:

```<code>if( ( A() && B() ) || ( B() && C() ) || ( C() && D() ) || .... )
{
    code
}
</code>```

The A/B/C/D/etc functions are relatively expensive, so it's not ideal that they could each be called twice.

Two alternatives I've thought of:

```<code>bool a = A();
bool b = B();
bool c = C();
bool d = D();
if( ( a && b ) || ( b && c ) || ( c && d ) || .... )
{
    code
}
</code>```

This version is not ideal because C(), D(), and any additional conditions are evaluated every time even if A() and B() were both true.  In the original version, they wouldn't have been called at all in that case.

```<code>bool b = B();
if( ( A() && b ) )
{
    code
}
else
{
    bool c = C();
    if( ( b && c ) )
    {
        code
    }
    else
    {
        bool d = D();
        if( ( c && D ) )
        {
            code
        }
        else
        {
            ...
        }
    }
}
</code>```

This version avoids any duplicate and unnecessary conditions from being evaluated, but is incredibly verbose and painful to write.

So I'm hopeful that there's some simpler but equally effective way to write it that I'm not thinking of...?

答:
This is very similar to an adjacent_find, but using adjacent_find would require reevaluating A, B, etc sometimes. We can write our own version of it that handles this by customizing on a predicate, rather than on "comparing equal":

```<code>template <typename FwdIter, typename Pred>
FwdIter find_if_consecutive(FwdIter cur, FwdIter last, Pred pred) {
    if (cur == last) return last;

    bool curMatches = false, nextMatches = pred(*cur);

    for (auto next = std::next(cur); next != last; ++cur, ++next) {
        curMatches = std::exchange(nextMatches, pred(*next));
        if (curMatches && nextMatches) return cur;
        // Note: this *might* possibly be faster by moving
        // forward by 2 when `nextMatches` is false, which
        // avoids one of the `curMatches && nextMatches`.
        // Implementation left as an exercise for the reader.
    }

    return last;
}
</code>```

This can then be used like so, if A, B, C, ... can all be function pointers of the same type:

```<code>auto fns = { A, B, C, D }; // Create an initializer_list

return fns.end()
    != find_if_consecutive(fns.begin(), fns.end(), [](auto f) { return f(); });
</code>```

Live on Wandbox

If we can't put the different expressions into a homogeneous type, we'd need a heterogeneous algorithms library; perhaps Boost Hana would work.

Body:
I'm trying to figure out the best way to simplify conditional statements that are of the form:

if( ( A() && B() ) || ( B() && C() ) || ( C() && D() ) || .... )
{
    code
}

The A/B/C/D/etc functions are relatively expensive, so it's not ideal that they could each be called twice.

Two alternatives I've thought of:

bool a = A();
bool b = B();
bool c = C();
bool d = D();
if( ( a && b ) || ( b && c ) || ( c && d ) || .... )
{
    code
}

This version is not ideal because C(), D(), and any additional conditions are evaluated every time even if A() and B() were both true.  In the original version, they wouldn't have been called at all in that case.

bool b = B();
if( ( A() && b ) )
{
    code
}
else
{
    bool c = C();
    if( ( b && c ) )
    {
        code
    }
    else
    {
        bool d = D();
        if( ( c && D ) )
        {
            code
        }
        else
        {
            ...
        }
    }
}

This version avoids any duplicate and unnecessary conditions from being evaluated, but is incredibly verbose and painful to write.

So I'm hopeful that there's some simpler but equally effective way to write it that I'm not thinking of...?

Body:
This is very similar to an adjacent_find, but using adjacent_find would require reevaluating A, B, etc sometimes. We can write our own version of it that handles this by customizing on a predicate, rather than on "comparing equal":

template <typename FwdIter, typename Pred>
FwdIter find_if_consecutive(FwdIter cur, FwdIter last, Pred pred) {
    if (cur == last) return last;

    bool curMatches = false, nextMatches = pred(*cur);

    for (auto next = std::next(cur); next != last; ++cur, ++next) {
        curMatches = std::exchange(nextMatches, pred(*next));
        if (curMatches && nextMatches) return cur;
        // Note: this *might* possibly be faster by moving
        // forward by 2 when `nextMatches` is false, which
        // avoids one of the `curMatches && nextMatches`.
        // Implementation left as an exercise for the reader.
    }

    return last;
}

This can then be used like so, if A, B, C, ... can all be function pointers of the same type:

auto fns = { A, B, C, D }; // Create an initializer_list

return fns.end()
    != find_if_consecutive(fns.begin(), fns.end(), [](auto f) { return f(); });

Live on Wandbox

If we can't put the different expressions into a homogeneous type, we'd need a heterogeneous algorithms library; perhaps Boost Hana would work.


问:
Adding Nodes to a BinarySearchTree
I ran into problem and can't figure it out why my nodes are not being added to a Binary Tree. I feel like it sets the node and than in the next loop it resets it.

E is a Customer object

T is a LinkedList, list of integers.

I'm not sure if I have to implement the Interface parent also.
I can see in console that it always sets nodes to the right.
Where's the error in my code?

Update:
If I replace in the add method

```<code>    BinaryNode<E, T> parent =  new BinaryNode<>() ;
</code>```

with

```<code>Parent<E, T> parent = this;
</code>```

Then it seems like its going into while loop and compares, I can see println statements in a console. But then I get an error:

```<code>    Exception in thread "main" java.lang.ClassCastException:
    teama.tree.BinaryNode cannot be cast to teama.tree.Parent
    at teama.tree.BinarySearchTree.add(BinarySearchTree.java:32)
    at teama.tree.TestBtree.main(TestBtree.java:44)
</code>```

and this code is highlighted and offering cast it to a BinaryNode:

```<code>    parent = (Parent<E, T>) node;
</code>```

If I remove the cast from it

```<code>    parent =  node;
</code>```

then it highlight the node with the red underline and offers it to cast back.
Why does this happen and how to fix it?

Here's the code:

```<code>public class BinaryNode<E, T> {

    /** The item associated with this node. */
    private E item;
    private T item2;

    /** The node at the root of the left subtree. */
    private BinaryNode<E, T> left;

    /** The node at the root of the right subtree. */
    private BinaryNode<E, T> right;

    public BinaryNode() {

    }

    /** Put item in a leaf node. */
    public BinaryNode(E item, T item2) {
        this.item = item;
        this.item2 = item2;

    public void setChild(int direction, BinaryNode<E, T> child) {
        if (direction < 0) {
            System.out.println("set Left");
            left = child;
        } else {
            System.out.println("set Right");
            right = child;
        }
    }
</code>```

Here's BinaryTree class

```<code>public class BinarySearchTree <E extends Comparable<E>, T>
    implements Parent<E, T>, Set<E> {
 {

    /** Root node. */
    private BinaryNode<E, T> root;

    /** A BinarySearchTree is initially empty. */
    public BinarySearchTree() {
       root = null;
    }
</code>```

Here I had to replace Parent<E,T> with the BinaryNode<E, T>, because nodes below were offered to cast by Eclipse, mismatch type.

```<code>public void add(E target, T list) {
    // Here I replaced Parent<E> parent = this;
    //  with BinaryNode<E, T> parent =  new BinaryNode<>()
    BinaryNode<E, T> parent =  new BinaryNode<>() ;
    BinaryNode<E, T> node = root;
    int comparison = 0;
    while (node != null) {
        System.out.println("While loop:");
        comparison = target.compareTo(node.getItem());
        System.out.println("Comparison=" + comparison);
        if (comparison < 0) {     // Go left
            System.out.println("Go Left");
            parent = node;
            node = node.getLeft();
        } else if (comparison == 0) {
            // It's already here
            return;
        } else {
            // Go right
            System.out.println("Go Right");
            parent = node;
            node = node.getRight();
        }
    }

    System.out.println("from add method: " + target +" list=" + list);
    // BinaryNode<E, T> newNode = new BinaryNode<E, T>(target, list);
    // newNode.setChild(comparison, newNode);
    parent.setChild(comparison, new BinaryNode<E, T>(target, list));
}
</code>```

And Parent interface:

```<code>public interface Parent<E, T> {

    /**
    * Return the left child if direction < 0, or the right child
    * otherwise.
    */
    public BinaryNode<E, T> getChild(int direction);

    /**
    * Replace the specified child of this parent with the new child.
    * If direction < 0, replace the left child.  Otherwise, replace
    * the right child.
    */
    public void setChild(int direction, BinaryNode<E, T> child);
</code>```

答: I think I got it resolved. In my BinaryNode class I haven't implemented interface parent, and that's why it was giving me mismatch error type. After I added implements Parent<E> to public class BinaryNode<E, T> it works fine now.

Title: Adding Nodes to a BinarySearchTree

Body:
I ran into problem and can't figure it out why my nodes are not being added to a Binary Tree. I feel like it sets the node and than in the next loop it resets it.

E is a Customer object

T is a LinkedList, list of integers.

I'm not sure if I have to implement the Interface parent also.
I can see in console that it always sets nodes to the right.
Where's the error in my code?

Update:
If I replace in the add method

    BinaryNode<E, T> parent =  new BinaryNode<>() ;

with

Parent<E, T> parent = this;

Then it seems like its going into while loop and compares, I can see println statements in a console. But then I get an error:

    Exception in thread "main" java.lang.ClassCastException:
    teama.tree.BinaryNode cannot be cast to teama.tree.Parent
    at teama.tree.BinarySearchTree.add(BinarySearchTree.java:32)
    at teama.tree.TestBtree.main(TestBtree.java:44)

and this code is highlighted and offering cast it to a BinaryNode:

    parent = (Parent<E, T>) node;

If I remove the cast from it

    parent =  node;

then it highlight the node with the red underline and offers it to cast back.
Why does this happen and how to fix it?

Here's the code:

public class BinaryNode<E, T> {

    /** The item associated with this node. */
    private E item;
    private T item2;

    /** The node at the root of the left subtree. */
    private BinaryNode<E, T> left;

    /** The node at the root of the right subtree. */
    private BinaryNode<E, T> right;

    public BinaryNode() {

    }

    /** Put item in a leaf node. */
    public BinaryNode(E item, T item2) {
        this.item = item;
        this.item2 = item2;

    public void setChild(int direction, BinaryNode<E, T> child) {
        if (direction < 0) {
            System.out.println("set Left");
            left = child;
        } else {
            System.out.println("set Right");
            right = child;
        }
    }

Here's BinaryTree class

public class BinarySearchTree <E extends Comparable<E>, T>
    implements Parent<E, T>, Set<E> {
 {

    /** Root node. */
    private BinaryNode<E, T> root;

    /** A BinarySearchTree is initially empty. */
    public BinarySearchTree() {
       root = null;
    }

Here I had to replace Parent<E,T> with the BinaryNode<E, T>, because nodes below were offered to cast by Eclipse, mismatch type.

public void add(E target, T list) {
    // Here I replaced Parent<E> parent = this;
    //  with BinaryNode<E, T> parent =  new BinaryNode<>()
    BinaryNode<E, T> parent =  new BinaryNode<>() ;
    BinaryNode<E, T> node = root;
    int comparison = 0;
    while (node != null) {
        System.out.println("While loop:");
        comparison = target.compareTo(node.getItem());
        System.out.println("Comparison=" + comparison);
        if (comparison < 0) {     // Go left
            System.out.println("Go Left");
            parent = node;
            node = node.getLeft();
        } else if (comparison == 0) {
            // It's already here
            return;
        } else {
            // Go right
            System.out.println("Go Right");
            parent = node;
            node = node.getRight();
        }
    }

    System.out.println("from add method: " + target +" list=" + list);
    // BinaryNode<E, T> newNode = new BinaryNode<E, T>(target, list);
    // newNode.setChild(comparison, newNode);
    parent.setChild(comparison, new BinaryNode<E, T>(target, list));
}

And Parent interface:

public interface Parent<E, T> {

    /**
    * Return the left child if direction < 0, or the right child
    * otherwise.
    */
    public BinaryNode<E, T> getChild(int direction);

    /**
    * Replace the specified child of this parent with the new child.
    * If direction < 0, replace the left child.  Otherwise, replace
    * the right child.
    */
    public void setChild(int direction, BinaryNode<E, T> child);


问:
How to calculate the multiplicator in a sum like sum += sum*(mulu^n)
I would like to calculate the spending factor in a rule where we spend Nth time the previous payment done

Here is an example of spending.

```<code>firstPaymentAmount=10
SpendingFactor=5
PaymentCount=4

payment1:    10
payment2:    50       (=  10 x 5)
payment3:   250       (=  50 x 5)
payment4:  1250       (= 250 x 5)
</code>```

At the end we get the sum of all payment made and we have :

```<code>10 + 50 + 250 + 1250 = 1560
</code>```

I would like to know the formula that let me retrieve the spending factor (=5 here) by only knowing these parameters:

```<code>paymentCount  = 4
initalPayment = 10
totalPaid     = 1560
</code>```

By knowing the formula to calculate the spendingFactor, I will then be able to know the amount and detail of each payment.

答:
I've came with a solution. It gets an approximation of the spending factor because there is no direct formula.

Getting the exact spending factor is too CPU intensive. So, I'm calculating a near approximation first. This value will always be above the solution. I then decrease that number until I'm getting below the total paid amount.

Here is a PHP sample of what I've done.

```<code>$paymentCount   = 4;
$initialPayment = 10;
$totalPaid      = 1560;

//----- precalculate the factor based on total payment for faster computation
//----- this predefined factor will always be above our final factor

$estimatedSpendingFactor = exp(log($totalPaid) / $paymentCount);

//----- find the estimated spending factor

do
{
    $estimatedSpendingFactor -= 0.0001;

    $y = $initialPayment * (pow($estimatedSpendingFactor, $paymentCount) - 1)
                         / ($estimatedSpendingFactor-1);
}
while ($y > $totalPaid);

//-----

printf("The spending factor is %f\n", $estimatedSpendingFactor);
</code>```

the output will be :

```<code>The spending factor is : 5.000000
</code>```

Body:
I would like to calculate the spending factor in a rule where we spend Nth time the previous payment done

Here is an example of spending.

firstPaymentAmount=10
SpendingFactor=5
PaymentCount=4

payment1:    10
payment2:    50       (=  10 x 5)
payment3:   250       (=  50 x 5)
payment4:  1250       (= 250 x 5)

At the end we get the sum of all payment made and we have :

10 + 50 + 250 + 1250 = 1560

I would like to know the formula that let me retrieve the spending factor (=5 here) by only knowing these parameters:

paymentCount  = 4
initalPayment = 10
totalPaid     = 1560

By knowing the formula to calculate the spendingFactor, I will then be able to know the amount and detail of each payment.

Body:
I've came with a solution. It gets an approximation of the spending factor because there is no direct formula.

Getting the exact spending factor is too CPU intensive. So, I'm calculating a near approximation first. This value will always be above the solution. I then decrease that number until I'm getting below the total paid amount.

Here is a PHP sample of what I've done.

$paymentCount   = 4;
$initialPayment = 10;
$totalPaid      = 1560;

//----- precalculate the factor based on total payment for faster computation
//----- this predefined factor will always be above our final factor

$estimatedSpendingFactor = exp(log($totalPaid) / $paymentCount);

//----- find the estimated spending factor

do
{
    $estimatedSpendingFactor -= 0.0001;

    $y = $initialPayment * (pow($estimatedSpendingFactor, $paymentCount) - 1)
                         / ($estimatedSpendingFactor-1);
}
while ($y > $totalPaid);

//-----

printf("The spending factor is %f\n", $estimatedSpendingFactor);

the output will be :

The spending factor is : 5.000000


问:
Visual Studio Code highlighting and clicking copy pastes
When I highlight some text with my mouse and then click off of the highlighted text, sometimes it copy pastes that text right after what was highlighted. I don't want it to copy paste on click, I just want it to unhighlight. I looked through the settings and configurations of my VS code, and couldn't find a way to turn it off. Any ideas?</p>

答:
The behavior you mention sounds a lot like the copy, drag and drop functionality that vscode offers and I occasionally accidentally trigger.  It can be disabled by setting to false:

// Controls if the editor should allow to move selections via drag and drop.

"editor.dragAndDrop": false,


问:
What is the fastest animation on the iPad
What is the fastest animation on the iPad? There are multiple flipping types, what is the fastest one?</p>

答:
You are limited by the hardware display refresh to a maximum of 60 fps.

You can do any of OpenGL, CG drawing in a drawRect, manual CALayer animation frame swaps, or use Core Animation at that frame rate if you are very very careful about how much you do on the UI thread during each frame time.


答:
Something like this?

```<code>SELECT
    ID
    , Column1
    , Column2
FROM
    (
        SELECT
            ID
            , Column1
            , Column2
            , ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Column1, Column2) R
        FROM YourTable
    ) Q
WHERE R > 1
</code>```

Update for Edit 2:

```<code>SELECT
    id_aux
    , city_aux
    , state_aux
    , g_aux
    , r_aux
FROM
    (
        SELECT
            id_aux
            , city_aux
            , state_aux
            , g_aux
            , r_aux
            , ROW_NUMBER() OVER (PARTITION BY id_aux ORDER BY id_aux) R
        FROM YourTable
    ) Q
WHERE R > 1
</code>```

Title: SQL How to SELECT all rows with repeated id's but not the first of each one?

Body:
Something like this?

SELECT
    ID
    , Column1
    , Column2
FROM
    (
        SELECT
            ID
            , Column1
            , Column2
            , ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Column1, Column2) R
        FROM YourTable
    ) Q
WHERE R > 1

Update for Edit 2:

SELECT
    id_aux
    , city_aux
    , state_aux
    , g_aux
    , r_aux
FROM
    (
        SELECT
            id_aux
            , city_aux
            , state_aux
            , g_aux
            , r_aux
            , ROW_NUMBER() OVER (PARTITION BY id_aux ORDER BY id_aux) R
        FROM YourTable
    ) Q
WHERE R > 1


问:
Neo4j cypher - filter out child nodes
Imagine the following graph:

The goal is to query for all connecting nodes between two entities ("Main" and "Other" in this case), but filter out mutual descendants. In other words, I would like the result set to only contain a and b, but not c, because C is a descendant of B, which is already included in the result set.

答:
I reproduced your scenario using this sample data set:

This query should work:

```<code>// match common child nodes between 'main' and 'other'
MATCH (:Node {name : "Main"})-[:child]->(child:Node)<-[:child]-(:Node {name : "Other"})
// match the children of child when exists
OPTIONAL MATCH (child)-[:child]->(n:Node)
// store children and childrenOfChild in separeted arrays
WITH collect(child) as children, collect(n) as childrenOfChild
// filter ...
WITH filter(child in children WHERE NOT child IN childrenOfChild) as directChildren
UNWIND directChildren as directChild
// return only direct child
RETURN directChild
</code>```

The output:

```<code>╒═════════════╕
│"directChild"│
╞═════════════╡
│{"name":"b"} │
├─────────────┤
│{"name":"a"} │
└─────────────┘
</code>```

Title: Neo4j cypher - filter out child nodes

Body:
I reproduced your scenario using this sample data set:

This query should work:

// match common child nodes between 'main' and 'other'
MATCH (:Node {name : "Main"})-[:child]->(child:Node)<-[:child]-(:Node {name : "Other"})
// match the children of child when exists
OPTIONAL MATCH (child)-[:child]->(n:Node)
// store children and childrenOfChild in separeted arrays
WITH collect(child) as children, collect(n) as childrenOfChild
// filter ...
WITH filter(child in children WHERE NOT child IN childrenOfChild) as directChildren
UNWIND directChildren as directChild
// return only direct child
RETURN directChild

The output:

╒═════════════╕
│"directChild"│
╞═════════════╡
│{"name":"b"} │
├─────────────┤
│{"name":"a"} │
└─────────────┘


问:
Move positions in a table - R
In R, considering a generic matrix A, how can I move the triangle NA to the position in matrix B? What about if the matrix is m x n?

```<code>> A <- matrix(c(3, NA, NA, 4, 2, NA, 1, 5, 3), nrow = 3)
> A
     [,1] [,2] [,3]
[1,]    3    4    1
[2,]   NA    2    5
[3,]   NA   NA    3

> B <- matrix(c(3, 2, 3, 4, 5, NA, 1, NA, NA), nrow = 3)
> B
     [,1] [,2] [,3]
[1,]    3    4    1
[2,]    2    5   NA
[3,]    3   NA   NA
</code>```

Thanks!

Title: Move positions in a table - R

Body:
In R, considering a generic matrix A, how can I move the triangle NA to the position in matrix B? What about if the matrix is m x n?

> A <- matrix(c(3, NA, NA, 4, 2, NA, 1, 5, 3), nrow = 3)
> A
     [,1] [,2] [,3]
[1,]    3    4    1
[2,]   NA    2    5
[3,]   NA   NA    3

> B <- matrix(c(3, 2, 3, 4, 5, NA, 1, NA, NA), nrow = 3)
> B
     [,1] [,2] [,3]
[1,]    3    4    1
[2,]    2    5   NA
[3,]    3   NA   NA

Thanks!

Body:
I don't know if there's a more idiomatic way, but this seems to do what you want:

A <- matrix(c(3, NA, NA, 4, 2, NA, 1, 5, 3), nrow = 3)
A

     [,1] [,2] [,3]
[1,]    3    4    1
[2,]   NA    2    5
[3,]   NA   NA    3

t(apply(A, 1, function(x) x[order(is.na(x))]))

     [,1] [,2] [,3]
[1,]    3    4    1
[2,]    2    5   NA
[3,]    3   NA   NA

A <- matrix(c(3, NA, NA, NA, 4, 2, NA, NA, 1, 5, 3, NA), nrow=4)
A

     [,1] [,2] [,3]
[1,]    3    4    1
[2,]   NA    2    5
[3,]   NA   NA    3
[4,]   NA   NA   NA

t(apply(A, 1, function(x) x[order(is.na(x))]))

     [,1] [,2] [,3]
[1,]    3    4    1
[2,]    2    5   NA
[3,]    3   NA   NA
[4,]   NA   NA   NA

A <- matrix(c(3, NA, NA, 4, 2, NA, 1, 5, 3, 6, 7, 8), nrow=3)
A

     [,1] [,2] [,3] [,4]
[1,]    3    4    1    6
[2,]   NA    2    5    7
[3,]   NA   NA    3    8

t(apply(A, 1, function(x) x[order(is.na(x))]))

     [,1] [,2] [,3] [,4]
[1,]    3    4    1    6
[2,]    2    5    7   NA
[3,]    3    8   NA   NA


问:
Token is getting invalidated using nodejs speakeasy library
My purpose is to expire a token after 1hr (3600 secs). While trying with nodejs speakeasy the token is getting invalidated much before that. The below logs are for "1, 10 and 60 minutes" and that also getting invalidated muche before the 1 minute. Max of the time I am getting inconsistent results.

Partial code snippet

```<code>let secret = speakeasy.generateSecret({
length: 10
});
let seconds= 3600; //1Hr

let token = speakeasy.totp({
  secret: secret.base32,
  step: seconds
});

let otp = {
  "secret": secret.base32.toString(),
  "token": token
};

function checkOTP(otp) {
  let verified = speakeasy.totp.verify({
    secret: otp.secret,
    token: otp.token,
    step: seconds
});
return verified;
}
</code>```

Am I doing something wrong? Few console logs from a sample script:

```<code>For 1 minute - Invalidated before 18secs
[ Fri Dec 08 2017 09:16:18 GMT-0800 (Pacific Standard Time) ](true) 9:16:59 AM
[ Fri Dec 08 2017 09:16:18 GMT-0800 (Pacific Standard Time) ](false) 9:17:00 AM

For 10Mins - Invalidated before 7minutes
[ Fri Dec 08 2017 09:18:28 GMT-0800 (Pacific Standard Time) ](true) 9:19:59 AM
[ Fri Dec 08 2017 09:18:28 GMT-0800 (Pacific Standard Time) ](true) 9:19:59 AM
[ Fri Dec 08 2017 09:18:28 GMT-0800 (Pacific Standard Time) ](true) 9:19:59 AM
[ Fri Dec 08 2017 09:18:28 GMT-0800 (Pacific Standard Time) ](true) 9:19:59 AM
[ Fri Dec 08 2017 09:18:28 GMT-0800 (Pacific Standard Time) ](false) 9:20:00 AM

For 1Hr - Invalidated before 7minutes
[ Fri Dec 08 2017 11:07:01 GMT-0800 (Pacific Standard Time) ](true) 11:56:41 AM
[ Fri Dec 08 2017 11:07:01 GMT-0800 (Pacific Standard Time) ](true) 11:56:43 AM
[ Fri Dec 08 2017 11:07:01 GMT-0800 (Pacific Standard Time) ](false) 12:00:37 PM
</code>```

What is the appropriate way to validate within the above window?

答:
From the readme of speakeasy it looks like your token parameters are wrong:

```<code>var token = speakeasy.totp({
  secret: secret.base32,
  encoding: 'base32',
  time: 1453667708 // You have this as 'step' not 'time'
});
</code>```

Body:
My purpose is to expire a token after 1hr (3600 secs). While trying with nodejs speakeasy the token is getting invalidated much before that. The below logs are for "1, 10 and 60 minutes" and that also getting invalidated muche before the 1 minute. Max of the time I am getting inconsistent results.

Partial code snippet

let secret = speakeasy.generateSecret({
length: 10
});
let seconds= 3600; //1Hr

let token = speakeasy.totp({
  secret: secret.base32,
  step: seconds
});

let otp = {
  "secret": secret.base32.toString(),
  "token": token
};

function checkOTP(otp) {
  let verified = speakeasy.totp.verify({
    secret: otp.secret,
    token: otp.token,
    step: seconds
});
return verified;
}

Am I doing something wrong? Few console logs from a sample script:

For 1 minute - Invalidated before 18secs
[ Fri Dec 08 2017 09:16:18 GMT-0800 (Pacific Standard Time) ](true) 9:16:59 AM
[ Fri Dec 08 2017 09:16:18 GMT-0800 (Pacific Standard Time) ](false) 9:17:00 AM

For 10Mins - Invalidated before 7minutes
[ Fri Dec 08 2017 09:18:28 GMT-0800 (Pacific Standard Time) ](true) 9:19:59 AM
[ Fri Dec 08 2017 09:18:28 GMT-0800 (Pacific Standard Time) ](true) 9:19:59 AM
[ Fri Dec 08 2017 09:18:28 GMT-0800 (Pacific Standard Time) ](true) 9:19:59 AM
[ Fri Dec 08 2017 09:18:28 GMT-0800 (Pacific Standard Time) ](true) 9:19:59 AM
[ Fri Dec 08 2017 09:18:28 GMT-0800 (Pacific Standard Time) ](false) 9:20:00 AM

For 1Hr - Invalidated before 7minutes
[ Fri Dec 08 2017 11:07:01 GMT-0800 (Pacific Standard Time) ](true) 11:56:41 AM
[ Fri Dec 08 2017 11:07:01 GMT-0800 (Pacific Standard Time) ](true) 11:56:43 AM
[ Fri Dec 08 2017 11:07:01 GMT-0800 (Pacific Standard Time) ](false) 12:00:37 PM

What is the appropriate way to validate within the above window?

Body:
From the readme of speakeasy it looks like your token parameters are wrong:

var token = speakeasy.totp({
  secret: secret.base32,
  encoding: 'base32',
  time: 1453667708 // You have this as 'step' not 'time'
});


问:
fileDownload.js jQuery plugin and PHP headers
I am using this great jquery.fileDownload.js plugin to allow users to download self-generated CSV files from my website.

From what I understood, based in the PHP code from this site (suggested by fileDownload creator), I need to set a cookie to identify when the download is sucessfull or not:

```<code>try {
    $page = file_get_contents($filepath);
    echo $page;
    header('Set-Cookie: fileDownload=true; path=/');
} catch(Exception $e) {
    header('Set-Cookie: fileDownload=false; path=/');
}
</code>```

It works as expected when fileDownload=true, but fail event is never fired when fileDownload=false.

Here is my javascript code:

```<code>$.fileDownload('export.php')
    .done(function() {
        alert('Done!');
    })
    .fail(function() {
        alert('Fail!');
    });
</code>```

And here is my export.php code:

```<code>header('Pragma: no-cache');
header('Cache-Control: no-cache, must-revalidate');
header('Content-type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="file.csv"');
try {
    // Code for generating the CSV file
    header('Set-Cookie: fileDownload=true; path=/');
} catch(Exception $e) {
    header('Set-Cookie: fileDownload=false; path=/');
}
exit;
</code>```

When file is generated correcly I got the success message, but never get the fail message, even when simulating an issue.

Please, what I am missing? Thank you!

答:
It looks like the cookie is only used to check if a download was completed, but not to assess failure. But it does catch HTTP errors, so the solution is simply sending a 500 from the server:</p>

```<code>try {
    $page = file_get_contents($filepath);
    echo $page;
    header('Set-Cookie: fileDownload=true; path=/');
} catch(Exception $e) {
    http_response_code(500);
}
</code>```

Body:
I am using this great jquery.fileDownload.js plugin to allow users to download self-generated CSV files from my website.

From what I understood, based in the PHP code from this site (suggested by fileDownload creator), I need to set a cookie to identify when the download is sucessfull or not:

try {
    $page = file_get_contents($filepath);
    echo $page;
    header('Set-Cookie: fileDownload=true; path=/');
} catch(Exception $e) {
    header('Set-Cookie: fileDownload=false; path=/');
}

It works as expected when fileDownload=true, but fail event is never fired when fileDownload=false.

Here is my javascript code:

$.fileDownload('export.php')
    .done(function() {
        alert('Done!');
    })
    .fail(function() {
        alert('Fail!');
    });

And here is my export.php code:

header('Pragma: no-cache');
header('Cache-Control: no-cache, must-revalidate');
header('Content-type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="file.csv"');
try {
    // Code for generating the CSV file
    header('Set-Cookie: fileDownload=true; path=/');
} catch(Exception $e) {
    header('Set-Cookie: fileDownload=false; path=/');
}
exit;

When file is generated correcly I got the success message, but never get the fail message, even when simulating an issue.

Please, what I am missing? Thank you!

Body:
It looks like the cookie is only used to check if a download was completed, but not to assess failure. But it does catch HTTP errors, so the solution is simply sending a 500 from the server:

try {
    $page = file_get_contents($filepath);
    echo $page;
    header('Set-Cookie: fileDownload=true; path=/');
} catch(Exception $e) {
    http_response_code(500);
}


问:
Pass ngModel in child component for common error handling
i am trying to pass ngModel in child component to displaying error from common component.

It giving error like.
Template parse errors:No provider for NgControl.

can any one please check the code and let me know what i am missing.

Plunker

Parent component

```<code>      <div>
  <h2>Hello {{name}}</h2>
  <form #countryForm="ngForm">
    <div class="form-group row">
      <label for="txtCountryName" class="col-sm-3 col-form-label">Country Name</label>
      <div class="col-sm-9">
        <input type="text" [(ngModel)]="name" ngModel #countryName="ngModel" name="name" class="form-control" id="txtCountryName" placeholder="Country Name"              required minlength="5" maxlength="15">
        <app-error-message [formControl]="countryName"></app-error-message>
      </div>
    </div>
  </form>
</div>
</code>```

Child component

```<code>@Component({
selector: 'app-error-message',
template: `<ng-container *ngIf="formControl">
            <div [hidden]="(formControl.valid || formControl.pristine) && (formControl.errors == null || formControl.errors.invalid == null)" class="alert alert-danger">
              {{GetValidationMessage()}}
            </div>
          </ng-container>`

  })

export class ErrorMessageComponent  {
@Input() public formControl: any = null;

public GetValidationMessage() {
    let errorMessage: string = "";
    if (this.formControl.errors) {
        if (this.formControl.dirty || this.formControl.touched) {
            if (this.formControl.errors.required != null) {
                errorMessage = "This field is required.";
            }
            if (this.formControl.errors.minlength != null) {
                errorMessage += "This field must be 8 characters long, we need another " + (this.formControl.errors.minlength.requiredLength - this.formControl.errors.minlength.actualLength) + " characters";
            }
        }
        if (this.formControl.errors.invalid != null) {
            errorMessage += this.formControl.errors.errorMessage;
        }
    }
    return errorMessage;
}
</code>```

}

答:
try accessing the local template reference variable #countryName, in the parent component. through @ViewChild

Then set a property public countryName: any equal to the local template variable.

//Parent Component

```<code>export class ParentComp implements AfterViewInIt{
      @ViewChild('add_template_reference_variable_here') countryNameRef;
      public countryName: any;

      ngAfterViewInit(): void {
       this.countryName = this.countryNameRef;
      }
}
</code>```

And then bind new variable to [formControl]="countryName"

// Parent Html Template

```<code><app-error-message [formControl]="countryName"></app-error-message>
</code>```

Body:
i am trying to pass ngModel in child component to displaying error from common component.

It giving error like.
Template parse errors:No provider for NgControl.

can any one please check the code and let me know what i am missing.

Plunker

Parent component

Hello {{name}}

  <form #countryForm="ngForm">

      Country Name

        <input type="text" [(ngModel)]="name" ngModel #countryName="ngModel" name="name" class="form-control" id="txtCountryName" placeholder="Country Name"              required minlength="5" maxlength="15">
        <app-error-message [formControl]="countryName"></app-error-message>

  </form>

Child component

@Component({
selector: 'app-error-message',
template: `<ng-container *ngIf="formControl">

              {{GetValidationMessage()}}

          </ng-container>`

  })

export class ErrorMessageComponent  {
@Input() public formControl: any = null;

public GetValidationMessage() {
    let errorMessage: string = "";
    if (this.formControl.errors) {
        if (this.formControl.dirty || this.formControl.touched) {
            if (this.formControl.errors.required != null) {
                errorMessage = "This field is required.";
            }
            if (this.formControl.errors.minlength != null) {
                errorMessage += "This field must be 8 characters long, we need another " + (this.formControl.errors.minlength.requiredLength - this.formControl.errors.minlength.actualLength) + " characters";
            }
        }
        if (this.formControl.errors.invalid != null) {
            errorMessage += this.formControl.errors.errorMessage;
        }
    }
    return errorMessage;
}

}

Body:
try accessing the local template reference variable #countryName, in the parent component. through @ViewChild

Then set a property public countryName: any equal to the local template variable.

//Parent Component

export class ParentComp implements AfterViewInIt{
      @ViewChild('add_template_reference_variable_here') countryNameRef;
      public countryName: any;

      ngAfterViewInit(): void {
       this.countryName = this.countryNameRef;
      }
}

And then bind new variable to [formControl]="countryName"

// Parent Html Template

<app-error-message [formControl]="countryName"></app-error-message>


问:
Bootstrap 4 container with full width image
It doesn't have to be bootstrap 4. I'm stuck and need help. trying to dive page into 2 sections. Left side has full width bg image. thats the problem and need help with css and html

My html code:

```<code><div class=left-bg-img>
<div class="container">
<div class="col-sm-6">
<p>Left content goes here.</p>
</div>
<div/><!--left-bg-->

<div class="col-sm-6">
<p>Right content goes here.</p>
</div>
</div>
</code>```

image example

答:
With Bootstrap 4, this works...

```<code><section>
  <div class="side-image"></div>
  <div class="container">
    <div class="row">
      <div class="col-sm-6 ml-sm-auto">
        <p>Some content over to the right.</p>
      </div>
    </div>
  </div>
</section>

<style>
.section-with-side-image {
  position: relative;
}
.side-image {
  position:absolute;
  top:0;
  bottom:0;
  right: 50%;
  left: 0;
  background-image: url('http://placehold.it/900/');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}
</style>
</code>```

https://codepen.io/Gwapedwink/pen/JOgXJw

Note: You seem to have forgotten the .row around the columns. So you will see that in my example.

Second Note: I added the .ml-sm-auto class to the col-sm-6, as it doesn't need the filler or an offset, that's not how Bootstrap 4 works.

Body:
It doesn't have to be bootstrap 4. I'm stuck and need help. trying to dive page into 2 sections. Left side has full width bg image. thats the problem and need help with css and html

My html code:

Left content goes here.

Right content goes here.

image example

Body:
With Bootstrap 4, this works...

<section>
  <div class="side-image"></div>
  <div class="container">
    <div class="row">
      <div class="col-sm-6 ml-sm-auto">
        <p>Some content over to the right.</p>
      </div>
    </div>
  </div>
</section>

<style>
.section-with-side-image {
  position: relative;
}
.side-image {
  position:absolute;
  top:0;
  bottom:0;
  right: 50%;
  left: 0;
  background-image: url('http://placehold.it/900/');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}
</style>

https://codepen.io/Gwapedwink/pen/JOgXJw

Note: You seem to have forgotten the .row around the columns. So you will see that in my example.

Second Note: I added the .ml-sm-auto class to the col-sm-6, as it doesn't need the filler or an offset, that's not how Bootstrap 4 works.