问:
How to Save the Filters in Fiddler
When i find the Tariff how to save the filter list  for the next reboot ? https://i.stack.imgur.com/7KZEj.jpg

答: Fiddler does not presently offer that feature. Vote here https://fiddler.ideas.aha.io/ideas/FID-I-114</p>

Title: How to Save the Filters in Fiddler


来源: stackexchange

问:
RxJava: Only emit if the first item for a given period
I want to transform my source Flowable in such a way that events only go though if they are the first item within a specified period.

That is, I want the first item to go through and then drop all subsequent items until there was a period of, say, 10 seconds, in which no upstream event arrived.

Note that is this neither

debounce: This would emit each item iff it was not followed by another one for 10 seconds - but this will force a 10 second delay on even the first item. I want to emit the first item right away.

throttleFirst: This would emit the first item and then drop all subsequent items for 10 seconds after that first one. I want to have the blocking period reset after each upstream item.

I've now solved it like this:

```<code>source
  .flatMap { Flowable.just(1).concatWith(Flowable.just(-1).delay(10, TimeUnit.SECONDS)) }
  .scan(0, { x, y -> x + y })
  .map { it > 0 }
  .distinctUntilChanged()
  .filter { it }
</code>```

NOTE: I don't care about the actual items in source, only that they occur - but, of course, I could just wrap the items in a Pair along with 1 or -1).

Is there a simpler way to use built-in RxJava(2) Operators to achieve the same goal?

答:
This might do what you need</p>

```<code>source.debounce(item -> Observable.timer(10,TimeUnit.SECONDS))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to transform my source Flowable in such a way that events only go though if they are the first item within a specified period.

That is, I want the first item to go through and then drop all subsequent items until there was a period of, say, 10 seconds, in which no upstream event arrived.

Note that is this neither

debounce: This would emit each item iff it was not followed by another one for 10 seconds - but this will force a 10 second delay on even the first item. I want to emit the first item right away.

throttleFirst: This would emit the first item and then drop all subsequent items for 10 seconds after that first one. I want to have the blocking period reset after each upstream item.

I've now solved it like this:

source
  .flatMap { Flowable.just(1).concatWith(Flowable.just(-1).delay(10, TimeUnit.SECONDS)) }
  .scan(0, { x, y -> x + y })
  .map { it > 0 }
  .distinctUntilChanged()
  .filter { it }

NOTE: I don't care about the actual items in source, only that they occur - but, of course, I could just wrap the items in a Pair along with 1 or -1).

Is there a simpler way to use built-in RxJava(2) Operators to achieve the same goal?

Body:
This might do what you need

source.debounce(item -> Observable.timer(10,TimeUnit.SECONDS))


问:
What is the difference between triangle inequality and path relaxation in Dijkstra's algorithm?
The relaxation process in Dijkstra's algorithm refers to updating the cost of all vertices connected to a vertex v from source vertex V.

I think the triangle inequality also refers the same.

答:
I know this is an old question but since I'm here I'll add a relevant answer in case it helps someone else...

What happens in the relaxation step of a shortest path algorithm is a move towards the shortest path. The algorithm maintains an estimate of the shortest path from node u to node v and corrects itself whenever it detects a shorter path during its walk.

If relaxation occurs that means that a violation of the triangle inequality was detected, and since that can't actually happen then it must mean that the algorithm's estimate is incorrect, so it updates the estimate through relaxation in order to bring the triangle formed by the three paths back into compliance with the triangle inequality.

The algorithm starts with estimates at infinity, and as it progresses, through relaxation these estimates each converge on the correct shortest path for each node.


问:
Truncating the end of variables based on pattern
I have a list of URLs in formats such as "www.blah.com/en-us" and I need to cut-off anything after the "www.blah.com". I've tried using the following:

```<code>import re
website = www.blah.com/en-us
cleanURL = re.sub('(.|\n)*?com', "", website)
</code>```

Output: 'en-us'

So I'm getting the opposite of what I want. Sorry if this post isn't correctly formatted, first time asking a question.

答: Is using regex a must? If there's no protocol (e.g. http://) in the URLs that you're trying to process, you could just use your_url_string.split('/', 1)[0] which should split on the first instance of '/' and gives you the part before the split.

Body:
I have a list of URLs in formats such as "www.blah.com/en-us" and I need to cut-off anything after the "www.blah.com". I've tried using the following:

import re
website = www.blah.com/en-us
cleanURL = re.sub('(.|\n)*?com', "", website)

Output: 'en-us'

So I'm getting the opposite of what I want. Sorry if this post isn't correctly formatted, first time asking a question.


问:
Really Slow MySQL Insert Query
I've got a table with about half a million records in it. It's not huge. A couple varchar(255) fields, some ints, a float, and a couple timestamps. There are indices on the ints as well as foreign key constraints. Inserts are taking forever. I'm talking 1-4 seconds to insert one row. I've had to deal with slow select queries plenty of times, but I'm stuck trying to figure out what's going on with this insert.

EDIT: Okay, I was really just asking for ideas on how to debug this, but, here's all the tables involved. Inserting into "ingredients" is what takes forever. Hopefully throwing a good portion of my schema onto the web doesn't bite me later...

```<code>CREATE TABLE `ingredients` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `quantity` float DEFAULT NULL,
  `food` varchar(255) NOT NULL,
  `unit_id` int(11) DEFAULT NULL,
  `ingredient_group_id` int(11) DEFAULT NULL,
  `order_by` int(11) NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  `description` varchar(255) DEFAULT NULL,
  `range` float DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `unit_id` (`unit_id`),
  KEY `ingredient_group_id` (`ingredient_group_id`),
  CONSTRAINT `ingredients_ibfk_1` FOREIGN KEY (`unit_id`) REFERENCES `units` (`id`),
  CONSTRAINT `ingredients_ibfk_2` FOREIGN KEY (`ingredient_group_id`) REFERENCES `ingredient_groups` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=269974 DEFAULT CHARSET=utf8

CREATE TABLE `units` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `abbreviation` varchar(255) CHARACTER SET latin1 NOT NULL,
  `type` int(11) NOT NULL,
  `si` float NOT NULL,
  `lower_bound` float DEFAULT NULL,
  `lower_unit_id` int(11) DEFAULT NULL,
  `upper_bound` float DEFAULT NULL,
  `upper_unit_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `lower_unit_id` (`lower_unit_id`),
  KEY `upper_unit_id` (`upper_unit_id`),
  CONSTRAINT `units_ibfk_1` FOREIGN KEY (`lower_unit_id`) REFERENCES `units` (`id`),
  CONSTRAINT `units_ibfk_2` FOREIGN KEY (`upper_unit_id`) REFERENCES `units` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8

CREATE TABLE `ingredient_groups` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `recipe_id` int(11) NOT NULL,
  `order_by` int(11) NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`id`),
  KEY `recipe_id` (`recipe_id`),
  CONSTRAINT `ingredient_groups_ibfk_1` FOREIGN KEY (`recipe_id`) REFERENCES `recipes` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=32739 DEFAULT CHARSET=utf8
</code>```

答:
You might want to look at the ingredients.unit_id index, since it has a low selectivity.

are the inserts happening concurrently?

ContentLicense: CC BY-SA 2.5

Title: Really Slow MySQL Insert Query

Body:
I've got a table with about half a million records in it. It's not huge. A couple varchar(255) fields, some ints, a float, and a couple timestamps. There are indices on the ints as well as foreign key constraints. Inserts are taking forever. I'm talking 1-4 seconds to insert one row. I've had to deal with slow select queries plenty of times, but I'm stuck trying to figure out what's going on with this insert.

EDIT: Okay, I was really just asking for ideas on how to debug this, but, here's all the tables involved. Inserting into "ingredients" is what takes forever. Hopefully throwing a good portion of my schema onto the web doesn't bite me later...

CREATE TABLE `ingredients` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `quantity` float DEFAULT NULL,
  `food` varchar(255) NOT NULL,
  `unit_id` int(11) DEFAULT NULL,
  `ingredient_group_id` int(11) DEFAULT NULL,
  `order_by` int(11) NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  `description` varchar(255) DEFAULT NULL,
  `range` float DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `unit_id` (`unit_id`),
  KEY `ingredient_group_id` (`ingredient_group_id`),
  CONSTRAINT `ingredients_ibfk_1` FOREIGN KEY (`unit_id`) REFERENCES `units` (`id`),
  CONSTRAINT `ingredients_ibfk_2` FOREIGN KEY (`ingredient_group_id`) REFERENCES `ingredient_groups` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=269974 DEFAULT CHARSET=utf8

CREATE TABLE `units` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `abbreviation` varchar(255) CHARACTER SET latin1 NOT NULL,
  `type` int(11) NOT NULL,
  `si` float NOT NULL,
  `lower_bound` float DEFAULT NULL,
  `lower_unit_id` int(11) DEFAULT NULL,
  `upper_bound` float DEFAULT NULL,
  `upper_unit_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `lower_unit_id` (`lower_unit_id`),
  KEY `upper_unit_id` (`upper_unit_id`),
  CONSTRAINT `units_ibfk_1` FOREIGN KEY (`lower_unit_id`) REFERENCES `units` (`id`),
  CONSTRAINT `units_ibfk_2` FOREIGN KEY (`upper_unit_id`) REFERENCES `units` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8

CREATE TABLE `ingredient_groups` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `recipe_id` int(11) NOT NULL,
  `order_by` int(11) NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`id`),
  KEY `recipe_id` (`recipe_id`),
  CONSTRAINT `ingredient_groups_ibfk_1` FOREIGN KEY (`recipe_id`) REFERENCES `recipes` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=32739 DEFAULT CHARSET=utf8


问:
PHP openssl_pkcs7_verify Not Working
I`m using pkcs7 to sign a document and everything works fine, the problem is that the command to verify the sign is not working, always return false. I try to use the terminal command into the file and works fine.

Sign command:

```<code>openssl_pkcs7_sign(
    $tempdoc,
    $tempsign,
    $this->signature_data['signcert'],
    array($this->signature_data['privkey'],
    $this->signature_data['password']),
    array(),
    PKCS7_BINARY | PKCS7_DETACHED);
</code>```

Verify command:

```<code>openssl_pkcs7_verify($tempsign, PKCS7_NOVERIFY)
</code>```

Terminal command:

```<code>openssl pkcs7 -inform DER -in signature.pkcs7 -print_certs -text
</code>```

EDIT 1

I make tests in my code and discover if i create my sign with only PKCS7_DETACHED or PKCS7_BINARY works fine the verify, but both together i receive the error. Why this is happening?

答:
Here with PHP 7 i can reproduce your problem. With both flags the verify fails.

Maybe THIS URL can help you., this part talks about it.

SMIME -sign "detached" "attaches" content similarly as-is  with
  -binary and text-canonicalized without, and signs that.  SMIME -verify recognizes "detached", but (in multi_split)  always canonicalizes both
  parts before using them. For content  that was sent noncanonical (with
  -sign -binary or equivalent)  this changes the signed content, and verify fails.  Content that was canonical as sent (originally
  canonical  or canonicalized by sender) does verify and similarly  is
  output without determining if sender changed it.

In the docs you can read that the parser isn't that smart:

BUGS

The MIME parser isn't very clever: it seems to handle most messages
  that I've thrown at it but it may choke on others.

Hope it helps!

Title: PHP openssl_pkcs7_verify Not Working

Body:
I`m using pkcs7 to sign a document and everything works fine, the problem is that the command to verify the sign is not working, always return false. I try to use the terminal command into the file and works fine.

Sign command:

openssl_pkcs7_sign(
    $tempdoc,
    $tempsign,
    $this->signature_data['signcert'],
    array($this->signature_data['privkey'],
    $this->signature_data['password']),
    array(),
    PKCS7_BINARY | PKCS7_DETACHED);

Verify command:

openssl_pkcs7_verify($tempsign, PKCS7_NOVERIFY)

Terminal command:

openssl pkcs7 -inform DER -in signature.pkcs7 -print_certs -text

EDIT 1

I make tests in my code and discover if i create my sign with only PKCS7_DETACHED or PKCS7_BINARY works fine the verify, but both together i receive the error. Why this is happening?


问:
How can I change Windows auth for a method based on the parameters it is passed?
Right now in my MVC application, I am using Windows Auth to restrict access to certain methods, like so:

```<code>   [Authorize(Roles = SystemRole.AppAdmin)]

    public ActionResult Edit(int? id)
    {
        //Find group by id in db
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    [Authorize(Roles = SystemRole.AppAdmin)]
    public ActionResult Edit([Bind(Include = "id, otherParam")] Item thisItem)
        //Post changes to db
    }
</code>```

I would like to have my code so that another AD group has limited admin rights to edit ONLY an item with a certain id (e.g. item 7), not allow them to access this method to try to edit other items.

I've tried Googling/searching Stack Overflow/reading Windows Auth documentation but must not be using good keywords, because I surely can't be the first person to want to do something like this.

答:
That kind of complex authorization is a bit tricky with default Windows Authentication.

You will need a hybrid approach in which your application stores users and their authorization in separate database.

Then add those authorization as claims when they sign-in. You can then apply Authorize attribute to action methods and controllers.

```<code>public void SignIn(User user, IList<string> roleNames)
{
   IList<Claim> claims = new List<Claim>
   {
      new Claim(ClaimTypes.Sid, user.Id.ToString()),
      new Claim(ClaimTypes.Name, user.UserName),
      new Claim(ClaimTypes.GivenName, user.FirstName),
      new Claim(ClaimTypes.Surname, user.LastName),
   };

   foreach (string roleName in roleNames)
   {
      claims.Add(new Claim(ClaimTypes.Role, roleName));
   }

   ClaimsIdentity identity = new ClaimsIdentity(claims, AuthenticationType);

   IOwinContext context = _context.Request.GetOwinContext();
   IAuthenticationManager authenticationManager = context.Authentication;

   authenticationManager.SignIn(identity);
}
</code>```

I have a working sample application at GitHub. You can take a look at it.

Body:
Right now in my MVC application, I am using Windows Auth to restrict access to certain methods, like so:

   [Authorize(Roles = SystemRole.AppAdmin)]

    public ActionResult Edit(int? id)
    {
        //Find group by id in db
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    [Authorize(Roles = SystemRole.AppAdmin)]
    public ActionResult Edit([Bind(Include = "id, otherParam")] Item thisItem)
        //Post changes to db
    }

I would like to have my code so that another AD group has limited admin rights to edit ONLY an item with a certain id (e.g. item 7), not allow them to access this method to try to edit other items.

I've tried Googling/searching Stack Overflow/reading Windows Auth documentation but must not be using good keywords, because I surely can't be the first person to want to do something like this.

Body:
That kind of complex authorization is a bit tricky with default Windows Authentication.

You will need a hybrid approach in which your application stores users and their authorization in separate database.

Then add those authorization as claims when they sign-in. You can then apply Authorize attribute to action methods and controllers.

public void SignIn(User user, IList<string> roleNames)
{
   IList<Claim> claims = new List<Claim>
   {
      new Claim(ClaimTypes.Sid, user.Id.ToString()),
      new Claim(ClaimTypes.Name, user.UserName),
      new Claim(ClaimTypes.GivenName, user.FirstName),
      new Claim(ClaimTypes.Surname, user.LastName),
   };

   foreach (string roleName in roleNames)
   {
      claims.Add(new Claim(ClaimTypes.Role, roleName));
   }

   ClaimsIdentity identity = new ClaimsIdentity(claims, AuthenticationType);

   IOwinContext context = _context.Request.GetOwinContext();
   IAuthenticationManager authenticationManager = context.Authentication;

   authenticationManager.SignIn(identity);
}

I have a working sample application at GitHub. You can take a look at it.


问:
randomly seeing 'Stub found while resolving method "???" overloading """" in package "XXX" '
We've in the past few weeks relocated our server and are randomly (but too often) getting the follow error.

The dbix verison is now 0.082820 and previously was 0.08250 without this error occurring.

"Stub found while resolving method "???" overloading """" in package "XXX" at /home/perlbrew/.perlbrew/libs/perl-5.16.3@latest-20160209/lib/perl5/DBIx/Class/Row.pm line 1250."

the package XXX

has which might be related

```<code>use Class::Trait qw( TPrintable  );

sub inflate_result {
    my $self = shift;
    my $ret = $self->next::method(@_);
    my $typeCd = $ret->typeCd;
    given ($typeCd) {
        when( $specialTypeCd ) {
            $self->ensure_class_loaded( $specialSubClass );
            bless ($ret, $specialSubClass);
        }
        default {
            bless ($ret, $self);
        }
    }
    return $ret;
}
</code>```

The code bringing in package XXX has a helper method doing:

```<code>my $theY = $c->model('DB::Y')->find( $yID,
    {
        prefetch => [ { 'xxxs' => 'typecd' } , 'zid' ]
    });

return $theY;
</code>```

thoughts in what the problem is; how to get it consistent to submit a bug report.

We already know about the potential workaround in Abstract.pm
of SQLA_ISVALUE_IGNORE_AUTOGENERATED_STRINGIFICATION=1

答:
A suggested fix by a person who choices to remain anonymous
(which was not enough for us in our perl 5.16.3)

We ended up switching to perl 5.26 and the problem is gone. (We were told "You are very unlikely to: 5.18 overhauled a lot of the overload internals.")

```<code>diff --git a/lib/SQL/Abstract.pm b/lib/SQL/Abstract.pm
index 264b0b1..b4d8fb4 100644
--- a/lib/SQL/Abstract.pm
+++ b/lib/SQL/Abstract.pm
@@ -104,7 +104,11 @@ sub is_plain_value ($) {
         # "%s"> and the source of overload::mycan())
         #
         # either has stringification which DBI SHOULD prefer out of the box
-        grep { *{ (qq[${_}::(""]) }{CODE} } @{ $_[2] = mro::get_linear_isa( $_[1] ) }
+        grep {
+          *{ (qq[${_}::()]) }{CODE}
+            and
+          *{ (qq[${_}::(""]) }{CODE}
+        } @{ $_[2] = mro::get_linear_isa( $_[1] ) }
           or
         # has nummification or boolification, AND fallback is *not* disabled
         (
</code>```

To put your mind at ease: here is what is actually happening:

```<code>perl -e '

    use warnings;
    use strict;

    require Scalar::Util;

    {
      package Some::Overload;
      use overload
        q{""}       => "named_stringifier",
        fallback => 1,
      ;

      sub named_stringifier { $_[0] . "" }
    }

    {
      package Some::Subclass;
      use base "Some::Overload";
    }

    my $thing = bless {}, "Some::Subclass";

    {
      no strict "refs";
      grep { *{ (qq[${_}::(""]) }{CODE} } qw( Some::Subclass Some::Overload );
    }

    for (1, 2) {

      # simulates runtime require of some *UNRELATED* class
      eval sprintf <<EOS, $_;
      {
        package Some::UnrelatedThing%s;
        use overload
          q{""} => sub { \$_[0] . "" },
          fallback => 1,
        ;
      }
EOS

      my $some_object = bless {}, "Some::Subclass";
    }

    warn "got here, all is well\n";
    exit 0;
'
</code>```

Body:
We've in the past few weeks relocated our server and are randomly (but too often) getting the follow error.

The dbix verison is now 0.082820 and previously was 0.08250 without this error occurring.

"Stub found while resolving method "???" overloading """" in package "XXX" at /home/perlbrew/.perlbrew/libs/perl-5.16.3@latest-20160209/lib/perl5/DBIx/Class/Row.pm line 1250."

the package XXX

has which might be related

use Class::Trait qw( TPrintable  );

sub inflate_result {
    my $self = shift;
    my $ret = $self->next::method(@_);
    my $typeCd = $ret->typeCd;
    given ($typeCd) {
        when( $specialTypeCd ) {
            $self->ensure_class_loaded( $specialSubClass );
            bless ($ret, $specialSubClass);
        }
        default {
            bless ($ret, $self);
        }
    }
    return $ret;
}

The code bringing in package XXX has a helper method doing:

my $theY = $c->model('DB::Y')->find( $yID,
    {
        prefetch => [ { 'xxxs' => 'typecd' } , 'zid' ]
    });

return $theY;

thoughts in what the problem is; how to get it consistent to submit a bug report.

We already know about the potential workaround in Abstract.pm
of SQLA_ISVALUE_IGNORE_AUTOGENERATED_STRINGIFICATION=1

Body:
A suggested fix by a person who choices to remain anonymous
(which was not enough for us in our perl 5.16.3)

We ended up switching to perl 5.26 and the problem is gone. (We were told "You are very unlikely to: 5.18 overhauled a lot of the overload internals.")

diff --git a/lib/SQL/Abstract.pm b/lib/SQL/Abstract.pm
index 264b0b1..b4d8fb4 100644
--- a/lib/SQL/Abstract.pm
+++ b/lib/SQL/Abstract.pm
@@ -104,7 +104,11 @@ sub is_plain_value ($) {
         # "%s"> and the source of overload::mycan())
         #
         # either has stringification which DBI SHOULD prefer out of the box
-        grep { *{ (qq[${_}::(""]) }{CODE} } @{ $_[2] = mro::get_linear_isa( $_[1] ) }
+        grep {
+          *{ (qq[${_}::()]) }{CODE}
+            and
+          *{ (qq[${_}::(""]) }{CODE}
+        } @{ $_[2] = mro::get_linear_isa( $_[1] ) }
           or
         # has nummification or boolification, AND fallback is *not* disabled
         (

To put your mind at ease: here is what is actually happening:

perl -e '

    use warnings;
    use strict;

    require Scalar::Util;

    {
      package Some::Overload;
      use overload
        q{""}       => "named_stringifier",
        fallback => 1,
      ;

      sub named_stringifier { $_[0] . "" }
    }

    {
      package Some::Subclass;
      use base "Some::Overload";
    }

    my $thing = bless {}, "Some::Subclass";

    {
      no strict "refs";
      grep { *{ (qq[${_}::(""]) }{CODE} } qw( Some::Subclass Some::Overload );
    }

    for (1, 2) {

      # simulates runtime require of some *UNRELATED* class
      eval sprintf <<EOS, $_;
      {
        package Some::UnrelatedThing%s;
        use overload
          q{""} => sub { \$_[0] . "" },
          fallback => 1,
        ;
      }
EOS

      my $some_object = bless {}, "Some::Subclass";
    }

    warn "got here, all is well\n";
    exit 0;
'


答:
How about just using

```<code>website = "www.blah.com/en-us"
cleanURL = website.split("/",1)[0]
</code>```

?

Title: Truncating the end of variables based on pattern

Body:
How about just using

website = "www.blah.com/en-us"
cleanURL = website.split("/",1)[0]

?


问:
Macros script Excel, filling in blanks with NULLS, error 400
All i'm trying to do is fill in NULL in the cells that are blank.

source code:

```<code>Sub fillNULLs()

Dim count As Integer
count = 0

Dim col As Integer
col = 2

While count < 23403

If (Cells(count, col) = "") Then

Cells(count, col) = "Null"

End If

count = count + 1

Wend

End Sub
</code>```

I run the macros and i get a 400 and an okay button. Can anyone spot the issue

答:
```<code>Sub fillNULLs()
Dim a, b As Range

Set a = Range("B1:B23402")
For Each b In a
   If (Trim(b.Value) = "") Then b = Null
Next b

End Sub
</code>```

Edit

To check it is doing what it must do

```<code>Sub fillNULLs()
Dim a, b As Range

Set a = Range("B1:B23402")
For Each b In a
   If (Trim(b.Value) = "") Then b = "Null"
Next b

End Sub
</code>```

You will see "Null" in the modified values.

Body:
All i'm trying to do is fill in NULL in the cells that are blank.

source code:

Sub fillNULLs()

Dim count As Integer
count = 0

Dim col As Integer
col = 2

While count < 23403

If (Cells(count, col) = "") Then

Cells(count, col) = "Null"

End If

count = count + 1

Wend

End Sub

I run the macros and i get a 400 and an okay button. Can anyone spot the issue

Body:
Sub fillNULLs()
Dim a, b As Range

Set a = Range("B1:B23402")
For Each b In a
   If (Trim(b.Value) = "") Then b = Null
Next b

End Sub

Edit

To check it is doing what it must do

Sub fillNULLs()
Dim a, b As Range

Set a = Range("B1:B23402")
For Each b In a
   If (Trim(b.Value) = "") Then b = "Null"
Next b

End Sub

You will see "Null" in the modified values.


问:
Combine sheet 3 from many workbooks into one new workbook
I have 77 workbooks and need to combine sheet 3 in all of them into one sheet in a new workbook. I have not done this in years.  I would really appreciate Any help. I modified some code from other webpages but it is not working for me.</p>

答:
If all of them are in one folder then this works:</p>

```<code>Sub CopySheetsOver()
 Dim Path As String, Filename As String
 Dim wbk As Workbook
 Dim wsh As Worksheet

 Path = "C:\Users\MaryGM\Desktop\YourFolder\" 'set the path to the desired folder
 Filename = Dir(Path & "*.xls") 'get names of all xls files, change to xlsx if desired

 Do While Filename <> "" 'loop over all the xlsx files in that folder
    Workbooks.Open Filename:=Path & Filename, ReadOnly:=True

    Set wbk = ActiveWorkbook
    If wbk.Worksheets.Count > 2 Then 'check if the third sheet exists
    Set wsh = wbk.Sheets(3)
    wsh.Copy After:=ThisWorkbook.Sheets(1)
   'set the name to be combination of original sheet name and its corresponding workbook:
    ThisWorkbook.ActiveSheet.Name = wbk.Name & "-" & wsh.Name
    End If
    Workbooks(Filename).Close
    Filename = Dir()
 Loop
End Sub
</code>```

ContentLicense: CC BY-SA 4.0

Body:
If all of them are in one folder then this works:

Sub CopySheetsOver()
 Dim Path As String, Filename As String
 Dim wbk As Workbook
 Dim wsh As Worksheet

 Path = "C:\Users\MaryGM\Desktop\YourFolder\" 'set the path to the desired folder
 Filename = Dir(Path & "*.xls") 'get names of all xls files, change to xlsx if desired

 Do While Filename <> "" 'loop over all the xlsx files in that folder
    Workbooks.Open Filename:=Path & Filename, ReadOnly:=True

    Set wbk = ActiveWorkbook
    If wbk.Worksheets.Count > 2 Then 'check if the third sheet exists
    Set wsh = wbk.Sheets(3)
    wsh.Copy After:=ThisWorkbook.Sheets(1)
   'set the name to be combination of original sheet name and its corresponding workbook:
    ThisWorkbook.ActiveSheet.Name = wbk.Name & "-" & wsh.Name
    End If
    Workbooks(Filename).Close
    Filename = Dir()
 Loop
End Sub


问:
dotnet restore NuGet.Config environment variables for ClearTextPassword doesn't work
To do CI I'd like to checkin a NuGet.Config file with my own nuget feed (an VSTS one). Like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="myfeed" value="https://xxx.pkgs.visualstudio.com/_packaging/myfeed/nuget/v3/index.json" />
  </packageSources>
  <packageSourceCredentials>
    <myfeed>
        <add key="ClearTextPassword" value="%PASSWD%" />
    </myfeed>
  </packageSourceCredentials>
</configuration>
</code>```

Because I don't want to check in the password, I read you can use Environment Variables in this configuration. I tried it and it works in the PackageSources value. But it seems it doesn't work in the PackageSourceCredentials like shown above.
Does someone has a solution for this?

答: I had to add the key Username to the PackageSourceCredentials. I thought it was of no use. But it cached the first time I removed it and later I added the env var and after this it broke.

Body:
To do CI I'd like to checkin a NuGet.Config file with my own nuget feed (an VSTS one). Like this:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="myfeed" value="https://xxx.pkgs.visualstudio.com/_packaging/myfeed/nuget/v3/index.json" />
  </packageSources>
  <packageSourceCredentials>
    <myfeed>
        <add key="ClearTextPassword" value="%PASSWD%" />
    </myfeed>
  </packageSourceCredentials>
</configuration>

Because I don't want to check in the password, I read you can use Environment Variables in this configuration. I tried it and it works in the PackageSources value. But it seems it doesn't work in the PackageSourceCredentials like shown above.
Does someone has a solution for this?


问:
How to customize Acrylic brush
I want to paint Stack Panel surface using Acrylic brush.

```<code><StackPanel Background="{ThemeResource SystemControlAcrylicElementBrush}"></StackPanel>
</code>```

It works for me but there is a problem when I want to change Tint color and opacity. There is a following code to change it:

```<code><ResourceDictionary.ThemeDictionaries>
<ResourceDictionary x:Key="Default">
    <AcrylicBrush x:Key="MyAcrylicBrush"
        BackgroundSource="HostBackdrop"
        TintColor="#FFFF0000"
        TintOpacity="0.8"
        FallbackColor="#FF7F0000"/>
</ResourceDictionary>
</code>```

I don't know where should I place it and rename brush for this?

```<code> <StackPanel Background="{ThemeResource **MyAcrylicBrush**}"></StackPanel>
</code>```

Thanks for help.
P.S. You need Windows Insider SDK and system build 16190 or higher

答:
You can create a ResourceDictionary, for example called "ThemeDictionary.xaml" and put the code you have for your AcrylicBrush in there.

Then in your App.xaml you can reference your ResourceDictionary like so:

```<code><Application.Resources>
  <ResourceDictionary>
    <ResourceDictionary.MergedDictionaries>
      <ResourceDictionary Source="ThemesDictionary.xaml" />
    </ResourceDictionary.MergedDictionaries>
  </ResourceDictionary>
</Application.Resources>
</code>```

Title: How to customize Acrylic brush

Body:
I want to paint Stack Panel surface using Acrylic brush.

<StackPanel Background="{ThemeResource SystemControlAcrylicElementBrush}"></StackPanel>

It works for me but there is a problem when I want to change Tint color and opacity. There is a following code to change it:

<ResourceDictionary.ThemeDictionaries>
<ResourceDictionary x:Key="Default">
    <AcrylicBrush x:Key="MyAcrylicBrush"
        BackgroundSource="HostBackdrop"
        TintColor="#FFFF0000"
        TintOpacity="0.8"
        FallbackColor="#FF7F0000"/>
</ResourceDictionary>

I don't know where should I place it and rename brush for this?

 <StackPanel Background="{ThemeResource **MyAcrylicBrush**}"></StackPanel>

Thanks for help.
P.S. You need Windows Insider SDK and system build 16190 or higher

Body:
You can create a ResourceDictionary, for example called "ThemeDictionary.xaml" and put the code you have for your AcrylicBrush in there.

Then in your App.xaml you can reference your ResourceDictionary like so:

<Application.Resources>
  <ResourceDictionary>
    <ResourceDictionary.MergedDictionaries>
      <ResourceDictionary Source="ThemesDictionary.xaml" />
    </ResourceDictionary.MergedDictionaries>
  </ResourceDictionary>
</Application.Resources>


问:
Unable To Implement Thymeleaf 3.0Decoupled Logic, Template is not getting populated with data?
I want to try decoupled template logic using thymeleaf. This is mentioned here in  thymeleaf 3.0 documentation.

According to tutorial I have created my project here

My template & decoupled logic is present inside LogicTemplate.html & LogicTemplate.th.xml file.

Code Snippet For LogicTemplate.html is as follows:

<title>ThymeLeaf:Example03</title>

   Name
   Price
   In Stock
   Comments

   Ppap
   10
   Yes
   No Comments

```
</div>
</div>

 4. Code Snippet For LogicTemplate.th.xml is as follows: </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-html lang-html prettyprint-override"><code><?xml version="1.0"?>
<thlogic>
  <attr sel="#ProductTable" th:remove="all-but-first">
    <attr sel="/tr[0]" th:each="prod : ${products}">
      <attr sel="td.Name" th:text="${prod.name}" />
      <attr sel="td.Price" th:text="${prod.price}" />
      <attr sel="td.InStock" th:text="${prod.inStock}" />
      <attr sel="td.Comments" th:text="${${prod.comments!=null and (not #lists.isEmpty(prod.comments))}?#lists.size(prod.comments):0}}" />
    </attr>
  </attr>
</thlogic></code>```

  5. I have created following java class DeCoupledLogic,Code snippet shown below:
`

```<code>public class DeCoupledLogic {
        public static void main(String[] args) {
            final FileTemplateResolver templateResolverFile = new FileTemplateResolver();
            templateResolverFile.setTemplateMode(TemplateMode.HTML);
            templateResolverFile.setPrefix("src/main/resources/templates/html/");
            templateResolverFile.setSuffix(".html");
            templateResolverFile.setCacheTTLMs(1 * 60 * 60 * 1000l);
            templateResolverFile.setCacheable(Boolean.TRUE);
            templateResolverFile.setCharacterEncoding("UTF-8");
            templateResolverFile.setCheckExistence(true);
            templateResolverFile.setUseDecoupledLogic(true);
            templateResolverFile.setCheckExistence(true);

            final StandardDecoupledTemplateLogicResolver resolver=new StandardDecoupledTemplateLogicResolver();
            resolver.setPrefix("src/main/resources/templates/html/");

            final TemplateEngine templateEngine = new TemplateEngine();
            templateEngine.setTemplateResolver(templateResolverFile);
            templateEngine.setDecoupledTemplateLogicResolver(resolver);

            final Context context01 = new Context();
            context01.setVariable("products",ProductRepository.getInstance().findAll());

            final BufferedWriter writer01=new BufferedWriter(new OutputStreamWriter(System.out));
            templateEngine.process("LogicTemplate",context01,writer01);
        }
    }
</code>```

`
But executing this code does not gives desired result.
Output Actual:

<title>ThymeLeaf:Example03</title>

   Name
   Price
   In Stock
   Comments

   Ppap
   10
   Yes
   No Comments

```

Output Expected:
Must not contain this static text but all product information.But I am unable to figure out where this code piece went wrong.Please Help me to identify potential error in my code.

答:
Thymeleaf configures a StandardDecoupledTemplateLogicResolver by default (and the one you are configuring looks like it is configured wrong).  I was able to get your files to work by changing it to this:

```<code>final FileTemplateResolver templateResolverFile = new FileTemplateResolver();
templateResolverFile.setTemplateMode(TemplateMode.HTML);
templateResolverFile.setPrefix("src/main/resources/templates/html/");
templateResolverFile.setSuffix(".html");
templateResolverFile.setCacheTTLMs(1 * 60 * 60 * 1000l);
templateResolverFile.setCacheable(Boolean.TRUE);
templateResolverFile.setCharacterEncoding("UTF-8");
templateResolverFile.setCheckExistence(true);
templateResolverFile.setUseDecoupledLogic(true);
templateResolverFile.setCheckExistence(true);

final TemplateEngine templateEngine = new TemplateEngine();
templateEngine.setTemplateResolver(templateResolverFile);

final Context context01 = new Context();
context01.setVariable("products",ProductRepository.getInstance().findAll());

final BufferedWriter writer01=new BufferedWriter(new OutputStreamWriter(System.out));
templateEngine.process("LogicTemplate",context01,writer01);
</code>```

Also, you have some typos in your logic xml, it should look like this:

```<code><?xml version="1.0"?>
<thlogic>
    <attr sel="#ProductTable" th:remove="all-but-first">
        <attr sel="/tr[0]" th:each="prod : ${products}">
            <attr sel="td.Name" th:text="${prod.name}" />
            <attr sel="td.Price" th:text="${prod.price}" />
            <attr sel="td.InStock" th:text="${prod.inStock}" />
            <attr sel="td.Comments" th:text="${prod.comments != null and (not #lists.isEmpty(prod.comments)) ? #lists.size(prod.comments) : 0}" />
        </attr>
    </attr>
</thlogic>
</code>```

Body:
I want to try decoupled template logic using thymeleaf. This is mentioned here in  thymeleaf 3.0 documentation.

According to tutorial I have created my project here

My template & decoupled logic is present inside LogicTemplate.html & LogicTemplate.th.xml file.

Code Snippet For LogicTemplate.html is as follows:

<title>ThymeLeaf:Example03</title>

   Name
   Price
   In Stock
   Comments

   Ppap
   10
   Yes
   No Comments

 4. Code Snippet For LogicTemplate.th.xml is as follows:

<?xml version="1.0"?>
<thlogic>
  <attr sel="#ProductTable" th:remove="all-but-first">
    <attr sel="/tr[0]" th:each="prod : ${products}">
      <attr sel="td.Name" th:text="${prod.name}" />
      <attr sel="td.Price" th:text="${prod.price}" />
      <attr sel="td.InStock" th:text="${prod.inStock}" />
      <attr sel="td.Comments" th:text="${${prod.comments!=null and (not #lists.isEmpty(prod.comments))}?#lists.size(prod.comments):0}}" />
    </attr>
  </attr>
</thlogic>

  5. I have created following java class DeCoupledLogic,Code snippet shown below:
`

public class DeCoupledLogic {
        public static void main(String[] args) {
            final FileTemplateResolver templateResolverFile = new FileTemplateResolver();
            templateResolverFile.setTemplateMode(TemplateMode.HTML);
            templateResolverFile.setPrefix("src/main/resources/templates/html/");
            templateResolverFile.setSuffix(".html");
            templateResolverFile.setCacheTTLMs(1 * 60 * 60 * 1000l);
            templateResolverFile.setCacheable(Boolean.TRUE);
            templateResolverFile.setCharacterEncoding("UTF-8");
            templateResolverFile.setCheckExistence(true);
            templateResolverFile.setUseDecoupledLogic(true);
            templateResolverFile.setCheckExistence(true);

            final StandardDecoupledTemplateLogicResolver resolver=new StandardDecoupledTemplateLogicResolver();
            resolver.setPrefix("src/main/resources/templates/html/");

            final TemplateEngine templateEngine = new TemplateEngine();
            templateEngine.setTemplateResolver(templateResolverFile);
            templateEngine.setDecoupledTemplateLogicResolver(resolver);

            final Context context01 = new Context();
            context01.setVariable("products",ProductRepository.getInstance().findAll());

            final BufferedWriter writer01=new BufferedWriter(new OutputStreamWriter(System.out));
            templateEngine.process("LogicTemplate",context01,writer01);
        }
    }

`
But executing this code does not gives desired result.
Output Actual:

<title>ThymeLeaf:Example03</title>

   Name
   Price
   In Stock
   Comments

   Ppap
   10
   Yes
   No Comments

Output Expected:
Must not contain this static text but all product information.But I am unable to figure out where this code piece went wrong.Please Help me to identify potential error in my code.

Body:
Thymeleaf configures a StandardDecoupledTemplateLogicResolver by default (and the one you are configuring looks like it is configured wrong).  I was able to get your files to work by changing it to this:

final FileTemplateResolver templateResolverFile = new FileTemplateResolver();
templateResolverFile.setTemplateMode(TemplateMode.HTML);
templateResolverFile.setPrefix("src/main/resources/templates/html/");
templateResolverFile.setSuffix(".html");
templateResolverFile.setCacheTTLMs(1 * 60 * 60 * 1000l);
templateResolverFile.setCacheable(Boolean.TRUE);
templateResolverFile.setCharacterEncoding("UTF-8");
templateResolverFile.setCheckExistence(true);
templateResolverFile.setUseDecoupledLogic(true);
templateResolverFile.setCheckExistence(true);

final TemplateEngine templateEngine = new TemplateEngine();
templateEngine.setTemplateResolver(templateResolverFile);

final Context context01 = new Context();
context01.setVariable("products",ProductRepository.getInstance().findAll());

final BufferedWriter writer01=new BufferedWriter(new OutputStreamWriter(System.out));
templateEngine.process("LogicTemplate",context01,writer01);

Also, you have some typos in your logic xml, it should look like this:

<?xml version="1.0"?>
<thlogic>
    <attr sel="#ProductTable" th:remove="all-but-first">
        <attr sel="/tr[0]" th:each="prod : ${products}">
            <attr sel="td.Name" th:text="${prod.name}" />
            <attr sel="td.Price" th:text="${prod.price}" />
            <attr sel="td.InStock" th:text="${prod.inStock}" />
            <attr sel="td.Comments" th:text="${prod.comments != null and (not #lists.isEmpty(prod.comments)) ? #lists.size(prod.comments) : 0}" />
        </attr>
    </attr>
</thlogic>


问:
Hide contour rectangle of sprite
How can I hide the contour of my sprite?

I tried to change in Pipeline

```<code>"ColorKeyColor" :- 00FFFFFF (RGBA : 255, 255, 255, 0) -00000000  (RGBA : 0,0 ,0 ,0)

"ColorKeyEnabled" : True or False

"PremultiplyAlpha" : True or False
</code>```

I tried all possibilities because I don't understand the specifics of PremultiplyAlpha and the others, even after reading the documentation.

Some others have had the same problem which they can't solve : http://community.monogame.net/t/texture-alpha/

Edit: I partially understand what PremultipliedAlpha utility is and I understand it's not my problem, but I tried to change this value because I was desperate.

答:
Ah, I see what your problem is. You seem to want to get rid of the background. Well, why don't you do it outside of your code in the Texture in a tool like Gimp or Paint.Net (or Photoshop, if you own it).

You can set one or multiple colors to be transparent in a texture, by comparing every pixel and set its alpha value to 0 when the color matches. But this is not very useful, since you do not have a way to tell your game what color you want to use besides using a separate file.

Title: Hide contour rectangle of sprite

Body:
How can I hide the contour of my sprite?

I tried to change in Pipeline

"ColorKeyColor" :- 00FFFFFF (RGBA : 255, 255, 255, 0) -00000000  (RGBA : 0,0 ,0 ,0)

"ColorKeyEnabled" : True or False

"PremultiplyAlpha" : True or False

I tried all possibilities because I don't understand the specifics of PremultiplyAlpha and the others, even after reading the documentation.

Some others have had the same problem which they can't solve : http://community.monogame.net/t/texture-alpha/

Edit: I partially understand what PremultipliedAlpha utility is and I understand it's not my problem, but I tried to change this value because I was desperate.


问:
Can speech be added to a receipt card?
I am using the bot framework technology in one of my projects and the receipt card suits my needs perfectly. I wanted to know if it is possible to provide a speech text to the output displayed.</p>

答:
Since the receipt card is an attachment to a message, it doesn't have a property for speech.  However, you can set the .Speak property of the message itself.  Something like this:</p>

```<code>var message = context.MakeMessage();
message.Speak = "Here is your receipt.";

var attachment = GetReceiptCard();
message.Attachments.Add(attachment);

await context.PostAsync(message);
</code>```

Title: Can speech be added to a receipt card?

Body:
Since the receipt card is an attachment to a message, it doesn't have a property for speech.  However, you can set the .Speak property of the message itself.  Something like this:

var message = context.MakeMessage();
message.Speak = "Here is your receipt.";

var attachment = GetReceiptCard();
message.Attachments.Add(attachment);

await context.PostAsync(message);


问:
How to make chrome compatible with Jupyter for Anaconda?
I am an anaconda user and Jupyter is a neat tool to run python code. However, for my macbook, I can't open it in Chrome (This page isn’t working
localhost didn’t send any data.),but it works in Safari, I have tried to reinstall chrome, but I still can't fix it. My system is Mac OS 10.11.5.
Who knows how I can fix it?
I can understand that the problem might be not specific enough, but I have been puzzled by this problem for quite a period of time.</p>

答:
There was a similar problem in the git page for Jupyter:
https://github.com/jupyter/notebook/issues/2438

Try going to directly to http://localhost:8888/tree
or whatever port you are using.


问:
How to pass custom component parameters in java and xml
When creating a custom component in android it is often asked how to create and pass through the attrs property to the constructor.

It is often suggested that when creating a component in java that you simply use the default constructor, i.e.

```<code>new MyComponent(context);
</code>```

rather than attempting to create an attrs object to pass through to the overloaded constructor often seen in xml based custom components. I've tried to create an attrs object and it doesn't seem either easy or at all possible (without an exceedingly complicated process), and by all accounts isn't really required.

My question is then: What is the most efficient way of construction a custom component in java that passes or sets properties that would have otherwise been set by the attrs object when inflating a component using xml?

答:
(Full disclosure:  This question is an offshoot of Creating custom view)

You can create constructors beyond the three standard ones inherited from View that add the attributes you want...

```<code>MyComponent(Context context, String foo)
{
  super(context);
  // Do something with foo
}
</code>```

...but I don't recommend it.  It's better to follow the same convention as other components.  This will make your component as flexible as possible and will prevent developers using your component from tearing their hair out because yours is inconsistent with everything else:

1.  Provide getters and setters for each of the attributes:

```<code>public void setFoo(String new_foo) { ... }
public String getFoo() { ... }
</code>```

2.  Define the attributes in res/values/attrs.xml so they can be used in XML.

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
  <declare-styleable name="MyComponent">
    <attr name="foo" format="string" />
  </declare-styleable>
</resources>
</code>```

3.  Provide the three standard constructors from View.

If you need to pick anything out of the attributes in one of the constructors that takes an AttributeSet, you can do...

```<code>TypedArray arr = context.obtainStyledAttributes(attrs, R.styleable.MyComponent);
CharSequence foo_cs = arr.getString(R.styleable.MyComponent_foo);
if (foo_cs != null) {
  // Do something with foo_cs.toString()
}
arr.recycle();  // Do this when done.
</code>```

With all that done, you can instantiate MyCompnent programmatically...

```<code>MyComponent c = new MyComponent(context);
c.setFoo("Bar");
</code>```

...or via XML:

```<code><!-- res/layout/MyActivity.xml -->
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:blrfl="http://schemas.android.com/apk/res-auto"
  ...etc...
>
  <com.blrfl.MyComponent
   android:id="@+id/customid"
   android:layout_weight="1"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:layout_gravity="center"
   blrfl:foo="bar"
   blrfl:quux="bletch"
  />
</LinearLayout>
</code>```

Additional Resource - https://developer.android.com/training/custom-views/create-view

Body:
When creating a custom component in android it is often asked how to create and pass through the attrs property to the constructor.

It is often suggested that when creating a component in java that you simply use the default constructor, i.e.

new MyComponent(context);

rather than attempting to create an attrs object to pass through to the overloaded constructor often seen in xml based custom components. I've tried to create an attrs object and it doesn't seem either easy or at all possible (without an exceedingly complicated process), and by all accounts isn't really required.

My question is then: What is the most efficient way of construction a custom component in java that passes or sets properties that would have otherwise been set by the attrs object when inflating a component using xml?

Body:
(Full disclosure:  This question is an offshoot of Creating custom view)

You can create constructors beyond the three standard ones inherited from View that add the attributes you want...

MyComponent(Context context, String foo)
{
  super(context);
  // Do something with foo
}

...but I don't recommend it.  It's better to follow the same convention as other components.  This will make your component as flexible as possible and will prevent developers using your component from tearing their hair out because yours is inconsistent with everything else:

1.  Provide getters and setters for each of the attributes:

public void setFoo(String new_foo) { ... }
public String getFoo() { ... }

2.  Define the attributes in res/values/attrs.xml so they can be used in XML.

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <declare-styleable name="MyComponent">
    <attr name="foo" format="string" />
  </declare-styleable>
</resources>

3.  Provide the three standard constructors from View.

If you need to pick anything out of the attributes in one of the constructors that takes an AttributeSet, you can do...

TypedArray arr = context.obtainStyledAttributes(attrs, R.styleable.MyComponent);
CharSequence foo_cs = arr.getString(R.styleable.MyComponent_foo);
if (foo_cs != null) {
  // Do something with foo_cs.toString()
}
arr.recycle();  // Do this when done.

With all that done, you can instantiate MyCompnent programmatically...

MyComponent c = new MyComponent(context);
c.setFoo("Bar");

...or via XML:

<!-- res/layout/MyActivity.xml -->
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:blrfl="http://schemas.android.com/apk/res-auto"
  ...etc...
>
  <com.blrfl.MyComponent
   android:id="@+id/customid"
   android:layout_weight="1"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:layout_gravity="center"
   blrfl:foo="bar"
   blrfl:quux="bletch"
  />
</LinearLayout>

Additional Resource - https://developer.android.com/training/custom-views/create-view


问:
sqlalchemy error (sqlalchemy.exc.NoForeignKeysError)
I am playing with a toy example to see the back populates in action but hitting an error that I can't understand. Below I have two 'models' that back populate each other. When I try to create a User object it throws an error. What am I missing?

"sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship Child.user - there are no foreign keys linking these tables.  Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression."

```<code>  engine = create_engine('sqlite:///:memory:', echo=False)
  Session = sessionmaker(bind=engine)
  session = Session()
  Base = declarative_base(bind=engine)

  class User(Base):
    __tablename__ = 'user'
    user_id = Column("UserID", Integer, primary_key=True)
    name = Column("Name", String(50))
    age = Column("Age", SmallInteger)
    child = relationship("Child", back_populates="user")

  class Child(Base):
    __tablename__ = 'child'
    child_id = Column("ChildID", Integer, primary_key=True)
    school = Column("School", String)
    grade = Column("Grade", String)
    user_id = Column("UserID", Integer, ForeignKey('User.UserID'), index=True, nullable=True)
    user = relationship("User", back_populates="child")
</code>```

答:
ForeignKey requires the table and column name, not model and attribute name, so it should be:

```<code>user_id = Column("UserID", Integer, ForeignKey('user.UserID'), ...)
</code>```

because your User model has a table name of user.

Body:
I am playing with a toy example to see the back populates in action but hitting an error that I can't understand. Below I have two 'models' that back populate each other. When I try to create a User object it throws an error. What am I missing?

"sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship Child.user - there are no foreign keys linking these tables.  Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression."

  engine = create_engine('sqlite:///:memory:', echo=False)
  Session = sessionmaker(bind=engine)
  session = Session()
  Base = declarative_base(bind=engine)

  class User(Base):
    __tablename__ = 'user'
    user_id = Column("UserID", Integer, primary_key=True)
    name = Column("Name", String(50))
    age = Column("Age", SmallInteger)
    child = relationship("Child", back_populates="user")

  class Child(Base):
    __tablename__ = 'child'
    child_id = Column("ChildID", Integer, primary_key=True)
    school = Column("School", String)
    grade = Column("Grade", String)
    user_id = Column("UserID", Integer, ForeignKey('User.UserID'), index=True, nullable=True)
    user = relationship("User", back_populates="child")

Body:
ForeignKey requires the table and column name, not model and attribute name, so it should be:

user_id = Column("UserID", Integer, ForeignKey('user.UserID'), ...)

because your User model has a table name of user.


问:
Gradle DSL method not found:'android()'
Android studio shows possible causes:

The project may be using a version of Gradle that does not contain the method.
The build file may be missing a Gradle plugin.

```<code>apply plugin: 'com.google.gms.google-services'
android {
        compileSdkVersion 17
        buildToolsVersion '23.0.1'

        defaultConfig {
            applicationId "com.android.application"
            manifestPlaceholders = [manifestApplicationId: "${com.android.application}",
                                    onesignal_app_id:"3z281386-18df-4ae8-95fb-da47db595f27",
                                    onesignal_google_project_number:"570040958475"]
            minSdkVersion 22
            targetSdkVersion 22
            versionCode 1
            versionName "1.0"
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        } }

    dependencies {
        compile fileTree(include: ['*.jar'], dir: 'libs')
        compile 'com.android.support:appcompat-v7:22.2.1'
        compile 'com.google.android.gms:play-services:8.1.0'
        compile 'com.google.android.gms:play-services-ads:8.1.0'
        compile 'com.google.android.gms:play-services-identity:8.1.0'
        compile 'com.google.android.gms:play-services-gcm:8.1.0'
        compile 'com.onesignal:OneSignal:2.+@aar'
        compile 'com.google.android.gms:play-services-analytics:8.1.0'
        compile 'com.google.android.gms:play-services-location:8.1.0' }
</code>```

答:
You need to add

```<code>apply plugin: 'com.android.application'
</code>```

As the first line of the build.gradle

Title: Gradle DSL method not found:'android()'

Body:
Android studio shows possible causes:

The project may be using a version of Gradle that does not contain the method.
The build file may be missing a Gradle plugin.

apply plugin: 'com.google.gms.google-services'
android {
        compileSdkVersion 17
        buildToolsVersion '23.0.1'

        defaultConfig {
            applicationId "com.android.application"
            manifestPlaceholders = [manifestApplicationId: "${com.android.application}",
                                    onesignal_app_id:"3z281386-18df-4ae8-95fb-da47db595f27",
                                    onesignal_google_project_number:"570040958475"]
            minSdkVersion 22
            targetSdkVersion 22
            versionCode 1
            versionName "1.0"
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        } }

    dependencies {
        compile fileTree(include: ['*.jar'], dir: 'libs')
        compile 'com.android.support:appcompat-v7:22.2.1'
        compile 'com.google.android.gms:play-services:8.1.0'
        compile 'com.google.android.gms:play-services-ads:8.1.0'
        compile 'com.google.android.gms:play-services-identity:8.1.0'
        compile 'com.google.android.gms:play-services-gcm:8.1.0'
        compile 'com.onesignal:OneSignal:2.+@aar'
        compile 'com.google.android.gms:play-services-analytics:8.1.0'
        compile 'com.google.android.gms:play-services-location:8.1.0' }

Body:
You need to add

apply plugin: 'com.android.application'

As the first line of the build.gradle


问:
Multi-threading in MATLAB
I have read MATLAB's info on multi-threading and how it is in-built in certain functions.  However, my requirement is different.
Say, I have 3 functions: fun1(data1), fun2(data2), fun3(data3).... Can I implement multi-threading between these functions?  I actually have 300+ functions using a lot of data.  Multi-threading may help me cut down a lot of the time.  Please suggest a command or something which I can further research on.  Thanks!</p>

答:
If you want to run a batch of different functions on different processors, you can use the Parallel Computing Toolbox, more specifically, a parfor loop, but you need to pass the functions as a list of handles.

```<code>funList = {@fun1,@fun2,@fun3};
dataList = {data1,data2,data3}; %# or pass file names

matlabpool open

parfor i=1:length(funList)
    %# call the function
    funList{i}(dataList{i});
end
</code>```

Edit:
Starting with R2015a matlabpool function has been removed from Matlab, you need to call parpool instead.

Title: Multi-threading in MATLAB

Body:
If you want to run a batch of different functions on different processors, you can use the Parallel Computing Toolbox, more specifically, a parfor loop, but you need to pass the functions as a list of handles.

funList = {@fun1,@fun2,@fun3};
dataList = {data1,data2,data3}; %# or pass file names

matlabpool open

parfor i=1:length(funList)
    %# call the function
    funList{i}(dataList{i});
end

Edit:
Starting with R2015a matlabpool function has been removed from Matlab, you need to call parpool instead.


问:
Align center isn't working
I'm trying to align the text inside my div both horizontally and vertically, but it's only aligning horizontally. Everything I try doesn't work...
here's my css code:

```<code>#loading > h1 {
  text-align: center;
  font-size: 21px;
  animation: fadeUpIn 3s;
  -webkit-animation: fadeUpIn 3s; /* Safari and Chrome */
}

@-webkit-keyframes fadeUpIn /* Safari and Chrome */
{
  from { opacity:0; top:150px; }
  to { opacity:1; top: 70px; }
}
#loading{
  position: absolute; top: 0; left: 0;
  width:100%;
  height: 100%;
  background-color: gray;
  color: white;
  opacity: 1;
  transition: 1s;
  visibility: visible;
}
#loading.hidden{
  opacity: 0;
  visibility: hidden;
}
</code>```

My html code:

```<code><div id="loading">
<h1>Creative. Simple.</h1>
</div>
</code>```

JS fiddle of the whole website:
https://jsfiddle.net/sjyoqdqy/

答:
I'd suggest adding this CSS to #loading > h1:

```<code>#loading > h1 {
  position: absolute;
  top: 48%;
  left: 0;
  right: 0;
  margin: 0;
}
</code>```

Then update the animation position to be consistent:

```<code>@-webkit-keyframes fadeUpIn /* Safari and Chrome */
{
  from { opacity:0; top:58%; }
  to { opacity:1; top: 48%; }
}
</code>```

Fiddle for an example:
https://jsfiddle.net/sjyoqdqy/6/

Title: Align center isn't working

Body:
I'm trying to align the text inside my div both horizontally and vertically, but it's only aligning horizontally. Everything I try doesn't work...
here's my css code:

#loading > h1 {
  text-align: center;
  font-size: 21px;
  animation: fadeUpIn 3s;
  -webkit-animation: fadeUpIn 3s; /* Safari and Chrome */
}

@-webkit-keyframes fadeUpIn /* Safari and Chrome */
{
  from { opacity:0; top:150px; }
  to { opacity:1; top: 70px; }
}
#loading{
  position: absolute; top: 0; left: 0;
  width:100%;
  height: 100%;
  background-color: gray;
  color: white;
  opacity: 1;
  transition: 1s;
  visibility: visible;
}
#loading.hidden{
  opacity: 0;
  visibility: hidden;
}

My html code:

Creative. Simple.

JS fiddle of the whole website:
https://jsfiddle.net/sjyoqdqy/

Body:
I'd suggest adding this CSS to #loading > h1:

#loading > h1 {
  position: absolute;
  top: 48%;
  left: 0;
  right: 0;
  margin: 0;
}

Then update the animation position to be consistent:

@-webkit-keyframes fadeUpIn /* Safari and Chrome */
{
  from { opacity:0; top:58%; }
  to { opacity:1; top: 48%; }
}

Fiddle for an example:
https://jsfiddle.net/sjyoqdqy/6/


问:
Mesh editing via SceneKit
This is my first post here. Hope I won't make any mistake...

I'm actually trying to manipulate a STL mesh file inside a SCNView through the model I/O framework.

I can't find any documentation or tutorial about mesh editing (cutting, cropping,...) directly via the SCNView. Most of the comments I have seen resolve this by using an external mesh editor (Blender, Meshmixer,...).

Do you know if there any tools or a way to allow mesh editing directly through the app?

Thanks for your help.

答: There is not. You'll have to implement all of the functionality you need yourself.</p>

Title: Mesh editing via SceneKit


问:
Poor TextBox performance with wrapping on and large amounts of data
I have a persistent problem with textboxes in WPF, using .NET 3.5. With a large (5000+ lines) amount of data in a TextBox with wrapping enabled, the window has ridiculously bad performance while being resized.

This only happens with TextWrapping="Wrap". Having the text data bound or just setting it programmatically makes no difference.

The code is literally as simple as this:

```<code><TextBox Margin="12,39,337,29" Text="{Binding Output, Mode=OneWay}" TextWrapping="Wrap" VerticalScrollBarVisibility="Visible" HorizontalScrollBarVisibility="Disabled" />
</code>```

The text is bound to a single string. The bound data is not being changed.

Edit: The data is not being changed while the window is resizing, is what I meant. It will be updated in the future. The TextBox does not need to be editable, but the actual text does need to be selectable. /Edit.

I've had a quick play with AvalonEdit, which has the same problem. It seems strange that I can't find any other threads which describe this issue.

Any advice?

Thanks,
Rich

答:
The part that is slow is displaying all that text at once. I have run into this issue before where the TextBox in my control became very large and had a ScrollViewer for the whole control that would handle the very large TextBox.

You are almost doing that, but without setting a max for your height/width, I'm not sure if your ScrollViewer is actually going to be utilized.

My solution is to use the built-in scrollViewer inside of your TextBox(which you are doing), and then limit the size of the textbox height/width so that it isn't trying to render 100% of the text all at once (and actually utilizes the ScrollViewer inside your TextBox)

(FYI, I also like using CanContentScroll=true, though I don't think it will affect the speed)

```<code><TextBox Margin="12,39,337,29" TextWrapping="Wrap"
         Text="{Binding Output, Mode=OneWay}"
         ScrollViewer.CanContentScroll="true"
         VerticalScrollBarVisibility="auto"
         HorizontalScrollBarVisibility="auto"
         MaxHeight="600" MaxWidth="600"/>
</code>```

Body:
I have a persistent problem with textboxes in WPF, using .NET 3.5. With a large (5000+ lines) amount of data in a TextBox with wrapping enabled, the window has ridiculously bad performance while being resized.

This only happens with TextWrapping="Wrap". Having the text data bound or just setting it programmatically makes no difference.

The code is literally as simple as this:

<TextBox Margin="12,39,337,29" Text="{Binding Output, Mode=OneWay}" TextWrapping="Wrap" VerticalScrollBarVisibility="Visible" HorizontalScrollBarVisibility="Disabled" />

The text is bound to a single string. The bound data is not being changed.

Edit: The data is not being changed while the window is resizing, is what I meant. It will be updated in the future. The TextBox does not need to be editable, but the actual text does need to be selectable. /Edit.

I've had a quick play with AvalonEdit, which has the same problem. It seems strange that I can't find any other threads which describe this issue.

Any advice?

Thanks,
Rich

Body:
The part that is slow is displaying all that text at once. I have run into this issue before where the TextBox in my control became very large and had a ScrollViewer for the whole control that would handle the very large TextBox.

You are almost doing that, but without setting a max for your height/width, I'm not sure if your ScrollViewer is actually going to be utilized.

My solution is to use the built-in scrollViewer inside of your TextBox(which you are doing), and then limit the size of the textbox height/width so that it isn't trying to render 100% of the text all at once (and actually utilizes the ScrollViewer inside your TextBox)

(FYI, I also like using CanContentScroll=true, though I don't think it will affect the speed)

<TextBox Margin="12,39,337,29" TextWrapping="Wrap"
         Text="{Binding Output, Mode=OneWay}"
         ScrollViewer.CanContentScroll="true"
         VerticalScrollBarVisibility="auto"
         HorizontalScrollBarVisibility="auto"
         MaxHeight="600" MaxWidth="600"/>


问:
Swift: UIScrollView won't work with constraints at all?
I'm trying to use a UIScrollView on my view as the content that I want to show won't fit on the screen. I work purely programmatically and cannot seem to grasp why my UIScrollView simply will not work when adding constraints. It works perfectly with frames but I that's the awkward, old way of doing things. I want to be able to add views to the scroll view and of course scroll down as it goes off screen. I have tried to add a topView as one of the views I want to be able to add and scroll with the scrollview but no joy. Where am I going wrong? Any help will be highly appreciated.

```<code>class ScrollTest: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .white

        setupviews()
    }

    let topView: UIView = {
        let view = UIView()
        view.backgroundColor = .yellow
        return view
    }()

    let containerView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()

    let scrollView: UIScrollView = {
        let sv = UIScrollView()
        sv.backgroundColor = .white
        sv.translatesAutoresizingMaskIntoConstraints = false
        return sv
    }()

    func setupviews() {
        view.addSubview(scrollView)
        scrollView.addSubview(containerView)

        containerView.addSubview(topView)

        scrollView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        scrollView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        scrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
//
        _ = containerView.anchor(scrollView.topAnchor, left: scrollView.leftAnchor, bottom: scrollView.bottomAnchor, right: scrollView.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 700)

        _ = topView.anchor(view.topAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, topConstant: 100, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 50)
    }
}
</code>```

答:
Couple of things. First, your containerView is missing translatesAutoresizingMaskIntoConstraints = false. Second, mostly, an UI objects needs four constraints to be valid. So you are missing some of them for your container view.

Here is a complete working code

```<code>let scrollView: UIScrollView = {
    let sv = UIScrollView()
    sv.backgroundColor = .red
    sv.translatesAutoresizingMaskIntoConstraints = false
    return sv
}()

let containerView: UIView = {
    let view = UIView()
    view.backgroundColor = .white
    view.translatesAutoresizingMaskIntoConstraints = false
    return view
}()

override func viewDidLoad() {
    super.viewDidLoad()

    view.addSubview(scrollView)

    scrollView.contentSize = CGSize(width: 320, height: 1500)

    scrollView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
    scrollView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
    scrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
    scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true

    scrollView.addSubview(containerView)

    containerView.leftAnchor.constraint(equalTo: scrollView.leftAnchor).isActive = true
    containerView.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
    containerView.widthAnchor.constraint(equalToConstant: 200).isActive = true
    containerView.heightAnchor.constraint(equalToConstant: 100).isActive = true

}
</code>```

Results is like

Body:
I'm trying to use a UIScrollView on my view as the content that I want to show won't fit on the screen. I work purely programmatically and cannot seem to grasp why my UIScrollView simply will not work when adding constraints. It works perfectly with frames but I that's the awkward, old way of doing things. I want to be able to add views to the scroll view and of course scroll down as it goes off screen. I have tried to add a topView as one of the views I want to be able to add and scroll with the scrollview but no joy. Where am I going wrong? Any help will be highly appreciated.

class ScrollTest: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .white

        setupviews()
    }

    let topView: UIView = {
        let view = UIView()
        view.backgroundColor = .yellow
        return view
    }()

    let containerView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()

    let scrollView: UIScrollView = {
        let sv = UIScrollView()
        sv.backgroundColor = .white
        sv.translatesAutoresizingMaskIntoConstraints = false
        return sv
    }()

    func setupviews() {
        view.addSubview(scrollView)
        scrollView.addSubview(containerView)

        containerView.addSubview(topView)

        scrollView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        scrollView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        scrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
//
        _ = containerView.anchor(scrollView.topAnchor, left: scrollView.leftAnchor, bottom: scrollView.bottomAnchor, right: scrollView.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 700)

        _ = topView.anchor(view.topAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, topConstant: 100, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 50)
    }
}

Body:
Couple of things. First, your containerView is missing translatesAutoresizingMaskIntoConstraints = false. Second, mostly, an UI objects needs four constraints to be valid. So you are missing some of them for your container view.

Here is a complete working code

let scrollView: UIScrollView = {
    let sv = UIScrollView()
    sv.backgroundColor = .red
    sv.translatesAutoresizingMaskIntoConstraints = false
    return sv
}()

let containerView: UIView = {
    let view = UIView()
    view.backgroundColor = .white
    view.translatesAutoresizingMaskIntoConstraints = false
    return view
}()

override func viewDidLoad() {
    super.viewDidLoad()

    view.addSubview(scrollView)

    scrollView.contentSize = CGSize(width: 320, height: 1500)

    scrollView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
    scrollView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
    scrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
    scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true

    scrollView.addSubview(containerView)

    containerView.leftAnchor.constraint(equalTo: scrollView.leftAnchor).isActive = true
    containerView.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
    containerView.widthAnchor.constraint(equalToConstant: 200).isActive = true
    containerView.heightAnchor.constraint(equalToConstant: 100).isActive = true

}

Results is like


问:
SSMS New query tab not showing spid
My SSMS;

Other SSMS;

Not showing spid and not showing execute query.

Tool>Options>Editor Tab and Status Bar> All True

Thank you advance.

答:
In SSMS 2017, they moved the SPID location down to the bottom right hand side of the query window.

There it shows: Server (Version) | User(spid) | Database | Elapsed Time | Rows Returned

Title: SSMS New query tab not showing spid


问:
Uncaught TypeError: d3.select(...).selectAll(...).data(...).enter(...).append(...).atrr is not a function
I am having the subject error while plotting D3 graph. The data is getting loaded correctly because when I do console.log I can see the array.

Javascript:

```<code>d3.csv("../../shot_logs.csv", function (data) {

    var shots = d3.select("svg")
        .selectAll("g")
        .data(data)
        .enter()
        .append("g")
            .atrr("class", "shot")
            .attr("transform", function (d) {
                    return "translate(" + d.x_coodinates + "," + d.y_coordinates + ")";
    });
    shots.append("circle")
        .attr("r", 5);

});
</code>```

HTML:

```<code><!DOCTYPE html>
<html lang="en-US">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="style-main.css" type="text/css" media="all">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://d3js.org/d3.v4.min.js"></script>
</head>

<body>
    <h1>D3 Charts</h1>
    <select id="selector"></select>
    <svg id="canvas" height="600px" width="1200px"></svg>

    <script src="JS/script.js"></script>
</body>

</html>
</code>```

答:
Looks like a simple typo :)

Change

```<code>.atrr("class", "shot")
</code>```

to

```<code>.attr("class", "shot")
</code>```

Body:
I am having the subject error while plotting D3 graph. The data is getting loaded correctly because when I do console.log I can see the array.

Javascript:

d3.csv("../../shot_logs.csv", function (data) {

    var shots = d3.select("svg")
        .selectAll("g")
        .data(data)
        .enter()
        .append("g")
            .atrr("class", "shot")
            .attr("transform", function (d) {
                    return "translate(" + d.x_coodinates + "," + d.y_coordinates + ")";
    });
    shots.append("circle")
        .attr("r", 5);

});

HTML:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="style-main.css" type="text/css" media="all">

D3 Charts

    <select id="selector"></select>
    <svg id="canvas" height="600px" width="1200px"></svg>

Body:
Looks like a simple typo :)

Change

.atrr("class", "shot")

to

.attr("class", "shot")


问:
How to set fixed number of elements of array in Ruby
How to set fixed number of elements of an array in Ruby.

eg. a=["a","b","c","d"]
Setting array size to 3 would output

```<code>a=["a","b","cd"]
</code>```

答:
```<code>class Array
  def squeeze(n, &p)
    p = Proc.new {|xs| xs.join} unless p
    arr = self[0..n-2]
    arr << p.call(self[n-1..-1])
  end
end

a = ['a', 'b', 'c', 'd', 'e']
a.squeeze(3) # => ["a", "b", "cde"]
</code>```

It needs bounds checking but you get the idea.  Note that the "combining" function can be given as a block argument:

```<code>[1, 2, 3, 4].squeeze(3) {|xs| xs.inject {|acc,x| acc+x}} # => [1, 2, 7]
</code>```

Body:
How to set fixed number of elements of an array in Ruby.

eg. a=["a","b","c","d"]
Setting array size to 3 would output

a=["a","b","cd"]

Body:
class Array
  def squeeze(n, &p)
    p = Proc.new {|xs| xs.join} unless p
    arr = self[0..n-2]
    arr << p.call(self[n-1..-1])
  end
end

a = ['a', 'b', 'c', 'd', 'e']
a.squeeze(3) # => ["a", "b", "cde"]

It needs bounds checking but you get the idea.  Note that the "combining" function can be given as a block argument:

[1, 2, 3, 4].squeeze(3) {|xs| xs.inject {|acc,x| acc+x}} # => [1, 2, 7]


问:
Cocoa app: how to close a window without terminating the app?
I am working on a Cocoa app, using Swift. The app opens with a window and the user can open another window using the menu. The problem is that when either window is closed using the red button, the app terminates. I don't want that behavior; I want the app to remain alive. It's not crashing; the AppDelegate's applicationWillTerminate method executes.

The AppDelegate has the method applicationShouldTerminateAfterLastWindowClosed, which returns false, but this method never gets executed.

I am a reasonably competent Swift iOS developer; this is my first real Cocoa app and I suspect this is something simple, but I'm baffled right now. How do I close a window without terminating the app entirely?

Edit: Here are some code snippets:

In the AppDelegate:

```<code>func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
    Log.methodEnter()
    return false
}
</code>```

Also in the AppDelegate, the method to open a window:

```<code>@IBAction func openVerbSettingsWindow(sender: NSMenuItem) {
    verbSettingsWindowController.showWindow (nil)

}
</code>```

From the windowViewController, the only method that does anything as the window loads and displays:

```<code>override func windowDidLoad() {
    super.windowDidLoad()
    window?.setFrame(NSMakeRect(400.0, 100.0, 950.0, 450.0), display: true)
}
</code>```

I'm hopeful this helps!

答:
I'm not a little embarrassed at the answer to this question; it has nothing to do with Cocoa or my code.

I have an app called RedQuits that configures OS X to close an app when that app's last window closes, rather than leaving the app running with no windows (OS X default behavior). When I got rid of RedQuits and re-booted so that OS X would return to its default behavior, the problem went away. For some reason, RedQuits causes my Cocoa app to quit when any application window closes. Interestingly, I found this because it causes the same behavior in Xcode: close one project window and Xcode shut down.

Body:
I am working on a Cocoa app, using Swift. The app opens with a window and the user can open another window using the menu. The problem is that when either window is closed using the red button, the app terminates. I don't want that behavior; I want the app to remain alive. It's not crashing; the AppDelegate's applicationWillTerminate method executes.

The AppDelegate has the method applicationShouldTerminateAfterLastWindowClosed, which returns false, but this method never gets executed.

I am a reasonably competent Swift iOS developer; this is my first real Cocoa app and I suspect this is something simple, but I'm baffled right now. How do I close a window without terminating the app entirely?

Edit: Here are some code snippets:

In the AppDelegate:

func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
    Log.methodEnter()
    return false
}

Also in the AppDelegate, the method to open a window:

@IBAction func openVerbSettingsWindow(sender: NSMenuItem) {
    verbSettingsWindowController.showWindow (nil)

}

From the windowViewController, the only method that does anything as the window loads and displays:

override func windowDidLoad() {
    super.windowDidLoad()
    window?.setFrame(NSMakeRect(400.0, 100.0, 950.0, 450.0), display: true)
}

I'm hopeful this helps!


问:
Libssh2 - libssh2_scp_recv2 function
Can someone explain me the libssh2_scp_recv2() function from libssh2 lib?

According to this I need to input the session var (LIBSSH2_SESSION *session), the path to the file I want (const char *path) and a struct with information of the file I want (struct_stat *sb).

Where is the part I receive the data from that file? Because what return is a pointer to the channel.

答:
I found the answer!
This function is only to make a request to that session and them it's just read it like a ssh output using the libssh2_channel_read() function.

Title: Libssh2 - libssh2_scp_recv2 function


问:
Dynamic href tag React in JSX
```<code>// This Javascript <a> tag generates correctly
React.createElement('a', {href:"mailto:"+this.props.email}, this.props.email)
</code>```

However, I'm struggling to recreate it in JSX

```<code><a href="mailto: {this.props.email}">{this.props.email}</a>

// => <a href="mailto: {this.props.email}"></a>
</code>```

The href tag thinks the {this.props.email} is a string instead of dynamically inputting the value of {this.props.email}. Any ideas on where I went amiss?

答:
A slightly more ES6 way to do what Patrick is suggesting would be to use a template literal:

email

Title: Dynamic href tag React in JSX

Body:
// This Javascript  tag generates correctly
React.createElement('a', {href:"mailto:"+this.props.email}, this.props.email)

However, I'm struggling to recreate it in JSX

{this.props.email}

// =>

The href tag thinks the {this.props.email} is a string instead of dynamically inputting the value of {this.props.email}. Any ideas on where I went amiss?

Body:
A slightly more ES6 way to do what Patrick is suggesting would be to use a template literal:

<a href={`mailto:${this.props.email}`}>email</a>


问:
add shinyBS popover on disabled button
I haven't found any information in documentation of shinyBS and on the google/SO about how to use trigger = 'manual' on, for example, addPopover of shinyBS. I thought this would be the way to add a tooltip to a disabled button. (I dont want to do it with div'ving the button and giving title to div.
Also would be nice if someone has a way to add tooltips reactively to shiny apps

答:
If you want to use trigger = manual on the popover, then you need to define a script to toggle the popover, e.g. with jQuery:

```<code>library(shiny)
library(shinyjs)
library(shinyBS)

ui <-shinyUI(fluidPage(useShinyjs(),
                       # press this button to trigger the popover
                       actionButton("addPopover", "Add Popover"),

                       # a disabled button
                       disabled(actionButton("disabledButton", "This button is disabled")),

                       # the popover to appear over the disabled button
                       bsPopover("disabledButton", "Popover", "Some text", trigger="manual"),

                       # the script to trigger the popover
                       uiOutput("trigger")))

server <- shinyServer(function(input,output, session){

  # on checkbox selection, disable button and trigger the popover
  output$trigger <- renderUI({
    input$addPopover
    tags$script("$('#disabledButton').popover('toggle');")
  })
})

shinyApp(ui,server)
</code>```

Title: add shinyBS popover on disabled button

Body:
If you want to use trigger = manual on the popover, then you need to define a script to toggle the popover, e.g. with jQuery:

library(shiny)
library(shinyjs)
library(shinyBS)

ui <-shinyUI(fluidPage(useShinyjs(),
                       # press this button to trigger the popover
                       actionButton("addPopover", "Add Popover"),

                       # a disabled button
                       disabled(actionButton("disabledButton", "This button is disabled")),

                       # the popover to appear over the disabled button
                       bsPopover("disabledButton", "Popover", "Some text", trigger="manual"),

                       # the script to trigger the popover
                       uiOutput("trigger")))

server <- shinyServer(function(input,output, session){

  # on checkbox selection, disable button and trigger the popover
  output$trigger <- renderUI({
    input$addPopover
    tags$script("$('#disabledButton').popover('toggle');")
  })
})

shinyApp(ui,server)


问:
implementing Invisible Google reCaptcha for asp.net application ?
This is my ASP.NET form. I want to add invisible recaptcha to it with server side validation. Can someone please help?

I can do client side validation but it doesnt use secret key. My another questions is Do we need secret key for invisible recaptcha?

Please see serverside code that i used for google recaptcha but it is not working for Invisible recaptcha. I am getting this error : -
reCAPTCHA Error: missing-input-response: Not Valid Recaptcha

```<code><div id="ContactFormDiv" runat="server">
    <div class="form-row form-required">
        <asp:Label ID="YourNameLabel" runat="server" AssociatedControlID="YourNameTextBox"> Your Name:</asp:Label>
        <asp:TextBox ID="YourNameTextBox" runat="server" CssClass="form300" MaxLength="150"></asp:TextBox>
    </div>
    <div class="form-row form-required">
            <div id='recaptcha' class="g-recaptcha"
                data-sitekey="site key"
                data-callback="onSubmit"
                data-size="invisible">
            </div>
    </div>
    <div class="form-row-buttons">
        <asp:Button ID="SendMessageButton" ClientIDMode="Static" runat="server" Text="Send Message" CssClass="buttonPositive"
            CausesValidation="True" OnClick="SendMessageButton_Click" />
    </div>
</div>
</code>```

Javascript Code

```<code> <script type="text/javascript" src="https://www.google.com/recaptcha/api.js" async defer></script>
</code>```

Serverside Code

```<code>  public class MyObject
{
    public string success { get; set; }
}

public static string ReCaptcha_Key = "------------------Site Key-----------------";
public static string ReCaptcha_Secret = "--------------Secret Key ---------------";

 public bool ValidateReCaptcha()
{
    bool Valid = false;
    //start building recaptch api call
    var sb = new StringBuilder();

    //Getting Response String Append to Post Method
    string Response = Request["g-recaptcha-response"];

    string url = "https://www.google.com/recaptcha/api/siteverify?secret=" + ReCaptcha_Secret + "&response=" + Response;
    sb.Append(url);

    //make the api call and determine validity
    using (var client = new WebClient())
    {
        var uri = sb.ToString();
        var json = client.DownloadString(uri);
        var serializer = new DataContractJsonSerializer(typeof(RecaptchaApiResponse));
        var ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
        var result = serializer.ReadObject(ms) as RecaptchaApiResponse;

        //--- Check if we are able to call api or not.
        if (result == null)
        {
            lblmsg.Text = "Captcha was unable to make the api call";
        }
        else // If Yes
        {
            //api call contains errors
            if (result.ErrorCodes != null)
            {
                if (result.ErrorCodes.Count > 0)
                {
                    foreach (var error in result.ErrorCodes)
                    {
                        lblmsg.Text = "reCAPTCHA Error: " + error;
                    }
                }
            }
            else //api does not contain errors
            {
                if (!result.Success) //captcha was unsuccessful for some reason
                {
                    lblmsg.Text = "Captcha did not pass, please try again.";
                }
                else //---- If successfully verified. Do your rest of logic.
                {
                    lblmsg.Text = "Captcha cleared ";
                    Valid = true;
                }
            }
        }
    }
    return Valid;
}

public bool temp = true;
protected void SendMessageButton_Click(object sender, EventArgs e)
{
    temp = ValidateReCaptcha();
    if (temp == false)
    {
        lblmsg.Text = "Not Valid Recaptcha";
        lblmsg.ForeColor = System.Drawing.Color.Red;
    }
    else
    {
        lblmsg.Text = "Successful";
        lblmsg.ForeColor = System.Drawing.Color.Green;
    }

    Page.Validate();

    if (this.Page.IsValid == true && temp == true)
    { //Page and invisible recaptcha is valid  }
 }
</code>```

I am getting this error : -
reCAPTCHA Error: missing-input-response: Not Valid Recaptcha

答:
I also have similar problem and it looks like it is harder to find any decent example. However, I saw that you have set
    data-callback="onSubmit"
but I didn't see where you have defined that method. Is it there? Could that be what are you missing?</p>

Body:
This is my ASP.NET form. I want to add invisible recaptcha to it with server side validation. Can someone please help?

I can do client side validation but it doesnt use secret key. My another questions is Do we need secret key for invisible recaptcha?

Please see serverside code that i used for google recaptcha but it is not working for Invisible recaptcha. I am getting this error : -
reCAPTCHA Error: missing-input-response: Not Valid Recaptcha

        <asp:Label ID="YourNameLabel" runat="server" AssociatedControlID="YourNameTextBox"> Your Name:</asp:Label>
        <asp:TextBox ID="YourNameTextBox" runat="server" CssClass="form300" MaxLength="150"></asp:TextBox>

        <asp:Button ID="SendMessageButton" ClientIDMode="Static" runat="server" Text="Send Message" CssClass="buttonPositive"
            CausesValidation="True" OnClick="SendMessageButton_Click" />

Javascript Code

Serverside Code

  public class MyObject
{
    public string success { get; set; }
}

public static string ReCaptcha_Key = "------------------Site Key-----------------";
public static string ReCaptcha_Secret = "--------------Secret Key ---------------";

 public bool ValidateReCaptcha()
{
    bool Valid = false;
    //start building recaptch api call
    var sb = new StringBuilder();

    //Getting Response String Append to Post Method
    string Response = Request["g-recaptcha-response"];

    string url = "https://www.google.com/recaptcha/api/siteverify?secret=" + ReCaptcha_Secret + "&response=" + Response;
    sb.Append(url);

    //make the api call and determine validity
    using (var client = new WebClient())
    {
        var uri = sb.ToString();
        var json = client.DownloadString(uri);
        var serializer = new DataContractJsonSerializer(typeof(RecaptchaApiResponse));
        var ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
        var result = serializer.ReadObject(ms) as RecaptchaApiResponse;

        //--- Check if we are able to call api or not.
        if (result == null)
        {
            lblmsg.Text = "Captcha was unable to make the api call";
        }
        else // If Yes
        {
            //api call contains errors
            if (result.ErrorCodes != null)
            {
                if (result.ErrorCodes.Count > 0)
                {
                    foreach (var error in result.ErrorCodes)
                    {
                        lblmsg.Text = "reCAPTCHA Error: " + error;
                    }
                }
            }
            else //api does not contain errors
            {
                if (!result.Success) //captcha was unsuccessful for some reason
                {
                    lblmsg.Text = "Captcha did not pass, please try again.";
                }
                else //---- If successfully verified. Do your rest of logic.
                {
                    lblmsg.Text = "Captcha cleared ";
                    Valid = true;
                }
            }
        }
    }
    return Valid;
}

public bool temp = true;
protected void SendMessageButton_Click(object sender, EventArgs e)
{
    temp = ValidateReCaptcha();
    if (temp == false)
    {
        lblmsg.Text = "Not Valid Recaptcha";
        lblmsg.ForeColor = System.Drawing.Color.Red;
    }
    else
    {
        lblmsg.Text = "Successful";
        lblmsg.ForeColor = System.Drawing.Color.Green;
    }

    Page.Validate();

    if (this.Page.IsValid == true && temp == true)
    { //Page and invisible recaptcha is valid  }
 }

I am getting this error : -
reCAPTCHA Error: missing-input-response: Not Valid Recaptcha


问:
showing structure view for python files using jedi-vim
Does jedi vim support anything like intellijs https://www.jetbrains.com/help/idea/structure-tool-window-file-structure-popup.html ? </p>

答: Found majutsushi/tagbar which does this pretty well actually. This video explains how it works with ruby too.</p>


问:
How to map assosiative array in React/ES6? Starts an infinite loop
The array is generated following way:

```<code>for(var i = start; i <= end;i+=step) {
    arr[i] = i + 'is the number';
}
</code>```

Array structure looks like this

```<code>arr = [
1100: "1100 is the number",
1101: "1101 is the number",
1102: "1102 is the number",
1103: "1103 is the number",
1104: "1104 is the number",
1105: "1105 is the number",
];
</code>```

and so on.

This array will be mapped into a list element in React.

```<code>render() {
    const list = this.arr;
    const timeList = list.map((element) =>
        <li>{element}</li>
        );

    return (
      <div className="App" >
        {timeList}
      </div>
    );
</code>```

It works fine with the regular arrays, but using this one gives me an infinite loop.

Why is this happening and what are the possibilities to solve this ?

Thank you

UPDATE:
Found out that
"If you use named indexes, JavaScript will redefine the array to a standard object.
After that, some array methods and properties will produce incorrect results."

But still no solution to the problem

答:
Might be the i <= end? have you tried start.length, etc etc.

another solution is try switch to map() function.

Please let me know.

Body:
The array is generated following way:

for(var i = start; i <= end;i+=step) {
    arr[i] = i + 'is the number';
}

Array structure looks like this

arr = [
1100: "1100 is the number",
1101: "1101 is the number",
1102: "1102 is the number",
1103: "1103 is the number",
1104: "1104 is the number",
1105: "1105 is the number",
];

and so on.

This array will be mapped into a list element in React.

render() {
    const list = this.arr;
    const timeList = list.map((element) =>

{element}

        );

    return (

        {timeList}

    );

It works fine with the regular arrays, but using this one gives me an infinite loop.

Why is this happening and what are the possibilities to solve this ?

Thank you

UPDATE:
Found out that
"If you use named indexes, JavaScript will redefine the array to a standard object.
After that, some array methods and properties will produce incorrect results."

But still no solution to the problem


问:
Stretch and scale CSS background
Is there a way to get a background in CSS to stretch or scale to fill its container?</p>

答:
For modern browsers, you can accomplish this by using background-size:

body {
    background-image: url(bg.jpg);
    background-size: cover;
}
```

<p><code>cover</code> means stretching the image either vertically or horizontally so it never tiles/repeats.</p>

<p>That would work for Safari 3 (or later), Chrome, Opera 10+, Firefox 3.6+, and Internet Explorer 9 (or later).</p>

<p>For it to work with lower verions of Internet Explorer, try these CSS:</p>

```filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.myBackground.jpg', sizingMethod='scale');
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='myBackground.jpg', sizingMethod='scale')";
```

OwnerDisplayName: Software Monkey

Title: Stretch and scale CSS background

LastEditorDisplayName: Diodeus

Body:
For modern browsers, you can accomplish this by using background-size:

body {
    background-image: url(bg.jpg);
    background-size: cover;
}

cover means stretching the image either vertically or horizontally so it never tiles/repeats.

That would work for Safari 3 (or later), Chrome, Opera 10+, Firefox 3.6+, and Internet Explorer 9 (or later).

For it to work with lower verions of Internet Explorer, try these CSS:

filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.myBackground.jpg', sizingMethod='scale');
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='myBackground.jpg', sizingMethod='scale')";


问:
endeca property value in lowercase
I have to store value in one Endeca property but in lowercase. Values can be in uppercase or in lowercase in the source file but I have to store it in lowercase in the Endeca property.

Any pointer on how I can proceed will be helpful.

Thanks
Neha

答:
This can be achieved either adding Java manipulator or Pearl Manipulator in the Endeca pipeline and put the code to convert the value from any case to lower case.

I hope this helps.

Thanks,
Ajay Agrawal

Title: endeca property value in lowercase