问:
PDFsharp image to XImage
I created a barcode as an image in my ASP.NET MVC app.

```<code>BarcodeLib.Barcode barcode = new BarcodeLib.Barcode()
{
    IncludeLabel = false,
    Alignment = AlignmentPositions.LEFT,
    Width = element.BarcodeWidth,
    Height = element.BarcodeHeight,
    RotateFlipType = RotateFlipType.RotateNoneFlipNone,
    BackColor = Color.Transparent,
    ForeColor = Color.Black,
    ImageFormat = System.Drawing.Imaging.ImageFormat.Png
 };
</code>```

This will create a barcode with the BarcodeLib.

How do I convert it to an XImage of PDFsharp?

```<code>Image img = barcode.Encode(TYPE.CODE128, "123456789");
gfx.DrawImage(xImage, 0, 0, 100, 100);
</code>```

答:
If you use the GDI build of PDFsharp then you can call the XImage.FromImage method.

With any build of PDFsharp you can write an PNG image to a MemoryStream and then get an XImage from that MemoryStream.

Title: PDFsharp image to XImage

Body:
I created a barcode as an image in my ASP.NET MVC app.

BarcodeLib.Barcode barcode = new BarcodeLib.Barcode()
{
    IncludeLabel = false,
    Alignment = AlignmentPositions.LEFT,
    Width = element.BarcodeWidth,
    Height = element.BarcodeHeight,
    RotateFlipType = RotateFlipType.RotateNoneFlipNone,
    BackColor = Color.Transparent,
    ForeColor = Color.Black,
    ImageFormat = System.Drawing.Imaging.ImageFormat.Png
 };

This will create a barcode with the BarcodeLib.

How do I convert it to an XImage of PDFsharp?

Image img = barcode.Encode(TYPE.CODE128, "123456789");
gfx.DrawImage(xImage, 0, 0, 100, 100);


来源: stackexchange

问:
Perl, how to read argv as hash?
So, I've read some guides about how to use Getopt::Long and similar libs to work with argv options, and still has no clue how to use it properly because of totally unclear (as for me) documentation and guides.

I have a script. It has next arguments:
-qp,
-pr,
-rp,
-vr, and most of them are for filenames.

Currently I have this use of Getopt::Long, which I find unsuitable because I need to check what is after option every time:

```<code>for(my $i = 0; $i < @ARGV; $i+=2){
    if ($ARGV[$i] eq "-qp"){
        unless ($ARGV[$i+1] eq "-vr" or $ARGV[$i+1] eq "-pr" or $ARGV[$i+1] eq "-rp"){
            $query_params = $ARGV[$i+1];
        }
    }
    elsif ($ARGV[$i] eq "-pr"){
        unless ($ARGV[$i+1] eq "-qp" or $ARGV[$i+1] eq "-pr" or $ARGV[$i+1] eq "-rp"){
            $params = $ARGV[$i+1];
        }
    }
    elsif ($ARGV[$i] eq "-vr"){
        unless ($ARGV[$i+1] eq "-vr" or $ARGV[$i+1] eq "-qp" or $ARGV[$i+1] eq "-rp"){
            $variables = $ARGV[$i+1];
        }
    }
    elsif ($ARGV[$i] eq "-rp"){
        unless ($ARGV[$i+1] eq "-qp" or $ARGV[$i+1] eq "-pr" or $ARGV[$i+1] eq "-vr"){
            $replace = $ARGV[$i+1];
        }
    }
}
</code>```

Maybe I don't need to use exact Getopt libs for Unix, I need just to pass some args to script. Is there any way to make it more simple and correct?

答:
Contrary to your claims, you aren't using Getopt::Long. But you should!

```<code>use strict;
use warnings qw( all );
use feature qw( say );

use File::Basename qw( basename );
use Getopt::Long   qw( );

my %opts;

sub parse_args {
   %opts = ();
   Getopt::Long::Configure(qw( posix_default ));
   GetOptions(
      'help|h|?' => \&help,
      'qp:s' => \$opts{qp},
      'pr:s' => \$opts{pr},
      'rp:s' => \$opts{rp},
      'vr:s' => \$opts{vr},
   )
      or usage();
}

parse_args();
</code>```

Using :s instead of =s makes the option's argument optional as requested in the comments.

Sample helper subs to complete the above:

```<code>sub help {
   my $prog = basename($0);
   say "usage: $prog [options]";
   say "       $prog --help";
   say "";
   say "Options:";
   say "   --qp path   ...explanation...";
   say "   --qp        ...explanation...";
   say "   --pr path   ...explanation...";
   say "   --pr        ...explanation...";
   say "   --rp path   ...explanation...";
   say "   --rp        ...explanation...";
   say "   --vr path   ...explanation...";
   say "   --vr        ...explanation...";
   exit(0);
}

sub usage {
   my $prog = basename($0);
   warn(@_) if @_;
   warn("Try `$prog --help' for more information\n");
   exit(1);
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Perl, how to read argv as hash?

Body:
So, I've read some guides about how to use Getopt::Long and similar libs to work with argv options, and still has no clue how to use it properly because of totally unclear (as for me) documentation and guides.

I have a script. It has next arguments:
-qp,
-pr,
-rp,
-vr, and most of them are for filenames.

Currently I have this use of Getopt::Long, which I find unsuitable because I need to check what is after option every time:

for(my $i = 0; $i < @ARGV; $i+=2){
    if ($ARGV[$i] eq "-qp"){
        unless ($ARGV[$i+1] eq "-vr" or $ARGV[$i+1] eq "-pr" or $ARGV[$i+1] eq "-rp"){
            $query_params = $ARGV[$i+1];
        }
    }
    elsif ($ARGV[$i] eq "-pr"){
        unless ($ARGV[$i+1] eq "-qp" or $ARGV[$i+1] eq "-pr" or $ARGV[$i+1] eq "-rp"){
            $params = $ARGV[$i+1];
        }
    }
    elsif ($ARGV[$i] eq "-vr"){
        unless ($ARGV[$i+1] eq "-vr" or $ARGV[$i+1] eq "-qp" or $ARGV[$i+1] eq "-rp"){
            $variables = $ARGV[$i+1];
        }
    }
    elsif ($ARGV[$i] eq "-rp"){
        unless ($ARGV[$i+1] eq "-qp" or $ARGV[$i+1] eq "-pr" or $ARGV[$i+1] eq "-vr"){
            $replace = $ARGV[$i+1];
        }
    }
}

Maybe I don't need to use exact Getopt libs for Unix, I need just to pass some args to script. Is there any way to make it more simple and correct?

Body:
Contrary to your claims, you aren't using Getopt::Long. But you should!

use strict;
use warnings qw( all );
use feature qw( say );

use File::Basename qw( basename );
use Getopt::Long   qw( );

my %opts;

sub parse_args {
   %opts = ();
   Getopt::Long::Configure(qw( posix_default ));
   GetOptions(
      'help|h|?' => \&help,
      'qp:s' => \$opts{qp},
      'pr:s' => \$opts{pr},
      'rp:s' => \$opts{rp},
      'vr:s' => \$opts{vr},
   )
      or usage();
}

parse_args();

Using :s instead of =s makes the option's argument optional as requested in the comments.

Sample helper subs to complete the above:

sub help {
   my $prog = basename($0);
   say "usage: $prog [options]";
   say "       $prog --help";
   say "";
   say "Options:";
   say "   --qp path   ...explanation...";
   say "   --qp        ...explanation...";
   say "   --pr path   ...explanation...";
   say "   --pr        ...explanation...";
   say "   --rp path   ...explanation...";
   say "   --rp        ...explanation...";
   say "   --vr path   ...explanation...";
   say "   --vr        ...explanation...";
   exit(0);
}

sub usage {
   my $prog = basename($0);
   warn(@_) if @_;
   warn("Try `$prog --help' for more information\n");
   exit(1);
}

ContentLicense: CC BY-SA 3.0


问:
How to get "location" UIToolbar button?
I was looking to add a "locate" button similar to the one in Apple's Map app.

^There

I looked in the options for bordered buttons but it's not listed.  How can I add one of these?

Thanks in advance.

答:
You have to create it yourself.

For example, using this method of UIBarButtonItem:

```<code>- (id)initWithImage:(UIImage *)image style:(UIBarButtonItemStyle)style target:(id)target action:(SEL)action
</code>```

ContentLicense: CC BY-SA 2.5

Title: How to get "location" UIToolbar button?

Body:
You have to create it yourself.

For example, using this method of UIBarButtonItem:

- (id)initWithImage:(UIImage *)image style:(UIBarButtonItemStyle)style target:(id)target action:(SEL)action


问:
calling two js functions one after another using one button
Here is my code, not working please help I want to call two js functions using one submit button.I have tried the below code.But it gives error.

function scrollWin() {

    // First time click
    if (e.name != 'Click') {
        e.name = "Click";

        function scrollWin() {
            window.scrollBy(0, 85);
        }
    }

    // When click it again..
    else if (e.name == 'Click') {
        e.name = "Unclick";

        function myFunction() {
            document.getElementById("demo").innerHTML = "
 Second Click
";
        }
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="button" onclick="scrollWin(); this.style.visibility= 'hidden';
myFunction()" value="Click Me" />

<p id="demo"></p></code>```

答:
What I understand you want to perform two operation on same button but in two different condition, if you want to perform keep state and perform action according to that then. Like:

```<code>    function scrollWin(e) {
    var btn = e.target;

    var state = btn.dataset.myattr;

    if( state == 'state1'){
        btn.dataset.myattr = 'state2';
        e.name = "Click";
        window.scrollBy(0, 85);
    }else if (state == 'state2'){
        btn.dataset.myattr = 'state1';
        e.name = "Unclick";
        document.getElementById("demo").innerHTML = "<h2> Second Click </h2>";
    }
}
</code>```

If you want to change the name attribute to something else you can do that and you don't have to change the JS code for that.

Body:
Here is my code, not working please help I want to call two js functions using one submit button.I have tried the below code.But it gives error.

function scrollWin() {

    // First time click
    if (e.name != 'Click') {
        e.name = "Click";

        function scrollWin() {
            window.scrollBy(0, 85);
        }
    }

    // When click it again..
    else if (e.name == 'Click') {
        e.name = "Unclick";

        function myFunction() {
            document.getElementById("demo").innerHTML = "
 Second Click
";
        }
    }
}

<input type="button" onclick="scrollWin(); this.style.visibility= 'hidden';
myFunction()" value="Click Me" />

Body:
What I understand you want to perform two operation on same button but in two different condition, if you want to perform keep state and perform action according to that then. Like:

    function scrollWin(e) {
    var btn = e.target;

    var state = btn.dataset.myattr;

    if( state == 'state1'){
        btn.dataset.myattr = 'state2';
        e.name = "Click";
        window.scrollBy(0, 85);
    }else if (state == 'state2'){
        btn.dataset.myattr = 'state1';
        e.name = "Unclick";
        document.getElementById("demo").innerHTML = "<h2> Second Click </h2>";
    }
}

If you want to change the name attribute to something else you can do that and you don't have to change the JS code for that.


问:
ld: library not found for -lVuforia
I'm integrating unity project to native ios project in c++. But I'm getting error

```<code>ld: library not found for -lVuforia
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

while building xcode project.

I'm using

xCode : 8.2.1

Unity : 5.6.1f1

答:
It doesn't look like you have the "Vuforia" library included in your build.
Under your Unity project, look for a file called Vuforia.framework. This file's inspector should have "iOS" marked in it, so it gets included in the generated Xcode project.</p>

Title: ld: library not found for -lVuforia

Body:
I'm integrating unity project to native ios project in c++. But I'm getting error

ld: library not found for -lVuforia
clang: error: linker command failed with exit code 1 (use -v to see invocation)

while building xcode project.

I'm using

xCode : 8.2.1

Unity : 5.6.1f1


问:
Insert From XML File
I'm attempting to update a customer table using an XML file, but it's not pulling the values from the XML into the variables to pass into the table. The error I get says "Cannot insert the value NULL into column 'EmailAddress'" even though there is clearly a value for EmailAddress. I feel like I'm missing something very simple, but can't figure it out. Any thoughts?</p>

```<code>USE MyGuitarShop

DECLARE @CustomerUpdate XML

SET @CustomerUpdate =
    '<NewCustomers>
        <Customer EmailAddress="izzychan@yahoo.com" Password="" FirstName="Isabella" LastName="Chan" />
        <Customer EmailAddress="johnprine@gmail.com" Password="" FirstName="John" LastName="Prine" />
        <Customer EmailAddress="kathykitchen@sbcglobal.net" Password="" FirstName="Kathy" LastName="Kitchen" />
    </NewCustomers>';

INSERT Customers (EmailAddress, Password, FirstName, LastName)
    VALUES
    (
        @CustomerUpdate.value('(/NewCustomers/Customer/EmailAddress)[1]', 'varchar(255)'),
        @CustomerUpdate.value('(/NewCustomers/Customer/Password)[1]', 'varchar(60)'),
        @CustomerUpdate.value('(/NewCustomers/Customer/FirstName)[1]', 'varchar(60)'),
        @CustomerUpdate.value('(/NewCustomers/Customer/LastName)[1]', 'varchar(60)')
    );

SELECT * FROM Customers
</code>```

答:
This code works perfectly now. </p>

```<code>    USE MyGuitarShop

DECLARE @CustomerUpdate XML

SET @CustomerUpdate =
    '<NewCustomers>
        <Customer EmailAddress="izzychan@yahoo.com" Password="" FirstName="Isabella" LastName="Chan" />
        <Customer EmailAddress="johnprine@gmail.com" Password="" FirstName="John" LastName="Prine" />
        <Customer EmailAddress="kathykitchen@sbcglobal.net" Password="" FirstName="Kathy" LastName="Kitchen" />
    </NewCustomers>';

INSERT Customers (EmailAddress, Password, FirstName, LastName)
    VALUES
    (
        @CustomerUpdate.value('(/NewCustomers/Customer/@EmailAddress)[1]', 'varchar(255)'),
        @CustomerUpdate.value('(/NewCustomers/Customer/@Password)[1]', 'varchar(60)'),
        @CustomerUpdate.value('(/NewCustomers/Customer/@FirstName)[1]', 'varchar(60)'),
        @CustomerUpdate.value('(/NewCustomers/Customer/@LastName)[1]', 'varchar(60)')
    );

INSERT Customers (EmailAddress, Password, FirstName, LastName)
    VALUES
    (
        @CustomerUpdate.value('(/NewCustomers/Customer/@EmailAddress)[2]', 'varchar(255)'),
        @CustomerUpdate.value('(/NewCustomers/Customer/@Password)[2]', 'varchar(60)'),
        @CustomerUpdate.value('(/NewCustomers/Customer/@FirstName)[2]', 'varchar(60)'),
        @CustomerUpdate.value('(/NewCustomers/Customer/@LastName)[2]', 'varchar(60)')
    );

INSERT Customers (EmailAddress, Password, FirstName, LastName)
    VALUES
    (
        @CustomerUpdate.value('(/NewCustomers/Customer/@EmailAddress)[3]', 'varchar(255)'),
        @CustomerUpdate.value('(/NewCustomers/Customer/@Password)[3]', 'varchar(60)'),
        @CustomerUpdate.value('(/NewCustomers/Customer/@FirstName)[3]', 'varchar(60)'),
        @CustomerUpdate.value('(/NewCustomers/Customer/@LastName)[3]', 'varchar(60)')
    );

SELECT * FROM Customers
</code>```

Title: Insert From XML File

Body:
I'm attempting to update a customer table using an XML file, but it's not pulling the values from the XML into the variables to pass into the table. The error I get says "Cannot insert the value NULL into column 'EmailAddress'" even though there is clearly a value for EmailAddress. I feel like I'm missing something very simple, but can't figure it out. Any thoughts?

USE MyGuitarShop

DECLARE @CustomerUpdate XML

SET @CustomerUpdate =
    '<NewCustomers>
        <Customer EmailAddress="izzychan@yahoo.com" Password="" FirstName="Isabella" LastName="Chan" />
        <Customer EmailAddress="johnprine@gmail.com" Password="" FirstName="John" LastName="Prine" />
        <Customer EmailAddress="kathykitchen@sbcglobal.net" Password="" FirstName="Kathy" LastName="Kitchen" />
    </NewCustomers>';

INSERT Customers (EmailAddress, Password, FirstName, LastName)
    VALUES
    (
        @CustomerUpdate.value('(/NewCustomers/Customer/EmailAddress)[1]', 'varchar(255)'),
        @CustomerUpdate.value('(/NewCustomers/Customer/Password)[1]', 'varchar(60)'),
        @CustomerUpdate.value('(/NewCustomers/Customer/FirstName)[1]', 'varchar(60)'),
        @CustomerUpdate.value('(/NewCustomers/Customer/LastName)[1]', 'varchar(60)')
    );

SELECT * FROM Customers

Body:
This code works perfectly now.

    USE MyGuitarShop

DECLARE @CustomerUpdate XML

SET @CustomerUpdate =
    '<NewCustomers>
        <Customer EmailAddress="izzychan@yahoo.com" Password="" FirstName="Isabella" LastName="Chan" />
        <Customer EmailAddress="johnprine@gmail.com" Password="" FirstName="John" LastName="Prine" />
        <Customer EmailAddress="kathykitchen@sbcglobal.net" Password="" FirstName="Kathy" LastName="Kitchen" />
    </NewCustomers>';

INSERT Customers (EmailAddress, Password, FirstName, LastName)
    VALUES
    (
        @CustomerUpdate.value('(/NewCustomers/Customer/@EmailAddress)[1]', 'varchar(255)'),
        @CustomerUpdate.value('(/NewCustomers/Customer/@Password)[1]', 'varchar(60)'),
        @CustomerUpdate.value('(/NewCustomers/Customer/@FirstName)[1]', 'varchar(60)'),
        @CustomerUpdate.value('(/NewCustomers/Customer/@LastName)[1]', 'varchar(60)')
    );

INSERT Customers (EmailAddress, Password, FirstName, LastName)
    VALUES
    (
        @CustomerUpdate.value('(/NewCustomers/Customer/@EmailAddress)[2]', 'varchar(255)'),
        @CustomerUpdate.value('(/NewCustomers/Customer/@Password)[2]', 'varchar(60)'),
        @CustomerUpdate.value('(/NewCustomers/Customer/@FirstName)[2]', 'varchar(60)'),
        @CustomerUpdate.value('(/NewCustomers/Customer/@LastName)[2]', 'varchar(60)')
    );

INSERT Customers (EmailAddress, Password, FirstName, LastName)
    VALUES
    (
        @CustomerUpdate.value('(/NewCustomers/Customer/@EmailAddress)[3]', 'varchar(255)'),
        @CustomerUpdate.value('(/NewCustomers/Customer/@Password)[3]', 'varchar(60)'),
        @CustomerUpdate.value('(/NewCustomers/Customer/@FirstName)[3]', 'varchar(60)'),
        @CustomerUpdate.value('(/NewCustomers/Customer/@LastName)[3]', 'varchar(60)')
    );

SELECT * FROM Customers


问:
Replacing character string with another character string
I have a data frame for which I am attempting to replace certain values with others. So, as a small example, I have a dummy data frame of:

```<code>dummy<-c("1","2","3","4")
dummy<-data.frame(dummy)
dummy$dummy<-as.character(dummy$dummy)

odd<-c("1","3")

replace(dummy$dummy, dummy$dummy==odd, "odd")

#> [1] "odd" "2"   "3"   "4"
</code>```

Why would this only replace "1" with "odd" and not "3"?

My actual dataset has more information in it (it is restaurant cuisine types and I need to replace the types of cuisine by a more general category. For example, I have the cuisine types "Italian" and "French" in my dataset that need to be replaced with "European", and cuisine types "Southwestern" and "Pacific Northwestern" that need to be replaced with "American".

Is the above idea the most efficient way to do this?

答:
It sounds like your replacement is an actual variable; if so, you can replace with an ifelse statement as follows:

```<code>df <- data.frame(dummy = c("1","2","3","4"))
df$dummy <- ifelse(df$dummy %in% c(1,3), "Odd", df$dummy)
df

  dummy
1   Odd
2     2
3   Odd
4     4
</code>```

Body:
I have a data frame for which I am attempting to replace certain values with others. So, as a small example, I have a dummy data frame of:

dummy<-c("1","2","3","4")
dummy<-data.frame(dummy)
dummy$dummy<-as.character(dummy$dummy)

odd<-c("1","3")

replace(dummy$dummy, dummy$dummy==odd, "odd")

#> [1] "odd" "2"   "3"   "4"

Why would this only replace "1" with "odd" and not "3"?

My actual dataset has more information in it (it is restaurant cuisine types and I need to replace the types of cuisine by a more general category. For example, I have the cuisine types "Italian" and "French" in my dataset that need to be replaced with "European", and cuisine types "Southwestern" and "Pacific Northwestern" that need to be replaced with "American".

Is the above idea the most efficient way to do this?

Body:
It sounds like your replacement is an actual variable; if so, you can replace with an ifelse statement as follows:

df <- data.frame(dummy = c("1","2","3","4"))
df$dummy <- ifelse(df$dummy %in% c(1,3), "Odd", df$dummy)
df

  dummy
1   Odd
2     2
3   Odd
4     4


问:
AWS javascript SDK SES SendMail Illegal Address
I'm attempting to send mail using AWS SES.

Here's the error I'm seeing:

```<code>{
    "message": "Illegal address",
    "code": "InvalidParameterValue",
    "time": "2017-06-02T03:12:37.110Z",
    "requestId": "544c6aee-4741-11e7-9cf5-a709f069aa99",
    "statusCode": 400,
    "retryable": false,
    "retryDelay": 73.04001529701054
}
</code>```

Here's the request object being passed in to SendMail method of AWS.SES for javascript SDK.

```<code>{
    "Destination": {
        "BccAddresses": [],
        "CcAddresses": [],
        "ToAddresses": [
            "success@simulator.amazonses.com"
        ]
    },
    "Message": {
        "Body": {
            "Html": {
                "Charset": "UTF-8",
                "Data": "You have been removed from Kudo mailing list for account: bob@gmail.com"
            },
            "Text": {
                "Charset": "UTF-8",
                "Data": "You have been removed from Kudo mailing list for account: bob@gmail.com"
            }
        },
        "Subject": {
            "Charset": "UTF-8",
            "Data": "Kudo email removal"
        }
    },
    "ReplyToAddresses": [],
    "ReturnPath": "",
    "ReturnPathArn": "",
    "Source": "donotreply@kudo.io",
    "SourceArn": "arn:aws:ses:us-west-2:1xxxxxxxxxx2:identity/donotreply@kudo.io"
}
</code>```

bob@gmail.com is verified on my account (which is still in sandbox mode).  donotreply@kudo.io is also verified on my account.

Edit:  I just tested it by using the test email option in SES and it worked...  still can't get it to send using the SDK though.

答:
Okay, the key is to remove the empty strings for ReturnPath and ReturnPathArn and SourceArn if you aren't using it.  Once I did that it worked.

Source: https://forums.aws.amazon.com/thread.jspa?messageID=787424&#787424

```<code>{
    "Destination": {
        "BccAddresses": [],
        "CcAddresses": [],
        "ToAddresses": [
            "success@simulator.amazonses.com"
        ]
    },
    "Message": {
        "Body": {
            "Html": {
                "Charset": "UTF-8",
                "Data": "You have been removed from Kudo mailing list for account: bob@gmail.com"
            },
            "Text": {
                "Charset": "UTF-8",
                "Data": "You have been removed from Kudo mailing list for account: bob@gmail.com"
            }
        },
        "Subject": {
            "Charset": "UTF-8",
            "Data": "Kudo email removal"
        }
    },
    "ReplyToAddresses": [],
    "Source": "donotreply@kudo.io"
}
</code>```

Body:
I'm attempting to send mail using AWS SES.

Here's the error I'm seeing:

{
    "message": "Illegal address",
    "code": "InvalidParameterValue",
    "time": "2017-06-02T03:12:37.110Z",
    "requestId": "544c6aee-4741-11e7-9cf5-a709f069aa99",
    "statusCode": 400,
    "retryable": false,
    "retryDelay": 73.04001529701054
}

Here's the request object being passed in to SendMail method of AWS.SES for javascript SDK.

{
    "Destination": {
        "BccAddresses": [],
        "CcAddresses": [],
        "ToAddresses": [
            "success@simulator.amazonses.com"
        ]
    },
    "Message": {
        "Body": {
            "Html": {
                "Charset": "UTF-8",
                "Data": "You have been removed from Kudo mailing list for account: bob@gmail.com"
            },
            "Text": {
                "Charset": "UTF-8",
                "Data": "You have been removed from Kudo mailing list for account: bob@gmail.com"
            }
        },
        "Subject": {
            "Charset": "UTF-8",
            "Data": "Kudo email removal"
        }
    },
    "ReplyToAddresses": [],
    "ReturnPath": "",
    "ReturnPathArn": "",
    "Source": "donotreply@kudo.io",
    "SourceArn": "arn:aws:ses:us-west-2:1xxxxxxxxxx2:identity/donotreply@kudo.io"
}

bob@gmail.com is verified on my account (which is still in sandbox mode).  donotreply@kudo.io is also verified on my account.

Edit:  I just tested it by using the test email option in SES and it worked...  still can't get it to send using the SDK though.

Body:
Okay, the key is to remove the empty strings for ReturnPath and ReturnPathArn and SourceArn if you aren't using it.  Once I did that it worked.

Source: https://forums.aws.amazon.com/thread.jspa?messageID=787424&#787424

{
    "Destination": {
        "BccAddresses": [],
        "CcAddresses": [],
        "ToAddresses": [
            "success@simulator.amazonses.com"
        ]
    },
    "Message": {
        "Body": {
            "Html": {
                "Charset": "UTF-8",
                "Data": "You have been removed from Kudo mailing list for account: bob@gmail.com"
            },
            "Text": {
                "Charset": "UTF-8",
                "Data": "You have been removed from Kudo mailing list for account: bob@gmail.com"
            }
        },
        "Subject": {
            "Charset": "UTF-8",
            "Data": "Kudo email removal"
        }
    },
    "ReplyToAddresses": [],
    "Source": "donotreply@kudo.io"
}


问:
bearer token is not working with my Authorize Attribute Roles with WebAPI, Username is null

I can log in and get the token key from http://localhost:58507/token by Postman

I can call an api with just [Authorize] Attribute

But when I set the roles [Authorize(Roles= "Admin")] I get this server internal Error:

"Message": "An error has occurred.",

"ExceptionMessage": "Value cannot be null. Parameter name: username",

"ExceptionType": "System.ArgumentNullException",

"StackTrace": "at System.Web.Util.SecUtility.CheckParameter(String& param, Boolean checkForNull, Boolean checkIfEmpty, Boolean checkForCommas, Int32 maxSize, String paramName)

this is my Codes:

the AuthorizeAttribute Class:

```<code>public class AuthorizeAttribute : System.Web.Http.AuthorizeAttribute
    {
        protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
            if (!HttpContext.Current.User.Identity.IsAuthenticated)
                base.HandleUnauthorizedRequest(actionContext);
            else
                actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Forbidden);
        }
    }
</code>```

the OAuthAuthorizationServerProvider Class :

```<code>public class MyOAuthProvider : OAuthAuthorizationServerProvider
{
    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
    }

    public override async Task GrantResourceOwnerCredentials(
        OAuthGrantResourceOwnerCredentialsContext context)
    {
        var identity = new ClaimsIdentity(context.Options.AuthenticationType);
        string username = context.UserName;
        string password = context.Password;
        if (Membership.ValidateUser(username, password))
        {
            using (var ee = new DBEntities())
            {
                MembershipUser mu = Membership.GetUser(username);
                Guid guid = (Guid)mu.ProviderUserKey;
                string roles = string.Join(",", Roles.GetRolesForUser(username));
                identity.AddClaim(new Claim(ClaimTypes.Role, roles));
                identity.AddClaim(new Claim("username", username));
                context.Validated(identity);
            }
        }
        else
        {
            context.SetError("Login Field", "Error username or password");
        }
    }
}
</code>```

答:
I found the solution on: this post

the problem was in this line

```<code>identity.AddClaim(new Claim("username", username));
</code>```

I change "username" to ClaimTypes.Name

```<code>identity.AddClaim(new Claim(ClaimTypes.Name, username));
</code>```

Body:
I can log in and get the token key from http://localhost:58507/token by Postman

I can call an api with just [Authorize] Attribute

But when I set the roles [Authorize(Roles= "Admin")] I get this server internal Error:

"Message": "An error has occurred.",

"ExceptionMessage": "Value cannot be null. Parameter name: username",

"ExceptionType": "System.ArgumentNullException",

"StackTrace": "at System.Web.Util.SecUtility.CheckParameter(String& param, Boolean checkForNull, Boolean checkIfEmpty, Boolean checkForCommas, Int32 maxSize, String paramName)

this is my Codes:

the AuthorizeAttribute Class:

public class AuthorizeAttribute : System.Web.Http.AuthorizeAttribute
    {
        protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
            if (!HttpContext.Current.User.Identity.IsAuthenticated)
                base.HandleUnauthorizedRequest(actionContext);
            else
                actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Forbidden);
        }
    }

the OAuthAuthorizationServerProvider Class :

public class MyOAuthProvider : OAuthAuthorizationServerProvider
{
    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
    }

    public override async Task GrantResourceOwnerCredentials(
        OAuthGrantResourceOwnerCredentialsContext context)
    {
        var identity = new ClaimsIdentity(context.Options.AuthenticationType);
        string username = context.UserName;
        string password = context.Password;
        if (Membership.ValidateUser(username, password))
        {
            using (var ee = new DBEntities())
            {
                MembershipUser mu = Membership.GetUser(username);
                Guid guid = (Guid)mu.ProviderUserKey;
                string roles = string.Join(",", Roles.GetRolesForUser(username));
                identity.AddClaim(new Claim(ClaimTypes.Role, roles));
                identity.AddClaim(new Claim("username", username));
                context.Validated(identity);
            }
        }
        else
        {
            context.SetError("Login Field", "Error username or password");
        }
    }
}

Body:
I found the solution on: this post

the problem was in this line

identity.AddClaim(new Claim("username", username));

I change "username" to ClaimTypes.Name

identity.AddClaim(new Claim(ClaimTypes.Name, username));


问:
How to append string in bash script using sed?
Hello I am trying to make a script to edit chrome flags on mac using a bash script. This script is to set max SSL to  TLS1.3 on chrome. However, I am having some issues with sed.
Here is what my command looks like:

```<code>sed -i '.bak' -e 's/{\"browser\".*origin\":\"\"\}/\"browser\":\{\"enabled_labs_experiments\":\[\"ssl-version-max@2\"\],\"last_redirect_origin\":\"\"\}/g' "./Local State"
</code>```

The goal is to append

"enabled_labs_experiments":["ssl-version-max@2"]

to this

{"browser":{"last_redirect_origin":""}

to make it looks like this

{"browser":{"enabled_labs_experiments":["ssl-version-max@2"],"last_redirect_origin":""}

Not sure what's wrong with my command but any help in achieving this is really appreciated or just pointing me in right direction would help greatly.

Thanks!

答:
If you have strings in Bash (versus a file), you may want to use the regex engine in Bash instead of sed to process them in this fashion.

Given:

```<code>$ s1='"enabled_labs_experiments":["ssl-version-max@2"]'
$ s2='{"browser":{"last_redirect_origin":""}'
</code>```

You can split on the first :{ in s2 this way:

```<code>$ [[ $s2 =~ (^[^:]+:){(.*$) ]] && echo "${BASH_REMATCH[1]}{$s1,${BASH_REMATCH[2]}"
{"browser":{"enabled_labs_experiments":["ssl-version-max@2"],"last_redirect_origin":""}
</code>```

Or, if you want the same regex as the other answers:

```<code>$ [[ $s2 =~ (^{\"browser\":){(\"last_redirect_origin\":\"\"}$) ]] && echo "${BASH_REMATCH[1]}{$s1,${BASH_REMATCH[2]}"
{"browser":{"enabled_labs_experiments":["ssl-version-max@2"],"last_redirect_origin":""}
</code>```

Body:
Hello I am trying to make a script to edit chrome flags on mac using a bash script. This script is to set max SSL to  TLS1.3 on chrome. However, I am having some issues with sed.
Here is what my command looks like:

sed -i '.bak' -e 's/{\"browser\".*origin\":\"\"\}/\"browser\":\{\"enabled_labs_experiments\":\[\"ssl-version-max@2\"\],\"last_redirect_origin\":\"\"\}/g' "./Local State"

The goal is to append

"enabled_labs_experiments":["ssl-version-max@2"]

to this

{"browser":{"last_redirect_origin":""}

to make it looks like this

{"browser":{"enabled_labs_experiments":["ssl-version-max@2"],"last_redirect_origin":""}

Not sure what's wrong with my command but any help in achieving this is really appreciated or just pointing me in right direction would help greatly.

Thanks!

Body:
If you have strings in Bash (versus a file), you may want to use the regex engine in Bash instead of sed to process them in this fashion.

Given:

$ s1='"enabled_labs_experiments":["ssl-version-max@2"]'
$ s2='{"browser":{"last_redirect_origin":""}'

You can split on the first :{ in s2 this way:

$ [[ $s2 =~ (^[^:]+:){(.*$) ]] && echo "${BASH_REMATCH[1]}{$s1,${BASH_REMATCH[2]}"
{"browser":{"enabled_labs_experiments":["ssl-version-max@2"],"last_redirect_origin":""}

Or, if you want the same regex as the other answers:

$ [[ $s2 =~ (^{\"browser\":){(\"last_redirect_origin\":\"\"}$) ]] && echo "${BASH_REMATCH[1]}{$s1,${BASH_REMATCH[2]}"
{"browser":{"enabled_labs_experiments":["ssl-version-max@2"],"last_redirect_origin":""}


问:
Java Multi-threading : Unexpected result
I am working on a Enterprise application. I am facing some issues while running application in multithreaded environment. I am writing a program in which there is a variable whose value is getting updated(incremented) at very fast rate (for example 10000 updates/persecond). A loop runs for certain iterations and the value of the variable is incremented and stored in HashMap. Once the loop terminates and value the variable in HashMap is printed. I am getting unexpected value of the variable.

Here is demo program (Please read comments for better understanding) :

class test implements Runnable {

    static ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
    static AtomicInteger value_to_be_incremented_stored = new AtomicInteger(0); // variable whose value to be updated
    static AtomicInteger i = new AtomicInteger(0);  // this runs the loop

    @Override
    public void run() {

        for (i.set(0); i.get() < 100000; i.incrementAndGet()) {
            /*
                This loop should run 100000 times and when loop terminates according to me value of variable
                "value_to_be_incremented_stored" should be 100000 as its value is incremented
                100000 times the loop also runs 100000 times.
            */
            System.out.println("Thread > " + Thread.currentThread() + "  " + value_to_be_incremented_stored.incrementAndGet());
            map.put("TC", value_to_be_incremented_stored.intValue());
        }

        System.out.println("Output by Thread  " + Thread.currentThread() + "     " + map.toString());
    }

    public static void main(String[] args) {

        test t1 = new test();
        Thread thread1 = new Thread(t1);
        thread1.setName("Thread 1");

        Thread thread2 = new Thread(t1);
        thread2.setName("Thread 2");

        Thread thread3 = new Thread(t1);
        thread3.setName("Thread 3");

        Thread thread4 = new Thread(t1);
        thread4.setName("Thread 4");

        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();

    }
}
```

Output (it varies) :

Issue :
I am running loop for 100000 times (i.get() < 100000) then how come value of variable value_to_be_incremented_stored becomes more than 100000.

答:
I found three defects.  One there is a race condition in the for loop between the point where you compare the loop counter, and where you increment it.  You should do this in one step to get an atomic operation:

```<code>for ( ; i.incrementAndGet() < 100000;  ) {
</code>```

The other is there is also a race condition between the increment of your counter, and placing it in the map.  Even though you increment these in series, any thread could be have a different value internally (it's at a different point in the loop) and it could put a previous value in the global map.  You need atomicity here to to make sure the value you increment is the value you place in the loop.

```<code>synchronized( lock ) {
    value_to_be_incremented_stored.incrementAndGet();
    map.put("TC", value_to_be_incremented_stored.intValue());
}
</code>```

Finally for some reason the < comparison produces a value of 99999 for me.  I had to use <= to fix it.

(And as we discussed in the comments, setting i.set(0) at the start of each for loop doesn't work for fairly obvious reasons.  Four defects, I guess.)

```<code>class ThreadTestX implements Runnable {

    static ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
    static AtomicInteger value_to_be_incremented_stored = new AtomicInteger(0); // variable whose value to be updated
    static AtomicInteger i = new AtomicInteger(0);  // this runs the loop
    static final Object lock = new Object();

    @Override
    public void run() {

        for ( ; i.incrementAndGet() <= 100000;  ) {
            /*
                This loop should run 100000 times and when loop terminates according to me value of variable
                "value_to_be_incremented_stored" should be 100000 as its value is incremented
                100000 times the loop also runs 100000 times.
            */
            synchronized( lock ) {
                value_to_be_incremented_stored.incrementAndGet();
    //            System.out.println("Thread > " + Thread.currentThread() +
    //                 "  " + value_to_be_incremented_stored.get());
                map.put("TC", value_to_be_incremented_stored.intValue());
            }
        }

        System.out.println("Output by Thread  " + Thread.currentThread()
                + "     " + map.toString());
    }

    public static void main(String[] args) {

        ThreadTestX t1 = new ThreadTestX();
        Thread thread1 = new Thread(t1);
        thread1.setName("Thread 1");

        Thread thread2 = new Thread(t1);
        thread2.setName("Thread 2");

        Thread thread3 = new Thread(t1);
        thread3.setName("Thread 3");

        Thread thread4 = new Thread(t1);
        thread4.setName("Thread 4");

        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();

    }
}
</code>```

Output:

```<code>run:
Output by Thread  Thread[Thread 4,5,main]     {TC=100000}
Output by Thread  Thread[Thread 3,5,main]     {TC=100000}
Output by Thread  Thread[Thread 1,5,main]     {TC=100000}
Output by Thread  Thread[Thread 2,5,main]     {TC=100000}
BUILD SUCCESSFUL (total time: 0 seconds)
</code>```

Afterthoughts:  And in spite of getting marked correct, I'm not sure I was correct.  The problem here is that you are trying to keep three things in sync: the loop counter i, the value to be incremented, and the map.  Allowing any of these to be executed outside of a synchronized block may invite them to be in an unexpected state.  I think the following may be safer:

```<code>@Override
public void run() {

    for ( ;;  ) {
        synchronized( lock ) {
            if( i.incrementAndGet() <= 100000 ) {
                value_to_be_incremented_stored.incrementAndGet();
                map.put("TC", value_to_be_incremented_stored.intValue());
            }
            else
                break;
        }
    }
    System.out.println("Output by Thread  " + Thread.currentThread()
            + "     " + map.toString());
}
</code>```

This removes the need for declaring the variables as AtomicInteger, but I don't see how else you ensure that their values don't change (due to some other thread) as that loop executes.

Body:
I am working on a Enterprise application. I am facing some issues while running application in multithreaded environment. I am writing a program in which there is a variable whose value is getting updated(incremented) at very fast rate (for example 10000 updates/persecond). A loop runs for certain iterations and the value of the variable is incremented and stored in HashMap. Once the loop terminates and value the variable in HashMap is printed. I am getting unexpected value of the variable.

Here is demo program (Please read comments for better understanding) :

class test implements Runnable {

    static ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
    static AtomicInteger value_to_be_incremented_stored = new AtomicInteger(0); // variable whose value to be updated
    static AtomicInteger i = new AtomicInteger(0);  // this runs the loop

    @Override
    public void run() {

        for (i.set(0); i.get() < 100000; i.incrementAndGet()) {
            /*
                This loop should run 100000 times and when loop terminates according to me value of variable
                "value_to_be_incremented_stored" should be 100000 as its value is incremented
                100000 times the loop also runs 100000 times.
            */
            System.out.println("Thread > " + Thread.currentThread() + "  " + value_to_be_incremented_stored.incrementAndGet());
            map.put("TC", value_to_be_incremented_stored.intValue());
        }

        System.out.println("Output by Thread  " + Thread.currentThread() + "     " + map.toString());
    }

    public static void main(String[] args) {

        test t1 = new test();
        Thread thread1 = new Thread(t1);
        thread1.setName("Thread 1");

        Thread thread2 = new Thread(t1);
        thread2.setName("Thread 2");

        Thread thread3 = new Thread(t1);
        thread3.setName("Thread 3");

        Thread thread4 = new Thread(t1);
        thread4.setName("Thread 4");

        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();

    }
}

Output (it varies) :

Issue :
I am running loop for 100000 times (i.get() < 100000) then how come value of variable value_to_be_incremented_stored becomes more than 100000.

Body:
I found three defects.  One there is a race condition in the for loop between the point where you compare the loop counter, and where you increment it.  You should do this in one step to get an atomic operation:

for ( ; i.incrementAndGet() < 100000;  ) {

The other is there is also a race condition between the increment of your counter, and placing it in the map.  Even though you increment these in series, any thread could be have a different value internally (it's at a different point in the loop) and it could put a previous value in the global map.  You need atomicity here to to make sure the value you increment is the value you place in the loop.

synchronized( lock ) {
    value_to_be_incremented_stored.incrementAndGet();
    map.put("TC", value_to_be_incremented_stored.intValue());
}

Finally for some reason the < comparison produces a value of 99999 for me.  I had to use <= to fix it.

(And as we discussed in the comments, setting i.set(0) at the start of each for loop doesn't work for fairly obvious reasons.  Four defects, I guess.)

class ThreadTestX implements Runnable {

    static ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
    static AtomicInteger value_to_be_incremented_stored = new AtomicInteger(0); // variable whose value to be updated
    static AtomicInteger i = new AtomicInteger(0);  // this runs the loop
    static final Object lock = new Object();

    @Override
    public void run() {

        for ( ; i.incrementAndGet() <= 100000;  ) {
            /*
                This loop should run 100000 times and when loop terminates according to me value of variable
                "value_to_be_incremented_stored" should be 100000 as its value is incremented
                100000 times the loop also runs 100000 times.
            */
            synchronized( lock ) {
                value_to_be_incremented_stored.incrementAndGet();
    //            System.out.println("Thread > " + Thread.currentThread() +
    //                 "  " + value_to_be_incremented_stored.get());
                map.put("TC", value_to_be_incremented_stored.intValue());
            }
        }

        System.out.println("Output by Thread  " + Thread.currentThread()
                + "     " + map.toString());
    }

    public static void main(String[] args) {

        ThreadTestX t1 = new ThreadTestX();
        Thread thread1 = new Thread(t1);
        thread1.setName("Thread 1");

        Thread thread2 = new Thread(t1);
        thread2.setName("Thread 2");

        Thread thread3 = new Thread(t1);
        thread3.setName("Thread 3");

        Thread thread4 = new Thread(t1);
        thread4.setName("Thread 4");

        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();

    }
}

Output:

run:
Output by Thread  Thread[Thread 4,5,main]     {TC=100000}
Output by Thread  Thread[Thread 3,5,main]     {TC=100000}
Output by Thread  Thread[Thread 1,5,main]     {TC=100000}
Output by Thread  Thread[Thread 2,5,main]     {TC=100000}
BUILD SUCCESSFUL (total time: 0 seconds)

Afterthoughts:  And in spite of getting marked correct, I'm not sure I was correct.  The problem here is that you are trying to keep three things in sync: the loop counter i, the value to be incremented, and the map.  Allowing any of these to be executed outside of a synchronized block may invite them to be in an unexpected state.  I think the following may be safer:

@Override
public void run() {

    for ( ;;  ) {
        synchronized( lock ) {
            if( i.incrementAndGet() <= 100000 ) {
                value_to_be_incremented_stored.incrementAndGet();
                map.put("TC", value_to_be_incremented_stored.intValue());
            }
            else
                break;
        }
    }
    System.out.println("Output by Thread  " + Thread.currentThread()
            + "     " + map.toString());
}

This removes the need for declaring the variables as AtomicInteger, but I don't see how else you ensure that their values don't change (due to some other thread) as that loop executes.


问:
Is it good practice to use multiple namespace in same C++ source file?
I want to include more than one namespace in the same .cpp file.

While std is widely used, the namespace z3 will be used in about 10% of a 25 KLOC file.

Will it be a good practice to use both as

```<code>    using namespace std;
    using namespace z3;
</code>```

I am thinking of using only std and then use the Z3 methods by mentioning the namespase whenever required. Like,

```<code>    using namespace std;

    z3::context c;
    z3::solver s;
</code>```

Which of these is better practice?

I do not want to rename them into one namespace.

Thanks and regards,
Sukanya

答:
It's actually best practice not to import the entire namespace into your program because it pollutes your namespace. This can lead to naming collisions. It's best to import only what you are using.

So instead of:

```<code>using namespace z3;
</code>```

You should do:

```<code>using z3::context;
</code>```

Body:
I want to include more than one namespace in the same .cpp file.

While std is widely used, the namespace z3 will be used in about 10% of a 25 KLOC file.

Will it be a good practice to use both as

    using namespace std;
    using namespace z3;

I am thinking of using only std and then use the Z3 methods by mentioning the namespase whenever required. Like,

    using namespace std;

    z3::context c;
    z3::solver s;

Which of these is better practice?

I do not want to rename them into one namespace.

Thanks and regards,
Sukanya

Body:
It's actually best practice not to import the entire namespace into your program because it pollutes your namespace. This can lead to naming collisions. It's best to import only what you are using.

So instead of:

using namespace z3;

You should do:

using z3::context;


问:
Seg fault doing new vector<string>
The following code gets a seg fault on the last line:

```<code>   HookAct *act = new HookAct;
    act->hkAct = HookAct::PRINT;
    act->params = new vector<string>;
</code>```

Valgrind tells me:

```<code>==15551== Process terminating with default action of signal 11 (SIGSEGV)
==15551== Access not within mapped region at address 0x0
==15551== at 0x5927026: std::string::assign(char const*, unsigned long) (in /usr/lib/libstdc++.so.6.0.10)
==15551== by 0x725424A: test (test.cpp:10)
</code>```

Does anyone have any idea why it is doing this?

FYI, here's the [current, temporary] definition of HookAct:

```<code>struct HookAct {
    enum {
        PRINT
    } hkAct;
    vector<string> *params;
};
</code>```

答:
The code you pasted is fine.

I think your problem is probably adding a NULL string to the vector act->params.

Title: Seg fault doing new vector<string>

Body:
The following code gets a seg fault on the last line:

   HookAct *act = new HookAct;
    act->hkAct = HookAct::PRINT;
    act->params = new vector<string>;

Valgrind tells me:

==15551== Process terminating with default action of signal 11 (SIGSEGV)
==15551== Access not within mapped region at address 0x0
==15551== at 0x5927026: std::string::assign(char const*, unsigned long) (in /usr/lib/libstdc++.so.6.0.10)
==15551== by 0x725424A: test (test.cpp:10)

Does anyone have any idea why it is doing this?

FYI, here's the [current, temporary] definition of HookAct:

struct HookAct {
    enum {
        PRINT
    } hkAct;
    vector<string> *params;
};


问:
GIT lets me checkout another branch with uncommitted changes, and alters files in that branch
GIF demonstrating the sequence of events

I create a branch foo, alter a file, then without committing the change I checkout master. GIT lets me do the checkout and the modification is carried over.

I commit this change.

Switch back to the branch foo, alter a file -- coincidentally in a way that makes it identical to the version in master -- then without committing the change I checkout master. This time I get an error "Error: Your local changes to the following files would be overwritten by checkout: index.html Please commit your changes or stash them before you can switch branches.  Aborting"

What is responsible for this inconsistent behavior?

答:
This is not inconsistent behaviour. This is very expected from the GIT, it just complains that file it tries to merge test.txt file to the master it fails to do.

It clearly complaints please commit your changes while switiching to another branch.

It's recommended to commit the changes in our local branch. When you switch branch from, if you are able to keep track of the changes of few files it's ok, what if 20 files? in that case, its better to commit the changes and switch to another branch.

When you switch to another branch, uncommitted changed files, not the new files. only the files you changed in a branch merge to another branch.

Here you merge the text.txt file in master branch and you committed there. Later you went to branch Foo and edited the file and you didn't commit the file in your local branch and you switched the branch and it didn't let you do. Because of the change what you did not able to track.

The suggestion is to commit the changes to your local branch.

```<code>git checkout -b foo
echo random > test.txt
git add test.txt
git commit -m "random commit"
git rebase master
git checkout master
git merge foo
</code>```

you're done.

Body:
This is not inconsistent behaviour. This is very expected from the GIT, it just complains that file it tries to merge test.txt file to the master it fails to do.

It clearly complaints please commit your changes while switiching to another branch.

It's recommended to commit the changes in our local branch. When you switch branch from, if you are able to keep track of the changes of few files it's ok, what if 20 files? in that case, its better to commit the changes and switch to another branch.

When you switch to another branch, uncommitted changed files, not the new files. only the files you changed in a branch merge to another branch.

Here you merge the text.txt file in master branch and you committed there. Later you went to branch Foo and edited the file and you didn't commit the file in your local branch and you switched the branch and it didn't let you do. Because of the change what you did not able to track.

The suggestion is to commit the changes to your local branch.

git checkout -b foo
echo random > test.txt
git add test.txt
git commit -m "random commit"
git rebase master
git checkout master
git merge foo

you're done.


问:
Better way to do this ( using LINQ )?
I am comparing two lists and in one case I am removing the uncommon elements from one list ( removing from lists with more number of elements ) and in the other case (else statement) I am adding the uncommon elements to one list ( adding to list with lesser elements )

I am able to do this using the below given code but I was hoping to achieve this using LINQ in a more concise manner. Please suggest me an equivalent LINQ code

```<code>if (receivedList.Count < AuthorFacets.Count)
{
    for (int i = AuthorFacets.Count - 1; i >= 0; i--)
    {
        if (!receivedList.Contains(AuthorFacets[i]))
            AuthorFacets.RemoveAt(i);
    }
}
else
{
    for (int i = 0; i < receivedList.Count; i++)
    {
        if (!AuthorFacets.Contains(receivedList[i]))
            AuthorFacets.Add(receivedList[i]);
    }
}
</code>```

答:
How about this?

```<code>using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        var receivedList = new List<string>();
        var AuthorFacets = new List<string>();

        receivedList.Add("2");
        receivedList.Add("4");
        receivedList.Add("6");

        AuthorFacets.Add("1");
        AuthorFacets.Add("2");
        AuthorFacets.Add("3");

        if (receivedList.Count < AuthorFacets.Count)
        {
            AuthorFacets = AuthorFacets.Where(i => receivedList.Contains(i)).ToList();
        }
        else
        {
            AuthorFacets.AddRange(receivedList.Where(i => !AuthorFacets.Contains(i)));
        }

        Console.WriteLine(string.Join("\n",AuthorFacets));
    }
}
</code>```

Source Code: https://dotnetfiddle.net/Hz8anK

Title: Better way to do this ( using LINQ )?

Body:
I am comparing two lists and in one case I am removing the uncommon elements from one list ( removing from lists with more number of elements ) and in the other case (else statement) I am adding the uncommon elements to one list ( adding to list with lesser elements )

I am able to do this using the below given code but I was hoping to achieve this using LINQ in a more concise manner. Please suggest me an equivalent LINQ code

if (receivedList.Count < AuthorFacets.Count)
{
    for (int i = AuthorFacets.Count - 1; i >= 0; i--)
    {
        if (!receivedList.Contains(AuthorFacets[i]))
            AuthorFacets.RemoveAt(i);
    }
}
else
{
    for (int i = 0; i < receivedList.Count; i++)
    {
        if (!AuthorFacets.Contains(receivedList[i]))
            AuthorFacets.Add(receivedList[i]);
    }
}

Body:
How about this?

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        var receivedList = new List<string>();
        var AuthorFacets = new List<string>();

        receivedList.Add("2");
        receivedList.Add("4");
        receivedList.Add("6");

        AuthorFacets.Add("1");
        AuthorFacets.Add("2");
        AuthorFacets.Add("3");

        if (receivedList.Count < AuthorFacets.Count)
        {
            AuthorFacets = AuthorFacets.Where(i => receivedList.Contains(i)).ToList();
        }
        else
        {
            AuthorFacets.AddRange(receivedList.Where(i => !AuthorFacets.Contains(i)));
        }

        Console.WriteLine(string.Join("\n",AuthorFacets));
    }
}

Source Code: https://dotnetfiddle.net/Hz8anK


问:
How to Pull all docker container images from docker repo at once?
I have a private docker repo in which i have 10 container images stored. I want to pull all images to a machine. is there a way i can pull all images from a repo with a single command? some command like

```<code>docker pull  xx.xx.com/reponame/*
</code>```

while researching I found ways to pull all tags of a single image; but no luck so far on all images

答:
Could 'hack' this with docker-compose.

```<code># docker-compose.yml
version: '3.1'
services:
  a:
    image: a-image
  b:
    image: b-image
  c:
    image: c-image
# .....
</code>```

docker-compose pull --parallel

Body:
I have a private docker repo in which i have 10 container images stored. I want to pull all images to a machine. is there a way i can pull all images from a repo with a single command? some command like

docker pull  xx.xx.com/reponame/*

while researching I found ways to pull all tags of a single image; but no luck so far on all images

Body:
Could 'hack' this with docker-compose.

# docker-compose.yml
version: '3.1'
services:
  a:
    image: a-image
  b:
    image: b-image
  c:
    image: c-image
# .....

docker-compose pull --parallel


问:
In JavaScript or jQuery, how to convert ontouchmove event into a basic click event on target
I am running my web app on Chromium on a touch device. It's an industry control panel, not a consumer tablet.

I have a problem when the user means to click (tap) on a button, but their finger moves a little, thus causing the 'ontouchmove' event to fire. I other words, the device reads it as a swipe instead of a click.

When this happens, the click event is not fired, so nothing happens, even though the button's hover is triggered. So, the user sees that their touch was registered (button changes color), but is then frustrated by the fact that nothing happens.

I'm hoping I can put something in index.html that globally converts these swipes into standard old-fashioned clicks.

```<code>document.ontouchmove = function() {
  // get target of this event
  // fire the click event of that target
}
</code>```

Is this even possible? I have jQuery installed. Is something like hammerjs needed? I'd like to get by with plain old JavaScript, if possible.

Thanks

答:
I'm not really sure but you can try it :
</p>

```<code>document.on("touchmove", function(e) {
  $(e.target).trigger("click");
});
</code>```

Body:
I am running my web app on Chromium on a touch device. It's an industry control panel, not a consumer tablet.

I have a problem when the user means to click (tap) on a button, but their finger moves a little, thus causing the 'ontouchmove' event to fire. I other words, the device reads it as a swipe instead of a click.

When this happens, the click event is not fired, so nothing happens, even though the button's hover is triggered. So, the user sees that their touch was registered (button changes color), but is then frustrated by the fact that nothing happens.

I'm hoping I can put something in index.html that globally converts these swipes into standard old-fashioned clicks.

document.ontouchmove = function() {
  // get target of this event
  // fire the click event of that target
}

Is this even possible? I have jQuery installed. Is something like hammerjs needed? I'd like to get by with plain old JavaScript, if possible.

Thanks

Body:
I'm not really sure but you can try it :

document.on("touchmove", function(e) {
  $(e.target).trigger("click");
});


问:
Parsing a string containing a date in a specific format into a Date object in Javascript
I'm learning Javascript as a new language, and I figured a good way to get used to how JS handles reg exp and string manipulation is to parse a string containing a date into a Date object.

I have a string in the form "2005-05-28".  What is the best Javascript-y way to parse that into a Date object?

答:
That format is acceptable for a standard JS date. So you only have to do:

```<code>var dateObject = new Date("2005-05-28");
</code>```

EDIT: The above is wrong and TJ is right; I've been busted with a lazy answer. And it even parses incorrectly in Firefox, subtracting one from the date.

Seeing that this question was trickier than I thought, I ran some tests carefully. IE (and others) will accept a slash instead of a dash (implementation trumps specification). So, the above will work with a simple replace():

```<code>var dateObject = new Date(("2005-05-28").replace("-", "/"));
</code>```

Note that I also tested this successfully with MM/DD/YYYY:

```<code>var dateObject = new Date("05/28/2005");
</code>```

So the slashes will parse in all major browsers (including IE6).

Body:
That format is acceptable for a standard JS date. So you only have to do:

var dateObject = new Date("2005-05-28");

EDIT: The above is wrong and TJ is right; I've been busted with a lazy answer. And it even parses incorrectly in Firefox, subtracting one from the date.

Seeing that this question was trickier than I thought, I ran some tests carefully. IE (and others) will accept a slash instead of a dash (implementation trumps specification). So, the above will work with a simple replace():

var dateObject = new Date(("2005-05-28").replace("-", "/"));

Note that I also tested this successfully with MM/DD/YYYY:

var dateObject = new Date("05/28/2005");

So the slashes will parse in all major browsers (including IE6).


问:
Trying to use transitionend event instead of setTimeout
I have this code:

$("#disable").click(function () {
     $("body").append("

");
    setTimeout(function () {
        $("#blackDisable").addClass("showBack");
    }, 150);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.fade {
    opacity: 0;
    transition: opacity .15s linear;
}

.showBack {
    opacity: .5;
}

#blackDisable {
    position: fixed;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 2222;
    background-color: black;
}</code>```

<button id="disable">Click Me</button>
```

I don't want to use setTimeout to force the transition work, so I searched for a solution and found transitionend event and replaced the setTimeout with transitionend event handler but it didn't fired.

How could I remove this setTimeout and use the transitionend event?

Thanks in advance and sorry for my english!

答:
transitionend has anything to do with your problem - since there was no transition to register any end.

It's an issue of immediately assigning classes to newly created (not yet DOM-styles-discoverable) elements - without a callback - where setTimeout acts actually like a "DOM-ready hack".

Without setTimeout? Two ways (or even more):

1. animation (instead of transition)

$("#disable").click(function() {

  $("body").append("

");
  $("#blackDisable").addClass("showBack");

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.fade {
  opacity: 0;
  /* no transition */
}

.showBack {
  /*opacity: .5; not ready, instead let the browser assign/trigger keyframes */
  animation : fadeIn 0.3s linear forwards;
}

#blackDisable {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 2222;
  background-color: black;
}

@keyframes fadeIn {
  to { opacity: 0.5; }
}</code>```

<button id="disable">Click Me</button>
```
</div>
</div>
</p>

<h2>2. Appending before any event</h2>

<p>and using CSS <code>visibility</code> to prevent overlapping problems</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// Append on DOM ready
$("body").append("<div id='blackDisable' class='fade'></div>");

// CALLBACK
$("#disable").click(function() {
  // Since the callback, it's now discoverable,
  // DOM set, CSS styles are set and we can transition!
  $("#blackDisable").addClass("showBack");

});</code>```

.fade {
  opacity: 0;
  visibility: hidden; /* you need this!!!!!! */
  transition: opacity .3s linear;
}

.showBack {
  opacity: .5;
  visibility: visible; /* and this!!!!!! */
}

#blackDisable {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 2222;
  background-color: black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="disable">Click Me</button>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script></code>```

3. queue

$("#disable").click(function() {

  $("body").append("

");

  // Instead of setTimeout but again mimicking a callback
  $("#blackDisable").delay().queue(function(){
    $(this).addClass("showBack");
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.fade {
  opacity: 0;
  transition: opacity .3s linear;
}

.showBack {
  opacity: .5;
}

#blackDisable {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 2222;
  background-color: black;
}</code>```

<button id="disable">Click Me</button>
```

Body:
I have this code:

$("#disable").click(function () {
     $("body").append("

");
    setTimeout(function () {
        $("#blackDisable").addClass("showBack");
    }, 150);
});

.fade {
    opacity: 0;
    transition: opacity .15s linear;
}

.showBack {
    opacity: .5;
}

#blackDisable {
    position: fixed;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 2222;
    background-color: black;
}

<button id="disable">Click Me</button>

I don't want to use setTimeout to force the transition work, so I searched for a solution and found transitionend event and replaced the setTimeout with transitionend event handler but it didn't fired.

How could I remove this setTimeout and use the transitionend event?

Thanks in advance and sorry for my english!

Body:
transitionend has anything to do with your problem - since there was no transition to register any end.

It's an issue of immediately assigning classes to newly created (not yet DOM-styles-discoverable) elements - without a callback - where setTimeout acts actually like a "DOM-ready hack".

Without setTimeout? Two ways (or even more):

1. animation (instead of transition)

$("#disable").click(function() {

  $("body").append("<div id='blackDisable' class='fade'></div>");
  $("#blackDisable").addClass("showBack");

});

.fade {
  opacity: 0;
  /* no transition */
}

.showBack {
  /*opacity: .5; not ready, instead let the browser assign/trigger keyframes */
  animation : fadeIn 0.3s linear forwards;
}

#blackDisable {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 2222;
  background-color: black;
}

@keyframes fadeIn {
  to { opacity: 0.5; }
}

<button id="disable">Click Me</button>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>

2. Appending before any event

and using CSS visibility to prevent overlapping problems

// Append on DOM ready
$("body").append("<div id='blackDisable' class='fade'></div>");

// CALLBACK
$("#disable").click(function() {
  // Since the callback, it's now discoverable,
  // DOM set, CSS styles are set and we can transition!
  $("#blackDisable").addClass("showBack");

});

.fade {
  opacity: 0;
  visibility: hidden; /* you need this!!!!!! */
  transition: opacity .3s linear;
}

.showBack {
  opacity: .5;
  visibility: visible; /* and this!!!!!! */
}

#blackDisable {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 2222;
  background-color: black;
}

<button id="disable">Click Me</button>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>

3. queue

$("#disable").click(function() {

  $("body").append("<div id='blackDisable' class='fade'></div>");

  // Instead of setTimeout but again mimicking a callback
  $("#blackDisable").delay().queue(function(){
    $(this).addClass("showBack");
  });

});

.fade {
  opacity: 0;
  transition: opacity .3s linear;
}

.showBack {
  opacity: .5;
}

#blackDisable {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 2222;
  background-color: black;
}

<button id="disable">Click Me</button>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>


问:
grepl with regex
I have a difficulty using grepl with regex.

Here is a small example:

I have a character vector:

```<code>text <- c(

  "D_Purpose__Repairs" ,
  "Age" ,
  "F_Job"
)
</code>```

And I want to select the words that start with D_ or F_.  So I write:

```<code>grepl("\\>D_.+ | \\>F_.+", text)

grepl("\\D_.+ | \\F_.+", text)

grepl("\\^D_.+ | \\^F_.+", text)
</code>```

However this returns:

```<code>[1] FALSE FALSE FALSE
</code>```

Could you help me understand what I am doing wrong and how should I correct my code?

Your advice will be appreciated.

答:
Some comments on your patterns:

\>D_.+ | \>F_.+ - here, \> matches the end of word position while the actual position here is a start of a word (so, you might want to try with \<'). Also, the spaces around|are meaningful, you should not add them unless you use aperl=TRUEwith a(?x)` modifier.

\D_.+ | \F_.+ is a malformed patter since \F is an unknown regex escape. \D matches any char but a digit, and is clearly something you did not expect.

\^D_.+ | \^F_.+ is the closest, but there are redundant spaces again, and the escaped ^  match literal caret symbols. If you do not escape carets they match the start of string positions.

Now, the most efficient pattern here is

```<code>grepl("^[DF]_.+", text)
</code>```

Meaning:

^ - start of string anchor

[DF] -  either D or F letters

_ - a literal underscore

.+ - any 1+ chars as many as possible up to the end of the string.

Title: grepl with regex

Body:
I have a difficulty using grepl with regex.

Here is a small example:

I have a character vector:

text <- c(

  "D_Purpose__Repairs" ,
  "Age" ,
  "F_Job"
)

And I want to select the words that start with D_ or F_.  So I write:

grepl("\\>D_.+ | \\>F_.+", text)

grepl("\\D_.+ | \\F_.+", text)

grepl("\\^D_.+ | \\^F_.+", text)

However this returns:

[1] FALSE FALSE FALSE

Could you help me understand what I am doing wrong and how should I correct my code?

Your advice will be appreciated.

Body:
Some comments on your patterns:

\>D_.+ | \>F_.+ - here, \> matches the end of word position while the actual position here is a start of a word (so, you might want to try with \<'). Also, the spaces around|are meaningful, you should not add them unless you use aperl=TRUEwith a(?x)` modifier.

\D_.+ | \F_.+ is a malformed patter since \F is an unknown regex escape. \D matches any char but a digit, and is clearly something you did not expect.

\^D_.+ | \^F_.+ is the closest, but there are redundant spaces again, and the escaped ^  match literal caret symbols. If you do not escape carets they match the start of string positions.

Now, the most efficient pattern here is

grepl("^[DF]_.+", text)

Meaning:

^ - start of string anchor

[DF] -  either D or F letters

_ - a literal underscore

.+ - any 1+ chars as many as possible up to the end of the string.


问:
fetch is not defined error in React Native
I am trying to use fetch in my project but there is an error saying

fetch is not defined

Someone knowing why?

答:
It might be better to add it in your .eslintrc config instead since the Fetch API is already included in React Native.

Details:
https://github.com/eslint/eslint/issues/4015#issuecomment-301920490


问:
How can I redirect stdout back to the terminal in a multi process c program?
I'm trying to write a c program that is the equivalent of the linux command ps -aux | sort -r -n -k 5 but I'm not getting any output

Here's my code

```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main(int argc, char ** argv){
    int pipes[2];
    int r;
    r = pipe(pipes);
    if (r < 0) {
        fprintf(stderr, "pipe failed\n\n"); // stderr is a FILE* variable for the standard error file (terminal)
        exit(2);
    }
    int saved_stdout = dup(1);
    int pid = fork();
    if(pid > 0){
        // Parent
        pid = fork();
        if(pid > 0){
            // Parent
            wait(NULL);
        }else if (pid == 0){
            // Child 1
        printf("Child 1\n");

        dup2(pipes[1], 1);
        close(pipes[0]);
        close(pipes[1]);

        execlp("/bin/ps", "ps", "-aux", (char*) NULL);
        exit(0);

        }else{
            fprintf(stderr, "FORK FAILED\n\n");
            return 1;
        }
    }else if (pid == 0){
        // Child 2
        printf("Child 2\n");
        dup2(pipes[0], 0);
        close(pipes[0]);
        close(pipes[1]);
        dup2(saved_stdout, 1);
        close(saved_stdout);
        execlp("/bin/sort", "sort", "-r", "-n", "-k", "5", (char*)NULL);
        exit(0);
    }else{
        fprintf(stderr, "FORK FAILED\n\n");
        return 1;
    }
    wait(NULL);
    printf("Exiting parent\n");
}
</code>```

The output I get is this

```<code>Child 1
Child 2
Exiting parent
</code>```

I doesn't actually print the execlp command, I've tried saving stdout to variable saved_stdout which is the solution I found in another answer, but that doesn't seem to work.

How can I redirect stdout back to the terminal?

答:
Strange my output with your code is:

Child 1
Child 2
```

<p>and the program don't stop. Or you sure that your output is valid ?</p>

<p>Whatever, your problem is that you don't close your pipe in your parents. Just add:</p>

```close(pipes[0]);
close(pipes[1]);
```

In your both parents (before your two call to wait()).

Plus saved_stdout is useless in your case, because you only change stdout in your child1. saved_stdout and 1 describe the same file in your child2.

Body:
I'm trying to write a c program that is the equivalent of the linux command ps -aux | sort -r -n -k 5 but I'm not getting any output

Here's my code

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main(int argc, char ** argv){
    int pipes[2];
    int r;
    r = pipe(pipes);
    if (r < 0) {
        fprintf(stderr, "pipe failed\n\n"); // stderr is a FILE* variable for the standard error file (terminal)
        exit(2);
    }
    int saved_stdout = dup(1);
    int pid = fork();
    if(pid > 0){
        // Parent
        pid = fork();
        if(pid > 0){
            // Parent
            wait(NULL);
        }else if (pid == 0){
            // Child 1
        printf("Child 1\n");

        dup2(pipes[1], 1);
        close(pipes[0]);
        close(pipes[1]);

        execlp("/bin/ps", "ps", "-aux", (char*) NULL);
        exit(0);

        }else{
            fprintf(stderr, "FORK FAILED\n\n");
            return 1;
        }
    }else if (pid == 0){
        // Child 2
        printf("Child 2\n");
        dup2(pipes[0], 0);
        close(pipes[0]);
        close(pipes[1]);
        dup2(saved_stdout, 1);
        close(saved_stdout);
        execlp("/bin/sort", "sort", "-r", "-n", "-k", "5", (char*)NULL);
        exit(0);
    }else{
        fprintf(stderr, "FORK FAILED\n\n");
        return 1;
    }
    wait(NULL);
    printf("Exiting parent\n");
}

The output I get is this

Child 1
Child 2
Exiting parent

I doesn't actually print the execlp command, I've tried saving stdout to variable saved_stdout which is the solution I found in another answer, but that doesn't seem to work.

How can I redirect stdout back to the terminal?

Body:
Strange my output with your code is:

Child 1
Child 2

and the program don't stop. Or you sure that your output is valid ?

Whatever, your problem is that you don't close your pipe in your parents. Just add:

close(pipes[0]);
close(pipes[1]);

In your both parents (before your two call to wait()).

Plus saved_stdout is useless in your case, because you only change stdout in your child1. saved_stdout and 1 describe the same file in your child2.


问:
Creating a Div that pops and then disppear in javascript
I am trying to write in javascript a code that shows a div in a random place, then blacks it out after 1000ms and waits for a user's click. My problem is in blackening it (the line that start in //). Could you explain me what's wrong in this?  </p>

```<code> <style type="text/css">
    #test {
    position:absolute;
    width:40px;
    height:40px;
    background-color:#d2fcd9;
}

  </style>

  <title></title>

<script type="text/javascript">//<![CDATA[
$(function(){
$('#test').click(function() {
    var docHeight = $(document).height(),
        docWidth = $(document).width(),
        $div = $('#test'),
        divWidth = $div.width(),
        divHeight = $div.height(),
        heightMax = docHeight - divHeight,
        widthMax = docWidth - divWidth;

    $div.css({
        left: Math.floor( Math.random() * widthMax ),
        top: Math.floor( Math.random() * heightMax ),

    });

    //setTimeout(function() {    $div.css({background-color: '#000000'  }); },          300);

});
});//]]>

</script>

</head>

<body bgcolor="#000000">
  <div id="test" style="left: 1168px; top: 222px;"></div>
</code>```

答:
```<code><style type="text/css">
    #test {
    position:absolute;
    width:40px;
    height:40px;
    background-color:#d2fcd9;
}

  </style>

  <title></title>

<script type="text/javascript">//<![CDATA[
$(function(){
$('#test').click(function() {
    var docHeight = $(document).height(),
        docWidth = $(document).width(),
        $div = $('#test'),
        divWidth = $div.width(),
        divHeight = $div.height(),
        heightMax = docHeight - divHeight,
        widthMax = docWidth - divWidth;

    $div.css({
        left: Math.floor( Math.random() * widthMax ),
        top: Math.floor( Math.random() * heightMax ),

    });

var color =  $div.css("background-color");
if(color === "rgba(0, 0, 0, 0)"){
color = "#d2fcd9;"
}else{
color = "rgba(0, 0, 0, 0)";
}
var timer = setTimeout(function() {    $div.css({"background-color": color  });
 clearTimeout(timer);

 },          300);

});
});//]]>

</script>

</head>

<body bgcolor="#000000">
  <div id="test" style="left: 1168px; top: 222px;"></div>
</code>```

use if-else check to toggle color and use double quotes on "background-color" also clear Timout timer in  setTimeout

Body:
I am trying to write in javascript a code that shows a div in a random place, then blacks it out after 1000ms and waits for a user's click. My problem is in blackening it (the line that start in //). Could you explain me what's wrong in this?

  <title></title>

Body:
<style type="text/css">
    #test {
    position:absolute;
    width:40px;
    height:40px;
    background-color:#d2fcd9;
}

  </style>

  <title></title>

<script type="text/javascript">//<![CDATA[
$(function(){
$('#test').click(function() {
    var docHeight = $(document).height(),
        docWidth = $(document).width(),
        $div = $('#test'),
        divWidth = $div.width(),
        divHeight = $div.height(),
        heightMax = docHeight - divHeight,
        widthMax = docWidth - divWidth;

    $div.css({
        left: Math.floor( Math.random() * widthMax ),
        top: Math.floor( Math.random() * heightMax ),

    });

var color =  $div.css("background-color");
if(color === "rgba(0, 0, 0, 0)"){
color = "#d2fcd9;"
}else{
color = "rgba(0, 0, 0, 0)";
}
var timer = setTimeout(function() {    $div.css({"background-color": color  });
 clearTimeout(timer);

 },          300);

});
});//]]>

</script>

</head>

<body bgcolor="#000000">
  <div id="test" style="left: 1168px; top: 222px;"></div>

use if-else check to toggle color and use double quotes on "background-color" also clear Timout timer in  setTimeout


问:
Cascade style delete in Mongoose
Is there a way to delete all children of an parent in Mongoose, similar to using MySQLs foreign keys?

For example, in MySQL I'd assign a foreign key and set it to cascade on delete. Thus, if I were to delete a client, all applications and associated users would be removed as well.

From a top level:

Delete Client

Delete Sweepstakes

Delete Submissions

Sweepstakes and submissions both have a field for client_id. Submissions has a field for both sweepstakes_id, and client_id.

Right now, I'm using the following code and I feel that there has to be a better way.

```<code>Client.findById(req.params.client_id, function(err, client) {

    if (err)
        return next(new restify.InternalError(err));
    else if (!client)
        return next(new restify.ResourceNotFoundError('The resource you requested could not be found.'));

    // find and remove all associated sweepstakes
    Sweepstakes.find({client_id: client._id}).remove();

    // find and remove all submissions
    Submission.find({client_id: client._id}).remove();

    client.remove();

    res.send({id: req.params.client_id});

});
</code>```

答:
In case your references are stored other way around, say, client has an array of submission_ids, then in a similar way as accepted answer you can define the following on submissionSchema:

```<code>submissionSchema.pre('remove', function(next) {
    Client.update(
        { submission_ids : this._id},
        { $pull: { submission_ids: this._id } },
        { multi: true })  //if reference exists in multiple documents
    .exec();
    next();
});
</code>```

which will remove the submission's id from the clients'  reference arrays on submission.remove().

Title: Cascade style delete in Mongoose

Body:
Is there a way to delete all children of an parent in Mongoose, similar to using MySQLs foreign keys?

For example, in MySQL I'd assign a foreign key and set it to cascade on delete. Thus, if I were to delete a client, all applications and associated users would be removed as well.

From a top level:

Delete Client

Delete Sweepstakes

Delete Submissions

Sweepstakes and submissions both have a field for client_id. Submissions has a field for both sweepstakes_id, and client_id.

Right now, I'm using the following code and I feel that there has to be a better way.

Client.findById(req.params.client_id, function(err, client) {

    if (err)
        return next(new restify.InternalError(err));
    else if (!client)
        return next(new restify.ResourceNotFoundError('The resource you requested could not be found.'));

    // find and remove all associated sweepstakes
    Sweepstakes.find({client_id: client._id}).remove();

    // find and remove all submissions
    Submission.find({client_id: client._id}).remove();

    client.remove();

    res.send({id: req.params.client_id});

});

Body:
In case your references are stored other way around, say, client has an array of submission_ids, then in a similar way as accepted answer you can define the following on submissionSchema:

submissionSchema.pre('remove', function(next) {
    Client.update(
        { submission_ids : this._id},
        { $pull: { submission_ids: this._id } },
        { multi: true })  //if reference exists in multiple documents
    .exec();
    next();
});

which will remove the submission's id from the clients'  reference arrays on submission.remove().


问:
Wrong URLs in Entities section of Tweet object
I'm extracting URLs from tweets using Twitter APIs with a Python lib named Twython. I use home_timeline API and look at entities to search for URLs.
Normally, the links in entities are correct. However, in some cases, the links are wrong. For example, this is a tweet from account @WWF-Philippines:

When I hover the cursor over the highlighted link, it shows shortened_url1 (I cannot put here because Stackoverflow doesn't allow) on the status bar. If I click on the link, it opens an external article. However, if I use Twitter API to query the corresponding tweet, here is the tweet I get:

```<code>Need a guide to properly enjoy the great outdoors while minimizing human impact? This list is for you!\xe2\x80\xa6 shortened_url2
</code>```

You can see the shortened_url2 here is different from the true link (shortened_url1) shown when hovering the cursor. If I follow the shortened_url2, it opens the same tweet. The link in the entities part is the same with this wrong link (shortened_url2).

So what's wrong with Twitter APIs here?
Thanks.

答:
I think you're looking at the old version of the entities.

The Twitter status is - https://twitter.com/WWF_Philippines/status/869027117652033536

Calling https://api.twitter.com/1.1/statuses/show/869027117652033536.json from the API gives us the following entities:

```<code>"truncated": true,
"entities": {
    "hashtags": [],
    "symbols": [],
    "user_mentions": [],
    "urls": [{
        "url": "https:\/\/t.co\/UatUzmm9re",
        "expanded_url": "https:\/\/twitter.com\/i\/web\/status\/869027117652033536",
        "display_url": "twitter.com\/i\/web\/status\/8\u2026",
        "indices": [104, 127]
    }]
},
</code>```

Notice at the top it says "truncated": true,?

Recently Twitter changed how it displays tweets and how they're represented in the API - see https://dev.twitter.com/overview/api/upcoming-changes-to-tweets

You need to add ?tweet_mode=extended to the end of your query.  That will get you back:

```<code>"truncated": false,
"display_text_range": [0, 126],
"entities": {
    "hashtags": [],
    "symbols": [],
    "user_mentions": [],
    "urls": [{
        "url": "https:\/\/t.co\/BgKxmFzrQc",
        "expanded_url": "http:\/\/bit.ly\/7LNTPrinciples",
        "display_url": "bit.ly\/7LNTPrinciples",
        "indices": [103, 126]
    }],
</code>```

Which contains the data you want.

Body:
I'm extracting URLs from tweets using Twitter APIs with a Python lib named Twython. I use home_timeline API and look at entities to search for URLs.
Normally, the links in entities are correct. However, in some cases, the links are wrong. For example, this is a tweet from account @WWF-Philippines:

When I hover the cursor over the highlighted link, it shows shortened_url1 (I cannot put here because Stackoverflow doesn't allow) on the status bar. If I click on the link, it opens an external article. However, if I use Twitter API to query the corresponding tweet, here is the tweet I get:

Need a guide to properly enjoy the great outdoors while minimizing human impact? This list is for you!\xe2\x80\xa6 shortened_url2

You can see the shortened_url2 here is different from the true link (shortened_url1) shown when hovering the cursor. If I follow the shortened_url2, it opens the same tweet. The link in the entities part is the same with this wrong link (shortened_url2).

So what's wrong with Twitter APIs here?
Thanks.

Body:
I think you're looking at the old version of the entities.

The Twitter status is - https://twitter.com/WWF_Philippines/status/869027117652033536

Calling https://api.twitter.com/1.1/statuses/show/869027117652033536.json from the API gives us the following entities:

"truncated": true,
"entities": {
    "hashtags": [],
    "symbols": [],
    "user_mentions": [],
    "urls": [{
        "url": "https:\/\/t.co\/UatUzmm9re",
        "expanded_url": "https:\/\/twitter.com\/i\/web\/status\/869027117652033536",
        "display_url": "twitter.com\/i\/web\/status\/8\u2026",
        "indices": [104, 127]
    }]
},

Notice at the top it says "truncated": true,?

Recently Twitter changed how it displays tweets and how they're represented in the API - see https://dev.twitter.com/overview/api/upcoming-changes-to-tweets

You need to add ?tweet_mode=extended to the end of your query.  That will get you back:

"truncated": false,
"display_text_range": [0, 126],
"entities": {
    "hashtags": [],
    "symbols": [],
    "user_mentions": [],
    "urls": [{
        "url": "https:\/\/t.co\/BgKxmFzrQc",
        "expanded_url": "http:\/\/bit.ly\/7LNTPrinciples",
        "display_url": "bit.ly\/7LNTPrinciples",
        "indices": [103, 126]
    }],

Which contains the data you want.


问:
When is LIMIT applied? Will it select all results before limiting?
I'm concerned about the performance of a query such as SELECT * FROM user LIMIT 5 on a very large user table. Will it select all records then limit to 5?

More specifically will the following query select all assetids before limiting...

```<code>SELECT * FROM assets WHERE asset_id IN(1,2,3,4,5,6,7,8,9,10) LIMIT 5
</code>```

I realize it doesn't make sense to include all ids in the IN() clause if I'm limiting but I'd like to know how mysql behaves in this situation.

Thanks.

答: Your query will have to scan all rows by asset_id column, so you better have an index on it. In my experience, you would always want to set an order by clause also, since the result set will be internally (i.e. order unknown), and you would not know why the returned 5 results were the ones you actually wanted.

Body:
I'm concerned about the performance of a query such as SELECT * FROM user LIMIT 5 on a very large user table. Will it select all records then limit to 5?

More specifically will the following query select all assetids before limiting...

SELECT * FROM assets WHERE asset_id IN(1,2,3,4,5,6,7,8,9,10) LIMIT 5

I realize it doesn't make sense to include all ids in the IN() clause if I'm limiting but I'd like to know how mysql behaves in this situation.

Thanks.


问:
#1062 - Duplicate entry for key 'PRIMARY'
So my MySQL database is behaving a little bit wierd. This is my table:

```<code>Name shares id  price   indvprc
cat   2     4   81      0
goog  4     4   20      20
fb    4     9   20      20
</code>```

I'm getting this #1062 error when I try to insert into the table. So I looked into it further and realized that when I try to insert values into the table, in which the name and shares values are the same, it will return the #1062 error. For example, If i inserted:

```<code>fb    4      6     20   20
</code>```

It would return an error. But if i changed the shares number to 6, it would run fine. Is it because of one of my columns that could be unique, or is it just something with mysql?

答:
I had this error from mySQL using DataNucleus and a database created with UTF8 - the error was being caused by this annotation for a primary key:

```<code>@PrimaryKey
@Unique
@Persistent(valueStrategy = IdGeneratorStrategy.UUIDSTRING)
protected String id;
</code>```

dropping the table and regenerating it with this fixed it.

```<code>@PrimaryKey
@Unique
@Persistent(valueStrategy = IdGeneratorStrategy.UUIDHEX)
protected String id;
</code>```

Body:
So my MySQL database is behaving a little bit wierd. This is my table:

Name shares id  price   indvprc
cat   2     4   81      0
goog  4     4   20      20
fb    4     9   20      20

I'm getting this #1062 error when I try to insert into the table. So I looked into it further and realized that when I try to insert values into the table, in which the name and shares values are the same, it will return the #1062 error. For example, If i inserted:

fb    4      6     20   20

It would return an error. But if i changed the shares number to 6, it would run fine. Is it because of one of my columns that could be unique, or is it just something with mysql?

Body:
I had this error from mySQL using DataNucleus and a database created with UTF8 - the error was being caused by this annotation for a primary key:

@PrimaryKey
@Unique
@Persistent(valueStrategy = IdGeneratorStrategy.UUIDSTRING)
protected String id;

dropping the table and regenerating it with this fixed it.

@PrimaryKey
@Unique
@Persistent(valueStrategy = IdGeneratorStrategy.UUIDHEX)
protected String id;


问:
How to test if a c-string contains characters outside certain ascii range?
So, let say I have simple code below:

```<code>int main() {
    char string1[256]="TEST1";
    char string2[256]="TESTOK"; //Also could be "TEST OK"

    if(//string doesn't contain "A-Z" || doesn't contain "SPACE")
    {
        //do something
    }

    return 0;
}
</code>```

Where the if statement is, all I would want to do is have string1 go into the if statement, because it contains something other than ASCII characters A-Z or a SPACE. However, in both examples of string2, I would want them to bypass the if statement because it contains A-Z or may have a SPACE, which all would be ok and should mean the char string doesn't go into the if statement.

I can not find a simple way to do this with c, to test for this. I have considered just looping through all the characters and testing if the ASCII value is of a certain value range or equals 32 for the space. However, that seems overly complicated. Also, I purposely set the 256 larger than the amount of characters in the string, so I worry about NULL characters messing things up possibly too.

Anyways, is there a simple way to do a test like this in C? Thanks for any help.

答:
I don't think iterating over the characters would be too complicated:

```<code>int i = 0;
while (string1[i] != '\0') {
    if (!((string[i] >= 'A' && string[i] <= 'Z') || string[i] == ' ')) {
        printf("Not good\n");
        break;
    }
    ++i;
}
</code>```

EDIT:

As Stargateur commented, using isupper would be more elegant:

```<code>int i = 0;
while (string1[i] != '\0') {
    if (!(isupper(string[i]) || string[i] == ' ')) {
        printf("Not good\n");
        break;
    }
    ++i;
}
</code>```

Body:
So, let say I have simple code below:

int main() {
    char string1[256]="TEST1";
    char string2[256]="TESTOK"; //Also could be "TEST OK"

    if(//string doesn't contain "A-Z" || doesn't contain "SPACE")
    {
        //do something
    }

    return 0;
}

Where the if statement is, all I would want to do is have string1 go into the if statement, because it contains something other than ASCII characters A-Z or a SPACE. However, in both examples of string2, I would want them to bypass the if statement because it contains A-Z or may have a SPACE, which all would be ok and should mean the char string doesn't go into the if statement.

I can not find a simple way to do this with c, to test for this. I have considered just looping through all the characters and testing if the ASCII value is of a certain value range or equals 32 for the space. However, that seems overly complicated. Also, I purposely set the 256 larger than the amount of characters in the string, so I worry about NULL characters messing things up possibly too.

Anyways, is there a simple way to do a test like this in C? Thanks for any help.

Body:
I don't think iterating over the characters would be too complicated:

int i = 0;
while (string1[i] != '\0') {
    if (!((string[i] >= 'A' && string[i] <= 'Z') || string[i] == ' ')) {
        printf("Not good\n");
        break;
    }
    ++i;
}

EDIT:

As Stargateur commented, using isupper would be more elegant:

int i = 0;
while (string1[i] != '\0') {
    if (!(isupper(string[i]) || string[i] == ' ')) {
        printf("Not good\n");
        break;
    }
    ++i;
}


问:
RPM build errors: Bad exit status from /var/tmp/rpm-tmp.MJ4rSp (%prep)
I'm trying to use the command "fedpkg prep" but when I do I get the following error
RPM build errors:
    Bad exit status from /var/tmp/rpm-tmp.MJ4rSp (%prep)
How do I resolve this problem? I'm a newbie to Linux. </p>

答: When I scrolled up to see if I could find an error, I discovered there wasn't enough space in the /boot directory for fedpkg prep to execute</p>


问:
Error with Spawned command: npminstall
I am trying to run a sample application from
https://ionicframework.com/getting-started/.
But I am getting the error - there was an error with the spawned process: npminstall every time I try to run the application. Any help is highly appreciated.</p>

答:
For me it was only to upgrade to new version of npm</p>

```<code>npm install -g npm
</code>```

Title: Error with Spawned command: npminstall

Body:
For me it was only to upgrade to new version of npm

npm install -g npm