问:
(S)CSS architecture: alternative backgrounds styling
I'm using 'component' approach to CSS as in SMACSS / ITCSS, I'm still scratching my head about styling sections with alternative (dark) background.

e.g. Stripe has regular (dark text on white) and alternative (white text on dark) sections.

As I understand there are options assuming HTML:

```<code><section class="dark">
    <h2>Title</h2>
    <p>Text</p>
    <a href="#" class="btn">Action</a>
</section>
</code>```

Style in context of section, e.g.:

```<code>.dark h2, .dark p, .dark btn {
  color: white;
}
</code>```

But a) context styling is not recommended; b) where does one put the styles? (Harry Roberts argues that in component's file)

Create alternative-colored components with modifiers

And change the HTML, e.g.:

```<code>.title--alt-color {color: white;}
.text--alt-color {color: white; }
...
</code>```

But a) it doesn't work when you don't know which components will go in there; b) more work of managing HTML.

Maybe there is a better way to handle this?

答:
What you're asking for is essentially to style a component within a section based on the section itself. Unfortunately this is impossible with CSS, as there is no parent selector in CSS. However, there is the inherit value, which allows you to style a component based on the rules defined by its parent - perfect for component-driven CSS.

In my opinion, the best way you can go about alternating background styling is to make use of the :nth-of-type pseudo-class on
:

section:nth-of-type(2n) {
  background: #464646;
  color: #fff;
}  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section>
    <h2>Title</h2>
    <p>Text</p>
    Action
</section>
<section>
    <h2>Title</h2>
    <p>Text</p>
    Action
</section>
<section>
    <h2>Title</h2>
    <p>Text</p>
    Action
</section>
<section>
    <h2>Title</h2>
    <p>Text</p>
    Action
</section></code>```

Considering :nth-of-type makes use of math to target elements, you can access literally any combination of elements you would like:

```<code>// Style every second element, starting with the first element
section:nth-of-type(2n - 1)

// Style every third element, starting with the second element (2, 5, 8, etc.)
section:nth-of-type(3n + 2)
</code>```

This way, it won't matter whether you're using a component-driven approach or not, as you'll be able to alternate the styling directly off of
 itself.

Elements that inherit an attribute from internal stylesheets (such as  tag colour) will unfortunately still be styled based on the internal stylesheet, rather than rules defined by their parent.

You can get around this by either using context-styling:

section:nth-of-type(n) {
  background: #464646;
  color: #fff;
}

section:nth-of-type(n) a {
  color: #fff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section>
    <h2>Title</h2>
    <p>Text</p>
    Action
</section></code>```

Or alternatively (and preferably) making use of the inherit value to tell every  tag to inherit its color from its parent:

section {
  background: #464646;
  color: #fff;
}
a {
  color: inherit;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section>
    <h2>Title</h2>
    <p>Text</p>
    Action
</section></code>```

Hope this helps!

Body:
I'm using 'component' approach to CSS as in SMACSS / ITCSS, I'm still scratching my head about styling sections with alternative (dark) background.

e.g. Stripe has regular (dark text on white) and alternative (white text on dark) sections.

As I understand there are options assuming HTML:

Title

Text

    Action

Style in context of section, e.g.:

.dark h2, .dark p, .dark btn {
  color: white;
}

But a) context styling is not recommended; b) where does one put the styles? (Harry Roberts argues that in component's file)

Create alternative-colored components with modifiers

And change the HTML, e.g.:

.title--alt-color {color: white;}
.text--alt-color {color: white; }
...

But a) it doesn't work when you don't know which components will go in there; b) more work of managing HTML.

Maybe there is a better way to handle this?

Body:
What you're asking for is essentially to style a component within a section based on the section itself. Unfortunately this is impossible with CSS, as there is no parent selector in CSS. However, there is the inherit value, which allows you to style a component based on the rules defined by its parent - perfect for component-driven CSS.

In my opinion, the best way you can go about alternating background styling is to make use of the :nth-of-type pseudo-class on <section>:

section:nth-of-type(2n) {
  background: #464646;
  color: #fff;
}

<section>
    <h2>Title</h2>
    <p>Text</p>
    <a href="#" class="btn">Action</a>
</section>
<section>
    <h2>Title</h2>
    <p>Text</p>
    <a href="#" class="btn">Action</a>
</section>
<section>
    <h2>Title</h2>
    <p>Text</p>
    <a href="#" class="btn">Action</a>
</section>
<section>
    <h2>Title</h2>
    <p>Text</p>
    <a href="#" class="btn">Action</a>
</section>

Considering :nth-of-type makes use of math to target elements, you can access literally any combination of elements you would like:

// Style every second element, starting with the first element
section:nth-of-type(2n - 1)

// Style every third element, starting with the second element (2, 5, 8, etc.)
section:nth-of-type(3n + 2)

This way, it won't matter whether you're using a component-driven approach or not, as you'll be able to alternate the styling directly off of <section> itself.

Elements that inherit an attribute from internal stylesheets (such as <a> tag colour) will unfortunately still be styled based on the internal stylesheet, rather than rules defined by their parent.

You can get around this by either using context-styling:

section:nth-of-type(n) {
  background: #464646;
  color: #fff;
}

section:nth-of-type(n) a {
  color: #fff;
}

<section>
    <h2>Title</h2>
    <p>Text</p>
    <a href="#" class="btn">Action</a>
</section>

Or alternatively (and preferably) making use of the inherit value to tell every <a> tag to inherit its color from its parent:

section {
  background: #464646;
  color: #fff;
}
a {
  color: inherit;
}

<section>
    <h2>Title</h2>
    <p>Text</p>
    <a href="#" class="btn">Action</a>
</section>

Hope this helps!


来源: stackexchange

问:
Storing objects inside a session
I am attempting to store an object into $_SESSION but I am having a few issues doing so.

Here is the class:

```<code>class Profile {
            var $username;
            var $password;
            var $admin;

            function __construct($username, $password) {
                $this->username = $username;
                $this->password = $password;
            }

            function getName() {
                return $this->username;
            }

            function isAdmin() {
                return $this->admin;
            }

            function setAdmin($admin) {
                return $this->admin = $admin;
            }
        }
</code>```

and I am storing the data inside the session this way:

```<code>$_SESSION['profile'] = serialize($profile);
</code>```

and when I attempt to load that data in another class I receive an error:

Fatal error: main(): The script tried to execute a method or access a property of an incomplete object. Please ensure that the class definition "Profile" of the object you are trying to operate on was loaded before unserialize() gets called or provide a __autoload() function to load the class definition in C:\wamp64\www\login\hidden.php on line 33

I have dumped the loaded object to check if it is actually being loaded and it appears the object has been unserialized and I can see all the data itself inside the object.

```<code>$profile = unserialize($_SESSION['profile']);
var_dump($profile);
</code>```

and I receive this on my localhost when dumping it:

```<code>C:\wamp64\www\login\hidden.php:31:
object(__PHP_Incomplete_Class)[1]
  public '__PHP_Incomplete_Class_Name' => string 'Profile' (length=7)
  public 'username' => string 'myles' (length=5)
  public 'password' => string 'myles' (length=5)
  public 'admin' => boolean true
</code>```

I am truly lost and have no idea what to do if someone could help me, that would be great.

答:
Before unserializing you need to do the same thing you would before creating an instance of the object normally:

```<code>$profile = new Profile("u", "p");
</code>```

That is, make sure you have included all the files that define that class. That is what the error message is trying to tell you:

Please ensure that the class definition "Profile" of the object you are trying to operate on was loaded before unserialize() gets called

So do something like this:

```<code><?php
require_once '/path/to/Profile.class.php';
session_start();
$profile = unserialize($_SESSION['profile']);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Storing objects inside a session

Body:
I am attempting to store an object into $_SESSION but I am having a few issues doing so.

Here is the class:

class Profile {
            var $username;
            var $password;
            var $admin;

            function __construct($username, $password) {
                $this->username = $username;
                $this->password = $password;
            }

            function getName() {
                return $this->username;
            }

            function isAdmin() {
                return $this->admin;
            }

            function setAdmin($admin) {
                return $this->admin = $admin;
            }
        }

and I am storing the data inside the session this way:

$_SESSION['profile'] = serialize($profile);

and when I attempt to load that data in another class I receive an error:

Fatal error: main(): The script tried to execute a method or access a property of an incomplete object. Please ensure that the class definition "Profile" of the object you are trying to operate on was loaded before unserialize() gets called or provide a __autoload() function to load the class definition in C:\wamp64\www\login\hidden.php on line 33

I have dumped the loaded object to check if it is actually being loaded and it appears the object has been unserialized and I can see all the data itself inside the object.

$profile = unserialize($_SESSION['profile']);
var_dump($profile);

and I receive this on my localhost when dumping it:

C:\wamp64\www\login\hidden.php:31:
object(__PHP_Incomplete_Class)[1]
  public '__PHP_Incomplete_Class_Name' => string 'Profile' (length=7)
  public 'username' => string 'myles' (length=5)
  public 'password' => string 'myles' (length=5)
  public 'admin' => boolean true

I am truly lost and have no idea what to do if someone could help me, that would be great.

Body:
Before unserializing you need to do the same thing you would before creating an instance of the object normally:

$profile = new Profile("u", "p");

That is, make sure you have included all the files that define that class. That is what the error message is trying to tell you:

Please ensure that the class definition "Profile" of the object you are trying to operate on was loaded before unserialize() gets called

So do something like this:

<?php
require_once '/path/to/Profile.class.php';
session_start();
$profile = unserialize($_SESSION['profile']);


问:
Rails: polymorphic associations, find commented on
I've implemented polymorphic comments on my Rails app using this tutorial.

So I have:

```<code>class Place < ApplicationRecord
  has_many :comments, as: :commentable
end

class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true
end
</code>```

Now I want to index all comments and join them with the places they comment on, but I have no idea on how to achieve this.

In my comments_controller.rb I have:

```<code>class CommentsController < ApplicationController
  def index
    @comments = Comment.all
  end
end
</code>```

And in my comments index.html.erb I can access:

```<code><%= comment.commentable_type %>
<%= comment.commentable_id %>
</code>```

But how do I access the actual attributes of what the comments are on, example: <%= comment.place.name %>?

I believe it is related to this answer but I don't know how: rails joins polymorphic association

答:
You can refer to the commentable object with just

```<code>comment.commentable
</code>```

The only thing to watch out for here is that it assumes that all your commentables have the method you call on them, such as name.

```<code>comment.commentable.name
</code>```

You will want to preload these in your controller to avoid an N+1 as well.

```<code>class CommentsController < ApplicationController
  def index
    @comments = Comment.includes(:commentable).all
  end
end
</code>```

Body:
I've implemented polymorphic comments on my Rails app using this tutorial.

So I have:

class Place < ApplicationRecord
  has_many :comments, as: :commentable
end

class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true
end

Now I want to index all comments and join them with the places they comment on, but I have no idea on how to achieve this.

In my comments_controller.rb I have:

class CommentsController < ApplicationController
  def index
    @comments = Comment.all
  end
end

And in my comments index.html.erb I can access:

<%= comment.commentable_type %>
<%= comment.commentable_id %>

But how do I access the actual attributes of what the comments are on, example: <%= comment.place.name %>?

I believe it is related to this answer but I don't know how: rails joins polymorphic association

Body:
You can refer to the commentable object with just

comment.commentable

The only thing to watch out for here is that it assumes that all your commentables have the method you call on them, such as name.

comment.commentable.name

You will want to preload these in your controller to avoid an N+1 as well.

class CommentsController < ApplicationController
  def index
    @comments = Comment.includes(:commentable).all
  end
end


问:
DIV that is scrollable to reveal DIV underneath
I have a number of DIVs that I have positioned on top of one another.

What I am trying to get to is being able to scroll the top DIV and then once at the bottom of the DIV, reveal the DIV underneath.

Here is where I've got to so far:

https://codepen.io/dadofgage/pen/yMqZaj

```<code><style>
    #container {
    position: relative;
}

.overlay, .overlay2, .overlay3,
.content{
    display:block;
    position: absolute;
    top: 0;
    left: 0;
}

.overlay3{
    z-index: 8;
    background: #000;
    color:#fff
}

.overlay2{
    z-index: 9;
    background: #c00;
}

.overlay{
    z-index: 10;
    background: #ccc;
}
</style>

<div id="container">
<div class="overlay3">This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  </div>
<div class="overlay2">This is the SECOND div of content.  This is the SECOND div of content.  This is the SECOND div of content.  This is the SECOND div of content.  This is the SECOND div of content.  This is the SECOND div of content.  This is the SECOND div of content.  This is the SECOND div of content.  This is the SECOND div of content.  This is the SECOND div of content.  This is the SECOND div of content.  This is the SECOND div of content.  This is the SECOND div of content.  This is the SECOND div of content.  This is the SECOND div of content.  This is the SECOND div of content.  This is the SECOND div of content.  This is the SECOND div of content.  This is the SECOND div of content.  This is the SECOND div of content.  </div>
<div class="overlay">This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  </div>
<div class="content">This is the BOTTOM div of content.  This is the BOTTOM div of content.  This is the BOTTOM div of content.  This is the BOTTOM div of content.  This is the BOTTOM div of content.  This is the BOTTOM div of content.  This is the BOTTOM div of content.  This is the BOTTOM div of content.  This is the BOTTOM div of content.  This is the BOTTOM div of content.  This is the BOTTOM div of content.  This is the BOTTOM div of content.  This is the BOTTOM div of content.  This is the BOTTOM div of content.  This is the BOTTOM div of content.  This is the BOTTOM div of content.  This is the BOTTOM div of content.  This is the BOTTOM div of content.  This is the BOTTOM div of content.  </div>
</code>```

答:
I would suggest making use of .scrollTop() and then conditionally reveal them based on that. For example:

https://jsfiddle.net/Twisty/89at6t77/

HTML

```<code><div id="container">
  <div id="o-3" class="overlay">This is contents #3.</div>
  <div id="o-2" class="overlay hidden">This is contents #2.</div>
  <div id="o-1" class="overlay hidden">This is contents #1.</div>
  <div id="o-0" class="content hidden">This is content.</div>
</div>
</code>```

CSS

```<code>#container {
  position: relative;
  height: 1500px;
}

.overlay,
.content {
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 150px;
  text-align: center;
  padding-top: 150px;
}

#o-3 {
  z-index: 8;
  background: #000;
  color: #fff
}

#o-2 {
  z-index: 9;
  background: #c00;
  top: 300px;
}

#o-1 {
  z-index: 10;
  background: #ccc;
  top: 600px;
}

#o-0 {
  top: 900px;
}

.hidden {
  display: none;
}
</code>```

JavaScript

```<code>$(function() {
  var boxHeight = $("#o-3").height();
  $(window).scroll(function(e) {
    currentPos = $(window).scrollTop() + boxHeight;
    if (currentPos > 320) {
      $("#o-2").fadeIn();
    }
    if (currentPos > 620) {
      $("#o-1").fadeIn();
    }
    if (currentPos > 920) {
      $("#o-0").fadeIn();
    }
  });
});
</code>```

Body:
I have a number of DIVs that I have positioned on top of one another.

What I am trying to get to is being able to scroll the top DIV and then once at the bottom of the DIV, reveal the DIV underneath.

Here is where I've got to so far:

https://codepen.io/dadofgage/pen/yMqZaj

This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.  This is the top div of content.

This is the SECOND div of content.  This is the SECOND div of content.  This is the SECOND div of content.  This is the SECOND div of content.  This is the SECOND div of content.  This is the SECOND div of content.  This is the SECOND div of content.  This is the SECOND div of content.  This is the SECOND div of content.  This is the SECOND div of content.  This is the SECOND div of content.  This is the SECOND div of content.  This is the SECOND div of content.  This is the SECOND div of content.  This is the SECOND div of content.  This is the SECOND div of content.  This is the SECOND div of content.  This is the SECOND div of content.  This is the SECOND div of content.  This is the SECOND div of content.

This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.  This is the THIRD div of content.

This is the BOTTOM div of content.  This is the BOTTOM div of content.  This is the BOTTOM div of content.  This is the BOTTOM div of content.  This is the BOTTOM div of content.  This is the BOTTOM div of content.  This is the BOTTOM div of content.  This is the BOTTOM div of content.  This is the BOTTOM div of content.  This is the BOTTOM div of content.  This is the BOTTOM div of content.  This is the BOTTOM div of content.  This is the BOTTOM div of content.  This is the BOTTOM div of content.  This is the BOTTOM div of content.  This is the BOTTOM div of content.  This is the BOTTOM div of content.  This is the BOTTOM div of content.  This is the BOTTOM div of content.

Body:
I would suggest making use of .scrollTop() and then conditionally reveal them based on that. For example:

https://jsfiddle.net/Twisty/89at6t77/

HTML

<div id="container">
  <div id="o-3" class="overlay">This is contents #3.</div>
  <div id="o-2" class="overlay hidden">This is contents #2.</div>
  <div id="o-1" class="overlay hidden">This is contents #1.</div>
  <div id="o-0" class="content hidden">This is content.</div>
</div>

CSS

#container {
  position: relative;
  height: 1500px;
}

.overlay,
.content {
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 150px;
  text-align: center;
  padding-top: 150px;
}

#o-3 {
  z-index: 8;
  background: #000;
  color: #fff
}

#o-2 {
  z-index: 9;
  background: #c00;
  top: 300px;
}

#o-1 {
  z-index: 10;
  background: #ccc;
  top: 600px;
}

#o-0 {
  top: 900px;
}

.hidden {
  display: none;
}

JavaScript

$(function() {
  var boxHeight = $("#o-3").height();
  $(window).scroll(function(e) {
    currentPos = $(window).scrollTop() + boxHeight;
    if (currentPos > 320) {
      $("#o-2").fadeIn();
    }
    if (currentPos > 620) {
      $("#o-1").fadeIn();
    }
    if (currentPos > 920) {
      $("#o-0").fadeIn();
    }
  });
});


问:
How to call a oracle stored procedure with RECORD as OUT parameter?
I have a procedure in oracle database, which looks like

```<code>create or replace PACKAGE MY_PACKAGE AS
  TYPE MY_RECORD IS RECORD
  (
    first_name abc.first_name%TYPE,
    middle_name abc.middle_name%TYPE,
    last_name abc.last_name%TYPE
  );
  TYPE MY_RECORD_REF IS REF CURSOR RETURN MY_RECORD;
  PROCEDURE getDetails(
    last_name IN OUT VARCHAR2,
    V_MY_RECORD_REF   OUT MY_RECORD_REF);
END MY_PACKAGE;
</code>```

I want to call the stored procedure to get the data and display them but unable to do so.

Can someone help?

Thanks in advance.

答:
The record is there to give you a definition of the result set. Use the packaged types to define local variables which you use when calling the procedure.

```<code>declare
    l_result_Set MY_PACKAGE.MY_RECORD_REF;
    l_record MY_PACKAGE.MY_RECORD;
    l_name abc.last_name%TYPE ;
begin
    -- get the results
    MY_PACKAGE.getDetails(
          l_name
          , l_result_Set );
    -- now read them
    loop
        fetch l_result_Set into l_record;
        exit when l_result_Set%notfound;
        -- do stuff here
    end loop;
end;
</code>```

"do you know how to do the same in java? "

A Ref Cursor is a JDBC Result Set. Andrej Koelewijn has a brief example in this blog post. Note the use of the Oracle library data type OracleTypes.CURSOR. The full sweep of ResultSet is covered in the JDBC Deve guide. Find out more.

Body:
I have a procedure in oracle database, which looks like

create or replace PACKAGE MY_PACKAGE AS
  TYPE MY_RECORD IS RECORD
  (
    first_name abc.first_name%TYPE,
    middle_name abc.middle_name%TYPE,
    last_name abc.last_name%TYPE
  );
  TYPE MY_RECORD_REF IS REF CURSOR RETURN MY_RECORD;
  PROCEDURE getDetails(
    last_name IN OUT VARCHAR2,
    V_MY_RECORD_REF   OUT MY_RECORD_REF);
END MY_PACKAGE;

I want to call the stored procedure to get the data and display them but unable to do so.

Can someone help?

Thanks in advance.

Body:
The record is there to give you a definition of the result set. Use the packaged types to define local variables which you use when calling the procedure.

declare
    l_result_Set MY_PACKAGE.MY_RECORD_REF;
    l_record MY_PACKAGE.MY_RECORD;
    l_name abc.last_name%TYPE ;
begin
    -- get the results
    MY_PACKAGE.getDetails(
          l_name
          , l_result_Set );
    -- now read them
    loop
        fetch l_result_Set into l_record;
        exit when l_result_Set%notfound;
        -- do stuff here
    end loop;
end;

"do you know how to do the same in java? "

A Ref Cursor is a JDBC Result Set. Andrej Koelewijn has a brief example in this blog post. Note the use of the Oracle library data type OracleTypes.CURSOR. The full sweep of ResultSet is covered in the JDBC Deve guide. Find out more.


问:
populate Jtable with array
I have created an array from my csv file and am stuck in putting it in to rows on the JTable</p>

```<code> try {
        BufferedReader br = new BufferedReader(new FileReader(datafile));
        String columnn = br.readLine();

        String[] columnnames = columnn.split("\t");
        DefaultTableModel tableMod = new DefaultTableModel();
        tableMod.setColumnIdentifiers(columnnames);
        jTable1.setModel(tableMod);
        while ((line = br.readLine()) != null) {

            String[] values = line.split("\t");

        for (int i = 0; i < values.length; i++) {
            System.out.println(values[i]);
        }

}
br.close();
    }
</code>```

答:
```<code>String[] values = line.split("\t");
</code>```

That doesn't do anything. You need to actually add the data to the model:

```<code>tableModel.addRow( line.split("\t") );
</code>```

You also need to make sure you have added the table to a JScrollPane and the scrollpane is added to the frame.

Title: populate Jtable with array

Body:
I have created an array from my csv file and am stuck in putting it in to rows on the JTable

 try {
        BufferedReader br = new BufferedReader(new FileReader(datafile));
        String columnn = br.readLine();

        String[] columnnames = columnn.split("\t");
        DefaultTableModel tableMod = new DefaultTableModel();
        tableMod.setColumnIdentifiers(columnnames);
        jTable1.setModel(tableMod);
        while ((line = br.readLine()) != null) {

            String[] values = line.split("\t");

        for (int i = 0; i < values.length; i++) {
            System.out.println(values[i]);
        }

}
br.close();
    }

Body:
String[] values = line.split("\t");

That doesn't do anything. You need to actually add the data to the model:

tableModel.addRow( line.split("\t") );

You also need to make sure you have added the table to a JScrollPane and the scrollpane is added to the frame.


问:
rename multiple files possible unintended interpolation
I'm using brew rename to rename multiple files...

```<code>file-24.png => file.png
file-48.png => file@2x.png
file-72.png => file@3x.png
</code>```

the first one is succeed with,,

```<code>rename 's/-24//g' *
</code>```

the second and third...

```<code>rename 's/-48/@2x/g' *
</code>```

and getting Possible unintended interpolation of @2 in string at (eval 2) line 1...

escaping doesnt work..

```<code>rename 's/-48/\@2x/g' *
</code>```

other possible ways to rename multiple files like this case are also welcome..

答:
I don't know what "brew rename" is, but if it uses normal regex

```<code>'s/pattern/q(@replacement)/e'
</code>```

This uses /e modifier to evaluate the replacement side as code, where q() operator (single quotes) is used to insert literal characters.

Another way is to use \x40 for @ character

```<code>'s/pattern/\x40replacement/'
</code>```

or just escape it, use \@ in the replacement.

This is suitable for when there's just one character to deal with, like here. if there's more than that then it's easier to single-quote the whole thing, with q() (for which we need /e flag).

Can't help it but ask -- are you certain that you want to have @ in a file name?  That character gets interpreted in various ways by many tools. For instance, sticking that file name in a variable in a Perl script leads to no end of trouble.  Why not even simply file_at_2x.png?

This may be more of a curiousity, but if you have a lot of files you can rename them all with

```<code>'s{ \-([0-9]+) }{ ($r = $1/24) > 1 && qq(_at_${r}x) || q() }ex'
</code>```

This captures the number ([0-9]+) into $1. Then, it finds the ratio ($r = $1/24) and if that is >1 then (&& short-circuits) it replaces -number with _at_${r}x, otherwise (||) removes it by putting an empty string, q().

I use {}{} delimiters so that I may use / inside, and }x allows spaces inside, for readability.

Please test this carefully with (a copy of) your actual files, as always.

ContentLicense: CC BY-SA 4.0

Body:
I'm using brew rename to rename multiple files...

file-24.png => file.png
file-48.png => file@2x.png
file-72.png => file@3x.png

the first one is succeed with,,

rename 's/-24//g' *

the second and third...

rename 's/-48/@2x/g' *

and getting Possible unintended interpolation of @2 in string at (eval 2) line 1...

escaping doesnt work..

rename 's/-48/\@2x/g' *

other possible ways to rename multiple files like this case are also welcome..

Body:
I don't know what "brew rename" is, but if it uses normal regex

's/pattern/q(@replacement)/e'

This uses /e modifier to evaluate the replacement side as code, where q() operator (single quotes) is used to insert literal characters.

Another way is to use \x40 for @ character

's/pattern/\x40replacement/'

or just escape it, use \@ in the replacement.

This is suitable for when there's just one character to deal with, like here. if there's more than that then it's easier to single-quote the whole thing, with q() (for which we need /e flag).

Can't help it but ask -- are you certain that you want to have @ in a file name?  That character gets interpreted in various ways by many tools. For instance, sticking that file name in a variable in a Perl script leads to no end of trouble.  Why not even simply file_at_2x.png?

This may be more of a curiousity, but if you have a lot of files you can rename them all with

's{ \-([0-9]+) }{ ($r = $1/24) > 1 && qq(_at_${r}x) || q() }ex'

This captures the number ([0-9]+) into $1. Then, it finds the ratio ($r = $1/24) and if that is >1 then (&& short-circuits) it replaces -number with _at_${r}x, otherwise (||) removes it by putting an empty string, q().

I use {}{} delimiters so that I may use / inside, and }x allows spaces inside, for readability.

Please test this carefully with (a copy of) your actual files, as always.


问:
Using a regex to extract a substring
I have the following string:

```<code><cfset foo="Students: Am Goron, rika Mrks, Apl Rirez, Ktsana Tanam    Course Location: Training Center - Hillsboro, OR - Hillsboro OR 97124    Course Date/Time: February 03, 2017">
</code>```

I want to use a regex to extract only the list of students which is:

```<code>Am Goron, rika Mrks, Apl Rirez, Ktsana Tanam
</code>```

If I use replace, I have to use many replace to make it happen. I think it would work with one regex, but I am not good with regular expressions. Can anybody help and guide?

答:
Regex's are not my strong suit either, but there are online tutorials and test sites like RegExrv2.1 you can use for practicing. With a bit of reading I came up with this:

```<code><cfset list = reReplaceNoCase(text, "^Students:(.*?)Course Location:.*$", "\1", "all")>
</code>```

Breaking it down, it searches for a string that:

^Students:  - starts with "Students:"

(.+?) - followed by one or more characters as a capturing group

Course Location: - followed by the course location

.*$ - ending with zero or more characters

Then use a backreference, i.e. \1 to replace everything except the matched group, ie the student list.

If you prefer non-regex options, you could also cheat (a little) and insert an extra colon, ie : before course location. That would allow you to treat the string as a list delimited by colons, and extract the second element with list functions:

```<code><cfset list = listGetAt( replace(text, "Course Location:", ":Course Location:"), 2, ":")>
</code>```

Title: Using a regex to extract a substring

Body:
I have the following string:

<cfset foo="Students: Am Goron, rika Mrks, Apl Rirez, Ktsana Tanam    Course Location: Training Center - Hillsboro, OR - Hillsboro OR 97124    Course Date/Time: February 03, 2017">

I want to use a regex to extract only the list of students which is:

Am Goron, rika Mrks, Apl Rirez, Ktsana Tanam

If I use replace, I have to use many replace to make it happen. I think it would work with one regex, but I am not good with regular expressions. Can anybody help and guide?

Body:
Regex's are not my strong suit either, but there are online tutorials and test sites like RegExrv2.1 you can use for practicing. With a bit of reading I came up with this:

<cfset list = reReplaceNoCase(text, "^Students:(.*?)Course Location:.*$", "\1", "all")>

Breaking it down, it searches for a string that:

^Students:  - starts with "Students:"

(.+?) - followed by one or more characters as a capturing group

Course Location: - followed by the course location

.*$ - ending with zero or more characters

Then use a backreference, i.e. \1 to replace everything except the matched group, ie the student list.

If you prefer non-regex options, you could also cheat (a little) and insert an extra colon, ie : before course location. That would allow you to treat the string as a list delimited by colons, and extract the second element with list functions:

<cfset list = listGetAt( replace(text, "Course Location:", ":Course Location:"), 2, ":")>


问:
Debugging Windows CE Device from Windows 10 with Visual Studio 2008
I upgraded from Windows 7 to Windows 10 this week. I develop compact framework software for mobile devices (Windows CE7, Windows Mobile e.g.). I use Visual Studio 2008.

Now I get the error: "error connecting to device" (Device Connectivity Component).

Windows Mobile Device Center is running and the device shows up in my explorer.
Any hints?

答:
In case it helps somebody else, I was using Visual Studio 2008 on Windows 10 and trying to connect to a Windows CE 5.0 device and was having the same problem.

The device was being detected by Win 10 and I could browse its file system from my PC etc, but VS2008 was failing to connect with a message:

ActiveSync bootstrap initialization failed. Please connect/cradle a
  real device or download the User-level Windows Mobile Device Center
  Application from...

In the end I got it working by manually installing Windows Mobile Device Center 6.1 (there's also a 32 bit version)


问:
Implement a 32x64 register file in Verilog
Here are the specifications of the register file:

Buses A, B, and W are 64 bits wide.

When RegWr is set to 1, then the data on Bus W is stored in the
register     specified by Rw, on the negative (falling) clock edge.

Register 31 must always read zero.

Data from registers (as specified by Ra and Rb) is sent on Bus A and
Bus B respectively, after a delay of 2 tics.

Writes to the register file must have a delay of 3 tics.

The Register File module should have the following interface:

```<code>module RegisterFile(BusA, BusB, BusW, RA, RB, RW, RegWr, Clk);
</code>```

Here is my current program

```<code>module RegisterFile(BusA, BusB, BusW, RA, RB, RW, RegWr, Clk);
 output [63:0] BusA;
 output [63:0] BusB;
 output [63:0] BusW;
 input RA;
 input RB;
 input RW;
 input RegWr;
 input Clk;
 reg [31:0] registers [31:0];

 assign #2 BusA = registers [0];
 assign #2 BusB = registers [1];

 always @ (negedge Clk) begin
  if(RegWr & RW !=0)
    registers[RW] <= #3 BusW;
 end
endmodule
</code>```

I am wondering how to initialize the RA and RB to zero, and wondering how to send the data from RA and RB to BusA and BusB correctly

答:
There are a few things that need to be changed in the code first

BusA, BusB and BusW are data buses each 64 bits wide. BusW is being used as the input bus, while BusA and BusB are output buses. Therefore the declaration of the ports needs to change as

```<code>input [63:0] BusW;
output [63:0] BusA, BusB;
</code>```

The register file has a depth of 32. and RA, RB and RW are the address buses. These addresses need to be 5 bits wide.

```<code>input [4:0] RA,RB,RW;
</code>```

The complete code can then be re-written as

```<code>module RegisterFile(BusA, BusB, BusW, RA, RB, RW, RegWr, Clk);
  output [63:0] BusA, BusB;
  input [63:0] BusW;
  input [4:0] RA, RB, RW;
  input RegWr;
  input Clk;

  reg [63:0] registers [31:0];

  assign #2 BusA = registers[RA];
  assign #2 BusB = registers[RB];

  always @ (negedge Clk)
  begin
    if(RegWr)
      if (RW != 4'd31)
        registers[RW] <= #3 BusW;
      else
        // This is done to allow the user to reset the 0th location to a zero value.
        registers[0] <= #3 'd0;
  end
endmodule
</code>```

I have simulated this code on edaplayground and also created a small testbench to test it. Here is the link to the code and testbench
https://www.edaplayground.com/x/5DXC

Body:
Here are the specifications of the register file:

Buses A, B, and W are 64 bits wide.

When RegWr is set to 1, then the data on Bus W is stored in the
register     specified by Rw, on the negative (falling) clock edge.

Register 31 must always read zero.

Data from registers (as specified by Ra and Rb) is sent on Bus A and
Bus B respectively, after a delay of 2 tics.

Writes to the register file must have a delay of 3 tics.

The Register File module should have the following interface:

module RegisterFile(BusA, BusB, BusW, RA, RB, RW, RegWr, Clk);

Here is my current program

module RegisterFile(BusA, BusB, BusW, RA, RB, RW, RegWr, Clk);
 output [63:0] BusA;
 output [63:0] BusB;
 output [63:0] BusW;
 input RA;
 input RB;
 input RW;
 input RegWr;
 input Clk;
 reg [31:0] registers [31:0];

 assign #2 BusA = registers [0];
 assign #2 BusB = registers [1];

 always @ (negedge Clk) begin
  if(RegWr & RW !=0)
    registers[RW] <= #3 BusW;
 end
endmodule

I am wondering how to initialize the RA and RB to zero, and wondering how to send the data from RA and RB to BusA and BusB correctly

Body:
There are a few things that need to be changed in the code first

BusA, BusB and BusW are data buses each 64 bits wide. BusW is being used as the input bus, while BusA and BusB are output buses. Therefore the declaration of the ports needs to change as

input [63:0] BusW;
output [63:0] BusA, BusB;

The register file has a depth of 32. and RA, RB and RW are the address buses. These addresses need to be 5 bits wide.

input [4:0] RA,RB,RW;

The complete code can then be re-written as

module RegisterFile(BusA, BusB, BusW, RA, RB, RW, RegWr, Clk);
  output [63:0] BusA, BusB;
  input [63:0] BusW;
  input [4:0] RA, RB, RW;
  input RegWr;
  input Clk;

  reg [63:0] registers [31:0];

  assign #2 BusA = registers[RA];
  assign #2 BusB = registers[RB];

  always @ (negedge Clk)
  begin
    if(RegWr)
      if (RW != 4'd31)
        registers[RW] <= #3 BusW;
      else
        // This is done to allow the user to reset the 0th location to a zero value.
        registers[0] <= #3 'd0;
  end
endmodule

I have simulated this code on edaplayground and also created a small testbench to test it. Here is the link to the code and testbench
https://www.edaplayground.com/x/5DXC


问:
Should you fork your own Project and submit pull request?
Hi I started a project on github with other people contributing, should I fork my own project and do updates via pull request. I've only been pushing changes to branches so far, and I am wondering if that is a bad practice.

What is the Git etiquette here?

答:
It's definitely not a bad practice, it's a completely normal way to use git.

As I see, the usual approach is to use master as a relatively stable branch, which can be built anytime. You implement new features in other branches, feature branches, then merge this into master. GitHub extends this way of doing things with pull requests, which are usually merged into master, just like feature branches of your own.

But the bottom line is: the system is flexible, and there is no single way of doing things, so you can choose whatever is comfortable for you, and your contributors.


问:
Unhandled rejection MongoError: cannot connect to server in MongoDB
I got Unhandled rejection MongoError: cannot connect to server when run my meanjs project.

Previously was running fine but when update nodejs 5.11.1, mongodb 3.2.6,"mongoose": "^4.4.16" and "connect-mongo": "^1.1.0", then this error getting.

Unhandled rejection MongoError: cannot connect to server
          at Collection.listIndexes (/home/shaishab/Project/Open-Source/BS-Commerce/node_modules/mongodb/lib/collection.js:1750:11)
          at indexInformation (/home/shaishab/Project/Open-Source/BS-Commerce/node_modules/mongodb/lib/db.js:1625:25)
          at Db.indexInformation (/home/shaishab/Project/Open-Source/BS-Commerce/node_modules/mongodb/lib/db.js:1589:44)
          at ensureIndex (/home/shaishab/Project/Open-Source/BS-Commerce/node_modules/mongodb/lib/db.js:1082:8)
          at Db.ensureIndex (/home/shaishab/Project/Open-Source/BS-Commerce/node_modules/mongodb/lib/db.js:1058:44)
          at ensureIndex (/home/shaishab/Project/Open-Source/BS-Commerce/node_modules/mongodb/lib/collection.js:1820:13)
          at Collection.ensureIndex (/home/shaishab/Project/Open-Source/BS-Commerce/node_modules/mongodb/lib/collection.js:1808:44)
          at MongoStore.setAutoRemoveAsync (/home/shaishab/Project/Open-Source/BS-Commerce/node_modules/connect-mongo/src/index.js:123:40)
          at MongoStore.handleNewConnectionAsync (/home/shaishab/Project/Open-Source/BS-Commerce/node_modules/connect-mongo/src/index.js:116:18)
          at MongoStore (/home/shaishab/Project/Open-Source/BS-Commerce/node_modules/connect-mongo/src/index.js:95:26)
          at module.exports (/home/shaishab/Project/Open-Source/BS-Commerce/config/express.js:101:10)
          at Object. (/home/shaishab/Project/Open-Source/BS-Commerce/server.js:31:38)
          at Module._compile (module.js:413:34)
          at Object.Module._extensions..js (module.js:422:10)

in config file code

```<code>var session = require('express-session'),
    MongoStore = require('connect-mongo')(session),
    mongoose = require('mongoose');

var db = mongoose.connect('dbUrl');
app.use(session({
        saveUninitialized: true,
        resave: true,
        secret: config.sessionSecret,
        store: new MongoStore({
            db: db.connection.db,
            collection: config.sessionCollection
        })
}));
</code>```

Can any one help me ?

答:
As I did not have a db variable, my solution was:

```<code>var mongoStore = require('connect-mongo')(session);
var mongoose = require('mongoose');

const connection = mongoose.createConnection('mongodb://localhost/chester');

app.use(session({
    secret: config.secrets.session,
    resave: true,
    saveUninitialized: true,
    store: new mongoStore({mongooseConnection: connection})
  }));
</code>```

hope it helps

Body:
I got Unhandled rejection MongoError: cannot connect to server when run my meanjs project.

Previously was running fine but when update nodejs 5.11.1, mongodb 3.2.6,"mongoose": "^4.4.16" and "connect-mongo": "^1.1.0", then this error getting.

Unhandled rejection MongoError: cannot connect to server
          at Collection.listIndexes (/home/shaishab/Project/Open-Source/BS-Commerce/node_modules/mongodb/lib/collection.js:1750:11)
          at indexInformation (/home/shaishab/Project/Open-Source/BS-Commerce/node_modules/mongodb/lib/db.js:1625:25)
          at Db.indexInformation (/home/shaishab/Project/Open-Source/BS-Commerce/node_modules/mongodb/lib/db.js:1589:44)
          at ensureIndex (/home/shaishab/Project/Open-Source/BS-Commerce/node_modules/mongodb/lib/db.js:1082:8)
          at Db.ensureIndex (/home/shaishab/Project/Open-Source/BS-Commerce/node_modules/mongodb/lib/db.js:1058:44)
          at ensureIndex (/home/shaishab/Project/Open-Source/BS-Commerce/node_modules/mongodb/lib/collection.js:1820:13)
          at Collection.ensureIndex (/home/shaishab/Project/Open-Source/BS-Commerce/node_modules/mongodb/lib/collection.js:1808:44)
          at MongoStore.setAutoRemoveAsync (/home/shaishab/Project/Open-Source/BS-Commerce/node_modules/connect-mongo/src/index.js:123:40)
          at MongoStore.handleNewConnectionAsync (/home/shaishab/Project/Open-Source/BS-Commerce/node_modules/connect-mongo/src/index.js:116:18)
          at MongoStore (/home/shaishab/Project/Open-Source/BS-Commerce/node_modules/connect-mongo/src/index.js:95:26)
          at module.exports (/home/shaishab/Project/Open-Source/BS-Commerce/config/express.js:101:10)
          at Object. (/home/shaishab/Project/Open-Source/BS-Commerce/server.js:31:38)
          at Module._compile (module.js:413:34)
          at Object.Module._extensions..js (module.js:422:10)

in config file code

var session = require('express-session'),
    MongoStore = require('connect-mongo')(session),
    mongoose = require('mongoose');

var db = mongoose.connect('dbUrl');
app.use(session({
        saveUninitialized: true,
        resave: true,
        secret: config.sessionSecret,
        store: new MongoStore({
            db: db.connection.db,
            collection: config.sessionCollection
        })
}));

Can any one help me ?

Body:
As I did not have a db variable, my solution was:

var mongoStore = require('connect-mongo')(session);
var mongoose = require('mongoose');

const connection = mongoose.createConnection('mongodb://localhost/chester');

app.use(session({
    secret: config.secrets.session,
    resave: true,
    saveUninitialized: true,
    store: new mongoStore({mongooseConnection: connection})
  }));

hope it helps


问:
Copy all used cells from one workbook sheet to another existing workbook sheet
I am trying to copy all the used cells in an excel worksheet from a closed workbook into an already created worksheet in my current workbook using VBA.

Have seen lots of examples on copy the sheet as a new sheet but not just the used contents into an existing sheet.

Thanks!
Mike

答:
Open the source workbook, using:
set wb = Workbooks.Open FileName:="fullPathAndFileName.xlsx", UpdateLinks:=0, ReadOnly:=True, AddToMru:=False

Using a reference to the sheet you want to copy, eg., wb.Sheets(1) (refers to the first sheet in the workbook), and a reference to your destination sheet, eg. destWorkSheet run a loop like this:

```<code>For Each cel in wb.Sheets(1).UsedRange.Cells
    destWorkSheet.Cells(cel.Row, cel.Column) = cel
Next
</code>```

This will copy the values cell by cell to the same location in the destination worksheet as they are in the source worksheet. You probably want to turn calculation off first. There are certainly other ways to do it as well.

You will still need to open the source workbook, but another approach is to do a direct write of Values. You can do this as long as the destination and source ranges are the same size and shape. This subroutine will do it for you:

```<code>    Private Sub CopyValuesSourceToDest(src As Range, dest As Range)
    'dest should be one cell, src can be a range of cells
    If dest.Cells.Count <> 1 Then MsgBox "Only pass one cell as the destination.": Exit Sub
    Dim rws As Long, cols As Long, trueDest As Range
    rws = src.Rows.Count
    cols = src.Columns.Count
    Set trueDest = dest.Parent.Range(dest.Cells(1, 1), dest.Cells(1, 1).Offset(rws - 1, cols - 1))
    trueDest.Value = src.Value
    End Sub
</code>```

You would then call the sub like this:

```<code>    CopyValuesSourceToDest sourceSheet.UsedRange, destSheet.Range("B7") 'B7, or whatever
</code>```

Body:
Open the source workbook, using:
set wb = Workbooks.Open FileName:="fullPathAndFileName.xlsx", UpdateLinks:=0, ReadOnly:=True, AddToMru:=False

Using a reference to the sheet you want to copy, eg., wb.Sheets(1) (refers to the first sheet in the workbook), and a reference to your destination sheet, eg. destWorkSheet run a loop like this:

For Each cel in wb.Sheets(1).UsedRange.Cells
    destWorkSheet.Cells(cel.Row, cel.Column) = cel
Next

This will copy the values cell by cell to the same location in the destination worksheet as they are in the source worksheet. You probably want to turn calculation off first. There are certainly other ways to do it as well.

You will still need to open the source workbook, but another approach is to do a direct write of Values. You can do this as long as the destination and source ranges are the same size and shape. This subroutine will do it for you:

    Private Sub CopyValuesSourceToDest(src As Range, dest As Range)
    'dest should be one cell, src can be a range of cells
    If dest.Cells.Count <> 1 Then MsgBox "Only pass one cell as the destination.": Exit Sub
    Dim rws As Long, cols As Long, trueDest As Range
    rws = src.Rows.Count
    cols = src.Columns.Count
    Set trueDest = dest.Parent.Range(dest.Cells(1, 1), dest.Cells(1, 1).Offset(rws - 1, cols - 1))
    trueDest.Value = src.Value
    End Sub

You would then call the sub like this:

    CopyValuesSourceToDest sourceSheet.UsedRange, destSheet.Range("B7") 'B7, or whatever


问:
Best way of using masks to select sub-vectors in Python
We want to select some elements of a 1D array v_data. The processing we need to do requires looping over sub-vectors of v_data.

Right now I use byte logic like Gosper's hack to create an integer n_mask whose binary representation corresponds to the indices of v_data I want.  n_mask can be converted to a binary vector through a method:

```<code>def num2bv(num, n_len):
    """Convert a number to a binary vector of some length"""
    return [bool((2**ii & num)//(2**ii)) for ii in reversed(range(0, n_len))]
</code>```

Setting bv_mask = num2bv(n_mask, len(v_data)), the sub-vector can be recovered by running v_data[bv_using]

Is this a bad way to do it? In particular I am concerned that:

Indexing with binary vectors will be slow in practice

num2bv will be slow in practice

Ability to use this technique for vectors of any length depends on Python's arbitrary-precision integers, which might be slow or nonportable

Are these valid concerns?

答:
Depending on the length of your vector it may be much faster to use itertools.combinations:

```<code>In [2] v = np.array(range(15))

In [3]: %time x = [v[num2bv(i,15)] for i in range(2**15)]
CPU times: user 498 ms, sys: 5.83 ms, total: 504 ms
Wall time: 506 ms

In [4]: %time x = [c for i in range(15) for c in combinations(v,i)]
CPU times: user 5.67 ms, sys: 1.53 ms, total: 7.2 ms
Wall time: 6.91 ms
</code>```

Body:
We want to select some elements of a 1D array v_data. The processing we need to do requires looping over sub-vectors of v_data.

Right now I use byte logic like Gosper's hack to create an integer n_mask whose binary representation corresponds to the indices of v_data I want.  n_mask can be converted to a binary vector through a method:

def num2bv(num, n_len):
    """Convert a number to a binary vector of some length"""
    return [bool((2**ii & num)//(2**ii)) for ii in reversed(range(0, n_len))]

Setting bv_mask = num2bv(n_mask, len(v_data)), the sub-vector can be recovered by running v_data[bv_using]

Is this a bad way to do it? In particular I am concerned that:

Indexing with binary vectors will be slow in practice

num2bv will be slow in practice

Ability to use this technique for vectors of any length depends on Python's arbitrary-precision integers, which might be slow or nonportable

Are these valid concerns?

Body:
Depending on the length of your vector it may be much faster to use itertools.combinations:

In [2] v = np.array(range(15))

In [3]: %time x = [v[num2bv(i,15)] for i in range(2**15)]
CPU times: user 498 ms, sys: 5.83 ms, total: 504 ms
Wall time: 506 ms

In [4]: %time x = [c for i in range(15) for c in combinations(v,i)]
CPU times: user 5.67 ms, sys: 1.53 ms, total: 7.2 ms
Wall time: 6.91 ms


问:
Powershell "screen" - keep the processes running even the connection is dropped?
I'm using enter-pssession to run scripts on remote servers. So I can login remotely to the servers. Run commands interactively, close the powershell console and later I can reattach the session and check the commands outputs.

Is there a Linux screen like functionality in powershell? I cannot use Windows remote desktop to connect the servers.

答:
I have recently run into double-hop issues with using PSSessions. What I did to work around that is to create a Session Configuration on the remote server that uses the -RunAs parameter to set the credentials that I need the commands on the remote server to be executed as. Then you connect to that session configuration on the remote server, and things should work as expected.

```<code>$MyCreds = Get-Credential ''
Invoke-Command -ScriptBlock {
    Set-PSSessionConfiguration -Name "My Remote Config" -RunAsCredential $using:MyCreds -Force
} -ComputerName Server01
</code>```

Then once the session configuration exists I can start a session using that config, and the whole double hop issue is null and void.

Now, mind you I do add some additional security, so that other people cannot use my session config, since that config has my credentials cached on the server (encrypted), and if they used that config they could do whatever they wanted as me. So to accomplish that I get my domain account SID, generate a SDDL line, and restrict access to the Session Config to only my account.

```<code>$Searcher = [adsisearcher]"(&(sAMAccountName=$($Creds.UserName.Split('\')[1]))(objectClass=user))"
$Results=$Searcher.FindOne().GetDirectoryEntry()
$MySID = new-object System.Security.Principal.SecurityIdentifier($Results.objectSid.value,0)|% value
$SDDL = "O:NSG:BAD:P(A;;GR;;;BA)(A;;GR;;;IU)(A;;GA;;;$MySID)S:P(AU;FA;GA;;;WD)(AU;SA;GXGW;;;WD)"
$FQDN = $Server.ServerName,$Server.Forest -join '.'
$MySessionName = "DoubleHop-{0}" -f $MyCreds.UserName.Split('\')[1]
Invoke-Command -ScriptBlock {
    Register-PSSessionConfiguration -Name $using:MySessionName -RunAsCredential $using:MyCreds -Force -SecurityDescriptorSddl $using:SDDL
} -ComputerName $FQDN -ea 4
</code>```

Body:
I have recently run into double-hop issues with using PSSessions. What I did to work around that is to create a Session Configuration on the remote server that uses the -RunAs parameter to set the credentials that I need the commands on the remote server to be executed as. Then you connect to that session configuration on the remote server, and things should work as expected.

$MyCreds = Get-Credential ''
Invoke-Command -ScriptBlock {
    Set-PSSessionConfiguration -Name "My Remote Config" -RunAsCredential $using:MyCreds -Force
} -ComputerName Server01

Then once the session configuration exists I can start a session using that config, and the whole double hop issue is null and void.

Now, mind you I do add some additional security, so that other people cannot use my session config, since that config has my credentials cached on the server (encrypted), and if they used that config they could do whatever they wanted as me. So to accomplish that I get my domain account SID, generate a SDDL line, and restrict access to the Session Config to only my account.

$Searcher = [adsisearcher]"(&(sAMAccountName=$($Creds.UserName.Split('\')[1]))(objectClass=user))"
$Results=$Searcher.FindOne().GetDirectoryEntry()
$MySID = new-object System.Security.Principal.SecurityIdentifier($Results.objectSid.value,0)|% value
$SDDL = "O:NSG:BAD:P(A;;GR;;;BA)(A;;GR;;;IU)(A;;GA;;;$MySID)S:P(AU;FA;GA;;;WD)(AU;SA;GXGW;;;WD)"
$FQDN = $Server.ServerName,$Server.Forest -join '.'
$MySessionName = "DoubleHop-{0}" -f $MyCreds.UserName.Split('\')[1]
Invoke-Command -ScriptBlock {
    Register-PSSessionConfiguration -Name $using:MySessionName -RunAsCredential $using:MyCreds -Force -SecurityDescriptorSddl $using:SDDL
} -ComputerName $FQDN -ea 4


问:
FloatingActionButton with BottomNavigationView
I cant position my FAB. It should be bottom right, but on top of the BottonNavigationView.

1) Can i achieve this without RelativeLayout inside coordinateLayout?

2) Show me how

3) Should i use FrameLayout as a container for fragments?

```<code><android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/appbar_padding_top"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/AppTheme.PopupOverlay">

    </android.support.v7.widget.Toolbar>

</android.support.design.widget.AppBarLayout>

<FrameLayout
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

</FrameLayout>

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab_electricity"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end|bottom"
    android:layout_margin="@dimen/fab_margin"
    app:layout_anchorGravity="bottom|right|end"
    app:srcCompat="@drawable/ic_add_electro" />

<android.support.design.widget.BottomNavigationView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_gravity="bottom">

</android.support.design.widget.BottomNavigationView>

</android.support.design.widget.CoordinatorLayout>
</code>```

答:
If you stick it in a linear layout and move the bottom nav outside of the coordinator view, it will be below it on the screen.

You could do it this way, but I prefer using an empty fragment container which I put in the hosting activity, and then place the fragment inside of it in code.

```<code><android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/appbar_padding_top"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
       app:popupTheme="@style/AppTheme.PopupOverlay">

    </android.support.v7.widget.Toolbar>

</android.support.design.widget.AppBarLayout>

<FrameLayout
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

</FrameLayout>

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab_electricity"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|right"
    app:srcCompat="@drawable/ic_add_electro"/>

</android.support.design.widget.CoordinatorLayout>
<android.support.design.widget.BottomNavigationView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_gravity="bottom">

</android.support.design.widget.BottomNavigationView>
</LinearLayout>
</code>```

Body:
I cant position my FAB. It should be bottom right, but on top of the BottonNavigationView.

1) Can i achieve this without RelativeLayout inside coordinateLayout?

2) Show me how

3) Should i use FrameLayout as a container for fragments?

<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/appbar_padding_top"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/AppTheme.PopupOverlay">

    </android.support.v7.widget.Toolbar>

</android.support.design.widget.AppBarLayout>

<FrameLayout
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

</FrameLayout>

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab_electricity"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end|bottom"
    android:layout_margin="@dimen/fab_margin"
    app:layout_anchorGravity="bottom|right|end"
    app:srcCompat="@drawable/ic_add_electro" />

<android.support.design.widget.BottomNavigationView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_gravity="bottom">

</android.support.design.widget.BottomNavigationView>

</android.support.design.widget.CoordinatorLayout>

Body:
If you stick it in a linear layout and move the bottom nav outside of the coordinator view, it will be below it on the screen.

You could do it this way, but I prefer using an empty fragment container which I put in the hosting activity, and then place the fragment inside of it in code.

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/appbar_padding_top"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
       app:popupTheme="@style/AppTheme.PopupOverlay">

    </android.support.v7.widget.Toolbar>

</android.support.design.widget.AppBarLayout>

<FrameLayout
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

</FrameLayout>

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab_electricity"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|right"
    app:srcCompat="@drawable/ic_add_electro"/>

</android.support.design.widget.CoordinatorLayout>
<android.support.design.widget.BottomNavigationView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_gravity="bottom">

</android.support.design.widget.BottomNavigationView>
</LinearLayout>


问:
Ajax Form doesn't remain on page
Been beating my mind at this but its now time for me to ask for help (ask i got work tomorrow and dont want to be on this all night)

My form is inside a modal and this is my script

```<code>$(function() {
    $("#applyForm").on('submit' , function(e) {
        $.ajax({
            type: 'POST',
            url: $("#applyForm").attr("action"),
            data: $('#applyForm').serialize(),
            success: function(data){
              alert('successfully submitted')},
            error: function(data){
              alert('something went wrong')
          }

     });
});
});
</code>```

It all works, It fires up the script and submits to the backend with a success message but as soon as you close the popup sucess message it redirects to the action "apply-now" page.

How can i prevent this without it breaking the submit, As i've tried return false and preventDefault.

Heres the form

```<code><form action="/apply-now/" enctype="multipart/form-data" id="applyForm" method="post" name="applyForm" class="form">
<input name="is_data_submitted" type="hidden" value="1">
<input name="listing_id" type="hidden" value="{$listing_id}">

MY FORM DATA

<button type="submit" id="submit" class="btn btn-warning">Apply now</button>
</code>```

Any help would really be appreciated !

Thanks

J

答:
Try this if you want the page not to reload:

```<code>$(function() {
    $("#applyForm").on('submit' , function(e) {
       e.preventDefault();
       //... the rest of your code
       //or add return false;
       return false;
    });
});
</code>```

As you catch the actual submiting the "normal" process will happen, you don't wan't that. So you have to stop it by e.preventDefault(). You can read the documentation about it here.

Or look right here for an example where it stays on the same page.

$("#form").submit(function(e){
    e.preventDefault();
    $(this).append("The page is staying here");
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="form">
    <input type="text" name="first" id="first">
    <input type="submit" value="enter">
</form></code>```

Hopefully this helps you.

Title: Ajax Form doesn't remain on page

Body:
Been beating my mind at this but its now time for me to ask for help (ask i got work tomorrow and dont want to be on this all night)

My form is inside a modal and this is my script

$(function() {
    $("#applyForm").on('submit' , function(e) {
        $.ajax({
            type: 'POST',
            url: $("#applyForm").attr("action"),
            data: $('#applyForm').serialize(),
            success: function(data){
              alert('successfully submitted')},
            error: function(data){
              alert('something went wrong')
          }

     });
});
});

It all works, It fires up the script and submits to the backend with a success message but as soon as you close the popup sucess message it redirects to the action "apply-now" page.

How can i prevent this without it breaking the submit, As i've tried return false and preventDefault.

Heres the form

<form action="/apply-now/" enctype="multipart/form-data" id="applyForm" method="post" name="applyForm" class="form">
<input name="is_data_submitted" type="hidden" value="1">
<input name="listing_id" type="hidden" value="{$listing_id}">

MY FORM DATA

<button type="submit" id="submit" class="btn btn-warning">Apply now</button>

Any help would really be appreciated !

Thanks

J

Body:
Try this if you want the page not to reload:

$(function() {
    $("#applyForm").on('submit' , function(e) {
       e.preventDefault();
       //... the rest of your code
       //or add return false;
       return false;
    });
});

As you catch the actual submiting the "normal" process will happen, you don't wan't that. So you have to stop it by e.preventDefault(). You can read the documentation about it here.

Or look right here for an example where it stays on the same page.

$("#form").submit(function(e){
    e.preventDefault();
    $(this).append("The page is staying here");
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="form">
    <input type="text" name="first" id="first">
    <input type="submit" value="enter">
</form>

Hopefully this helps you.


问:
How to use namespaces when writing XML file with SimpleXML
I’m writing a Google products RSS feed with SimpleXML in PHP. I’ve got my products coming from the database and creating the RSS file fine, but having problems when it comes to namespaces.

I’ve Googled and search Stack Overflow and come across dozens of posts of how to parse XML feeds containing namespaces, but my issue is actually authoring an XML file with a namespace.

Here is what the file should look like:

```<code><?xml version="1.0" encoding="UTF-8" ?>
<rss version ="2.0" xmlns:g="http://base.google.com/ns/1.0">
    <!-- content -->
</rss>
</code>```

And here is my code:

```<code><?php

$xml = new SimpleXMLElement('<rss></rss>');
$xml->addAttribute('version', '2.0');

$xml->addChild('channel');
$xml->channel->addChild('title', 'Removed');
$xml->channel->addChild('description', 'Removed');
$xml->channel->addChild('link', 'Removed');

foreach ($products as $product) {
    $item = $xml->channel->addChild('item');
    $item->addChild('title', htmlspecialchars($product['title']));
    $item->addChild('description', htmlspecialchars($product['title']));
    $item->addChild('link', $product['url']);
    $item->addChild('id', $product['product_id']);
    $item->addChild('price', $product['price_latest']);
    $item->addChild('brand', $product['range']);
    $item->addChild('condition', 'new');
    $item->addChild('image_link', $product['image']);
}
</code>```

How do I introduce the g namespace, both the xmlns declaration in the root rss element, and then as a prefix for id, price, brand, condition and image_link in each item element?

答:
This can be done by adding the namespace declaration into the root element creation along with adding the namespace to the addChild function.

The modification to the original code:

```<code>$products[] = array(
  "title" => "Foobar",
  "description" => "Foo",
  "url" => "https://f.oo.bar",
  "product_id" => "00001",
  "price_latest" => "$3.50",
  "range" => "Foo",
  "image" => "https://f.oo.bar/image.tiff",
);

$xml = new SimpleXMLElement('<rss xmlns:g="http://base.google.com/ns/1.0"/>');
$xml->addAttribute('version', '2.0');

$xml->addChild('channel');
$xml->channel->addChild('title', 'Removed');
$xml->channel->addChild('description', 'Removed');
$xml->channel->addChild('link', 'Removed');

foreach ($products as $product) {
    $item = $xml->channel->addChild('item');
    $item->addChild('title', htmlspecialchars($product['title']));
    $item->addChild('description', htmlspecialchars($product['title']));
    $item->addChild('link', $product['url']);
    $item->addChild('id', $product['product_id'], "http://base.google.com/ns/1.0");
    $item->addChild('price', $product['price_latest'], "http://base.google.com/ns/1.0");
    $item->addChild('brand', $product['range'], "http://base.google.com/ns/1.0");
    $item->addChild('condition', 'new', "http://base.google.com/ns/1.0");
    $item->addChild('image_link', $product['image'], "http://base.google.com/ns/1.0");
}

print_r($xml->asXML());
</code>```

Would yield the response:

```<code><?xml version="1.0"?>
<rss xmlns:g="http://base.google.com/ns/1.0" version="2.0">
  <channel>
    <title>Removed</title>
    <description>Removed</description>
    <link>Removed</link>
    <item>
      <title>Foobar</title>
      <description>Foobar</description><link/>
      <g:id>00001</g:id>
      <g:price>$3.50</g:price>
      <g:brand>Foo</g:brand>
      <g:condition>new</g:condition>
      <g:image_link>https://f.oo.bar/image.tiff</g:image_link>
    </item>
  </channel>
</rss>
</code>```

Body:
I’m writing a Google products RSS feed with SimpleXML in PHP. I’ve got my products coming from the database and creating the RSS file fine, but having problems when it comes to namespaces.

I’ve Googled and search Stack Overflow and come across dozens of posts of how to parse XML feeds containing namespaces, but my issue is actually authoring an XML file with a namespace.

Here is what the file should look like:

<?xml version="1.0" encoding="UTF-8" ?>
<rss version ="2.0" xmlns:g="http://base.google.com/ns/1.0">

</rss>

And here is my code:

<?php

$xml = new SimpleXMLElement('<rss></rss>');
$xml->addAttribute('version', '2.0');

$xml->addChild('channel');
$xml->channel->addChild('title', 'Removed');
$xml->channel->addChild('description', 'Removed');
$xml->channel->addChild('link', 'Removed');

foreach ($products as $product) {
    $item = $xml->channel->addChild('item');
    $item->addChild('title', htmlspecialchars($product['title']));
    $item->addChild('description', htmlspecialchars($product['title']));
    $item->addChild('link', $product['url']);
    $item->addChild('id', $product['product_id']);
    $item->addChild('price', $product['price_latest']);
    $item->addChild('brand', $product['range']);
    $item->addChild('condition', 'new');
    $item->addChild('image_link', $product['image']);
}

How do I introduce the g namespace, both the xmlns declaration in the root rss element, and then as a prefix for id, price, brand, condition and image_link in each item element?

Body:
This can be done by adding the namespace declaration into the root element creation along with adding the namespace to the addChild function.

The modification to the original code:

$products[] = array(
  "title" => "Foobar",
  "description" => "Foo",
  "url" => "https://f.oo.bar",
  "product_id" => "00001",
  "price_latest" => "$3.50",
  "range" => "Foo",
  "image" => "https://f.oo.bar/image.tiff",
);

$xml = new SimpleXMLElement('<rss xmlns:g="http://base.google.com/ns/1.0"/>');
$xml->addAttribute('version', '2.0');

$xml->addChild('channel');
$xml->channel->addChild('title', 'Removed');
$xml->channel->addChild('description', 'Removed');
$xml->channel->addChild('link', 'Removed');

foreach ($products as $product) {
    $item = $xml->channel->addChild('item');
    $item->addChild('title', htmlspecialchars($product['title']));
    $item->addChild('description', htmlspecialchars($product['title']));
    $item->addChild('link', $product['url']);
    $item->addChild('id', $product['product_id'], "http://base.google.com/ns/1.0");
    $item->addChild('price', $product['price_latest'], "http://base.google.com/ns/1.0");
    $item->addChild('brand', $product['range'], "http://base.google.com/ns/1.0");
    $item->addChild('condition', 'new', "http://base.google.com/ns/1.0");
    $item->addChild('image_link', $product['image'], "http://base.google.com/ns/1.0");
}

print_r($xml->asXML());

Would yield the response:

<?xml version="1.0"?>
<rss xmlns:g="http://base.google.com/ns/1.0" version="2.0">
  <channel>
    <title>Removed</title>
    <description>Removed</description>
    <link>Removed</link>
    <item>
      <title>Foobar</title>
      <description>Foobar</description><link/>
      <g:id>00001</g:id>
      <g:price>$3.50</g:price>
      <g:brand>Foo</g:brand>
      <g:condition>new</g:condition>
      <g:image_link>https://f.oo.bar/image.tiff</g:image_link>
    </item>
  </channel>
</rss>


问:
How SSH Tunnel from Windows VM to the host system, which is running Mac
I am trying to ssh tunnel from a Windows VM to the host system, which is running Mac.

I am running this command:

```<code>ssh -L 80:localhost:5454 10.0.2.2
</code>```

It then prompts me three times for a password like this:

```<code>Password:
Password:
Password:
</code>```

Each time I enter my password for the windows vm, and it then prompts me for another password:

```<code>John Smith@10.0.2.2's password:
</code>```

Now this I think is the password I am using for my Mac host system, but it says permission denied and thats it.

So my question is what are these passwords referring to? My ssh password? Even though I have never set one of these up.

Any help would be great!

答:
Because you have not specified otherwise - you are trying to use your Windows username to authenticate on the Mac.

I assume these username are not exactly the same.

From the Mac run

```<code>whoami
</code>```

Which will print out your exact username, then from Windows, add that username in front of the IP when connecting.

```<code>ssh macUser@10.0.2.2
    /\
</code>```

You will then be prompted for the password of the user on the mac.

Body:
I am trying to ssh tunnel from a Windows VM to the host system, which is running Mac.

I am running this command:

ssh -L 80:localhost:5454 10.0.2.2

It then prompts me three times for a password like this:

Password:
Password:
Password:

Each time I enter my password for the windows vm, and it then prompts me for another password:

John Smith@10.0.2.2's password:

Now this I think is the password I am using for my Mac host system, but it says permission denied and thats it.

So my question is what are these passwords referring to? My ssh password? Even though I have never set one of these up.

Any help would be great!

Body:
Because you have not specified otherwise - you are trying to use your Windows username to authenticate on the Mac.

I assume these username are not exactly the same.

From the Mac run

whoami

Which will print out your exact username, then from Windows, add that username in front of the IP when connecting.

ssh macUser@10.0.2.2
    /\

You will then be prompted for the password of the user on the mac.


问:
TDD FIRST principle
I am not understanding how the TDD FIRST principle isn't being adhered to in the following code.

These are my notes about the FIRST principle:

Fast: run (subset of) tests quickly (since you'll be running them all the time)

Independent: no tests depend on others, so can run any subset in any order

Repeatable: run N times, get same result (to help isolate bugs and enable automation)

Self-checking: test can automatically detect if passed (no human checking of output)

Timely: written about the same time as code under test (with TDD, written first!)

The quiz question:

Sally wants her website to have a special layout on the first Tuesday of every month. She has the following controller and test code:

```<code># HomeController
 def index
   if Time.now.tuesday?
     render 'special_index'
   else
     render 'index'
   end
 end

 # HomeControllerSpec
 it "should render special template on Tuesdays" do
   get 'index'
   if Time.now.tuesday?
     response.should render_template('special_index')
   else
     response.should render_template('index')
   end
 end
</code>```

What FIRST principle is not being followed?

Fast

Independent

Repeatable

Self-checking

Timely

I'm not sure which FIRST principle  is not being adhered to:

Fast: The code seems to be fast because there is nothing complex about its tests.

Independent: The test doesn't depend on other tests.

Repeatable: The test will get the same result every time. 'special_index' if it's Tuesday and 'index' if it's not Tuesday.

Self-checking: The test can automatically detect if it's passed.

Timely: Both the code and the test code are presented here at the same time.

I chose Timely on the quiz because the test code was presented after the controller code. But I got the question wrong, and in retrospect, this wasn't a good choice. I'm not sure which FIRST principle isn't being followed here.

答:
F.I.R.S.T., F.I.I.R.S.T. and FASRCS

Yes, the confusion partly has the reason, that the F.I.R.S.T. principle is not complete or concise enough concerning the "I". In courses I attended the principle was called F.I.I.R.S.T.

The second "I" stands for "Isolated". The test above is independent from other tests, but is not isolated in a separate class or project.

[Updated]:

Isolation can mean:

A unit tests isolates functionality out of a SUT (system under test). You can isolate functionality even out of one single function. This draws the line between unit tests or their relatives component tests and integration tests, and of course to system tests.

"Tests isolate failures. A developer should never have to reverse-engineer tests or the code being tested to know what went wrong. Each test class name and test method name with the text of the assertion should state exactly what is wrong and where." Ref.: History of FIRST principle

A unit test could be isolated from the SUT which it tests in a different developer artifact (class, package, development project) and/or delivery artifact (Dll, package, assembly).

Unit tests, testing the same SUT, especially their containing Asserts, should be isolated from each other in different test functions, but this is only a recommendation. Ideally each unit test contains only one assert.

Unit tests, testing different SUTs, should be isolated from each other or from other kind of tests of course further more in different classes or other mentioned artifacts.

Independence can mean:

Unit tests should not rely on each other (explicit independency), with the exception of special "setup" and "teardown" functions, but even this is subject for a discussion.

Especially unit tests should be order-independant (implicit independency). The result should not depend on unit tests executed before. While this sounds trivial, it isn't. There are tests which cannot avoid doing initializations and/or starting runtimes. Just one shared (e.g. class) variable and the SUT could react differently, if it was started before. You make an outside call to the operating system? Some dll will be loaded first time? You already have a potential dependency, at least on OS level- sometimes only minor, sometimes essential to not discover an error. It may be necessary to add cleanup code to reach optimal independency of tests.

Unit tests should be independant as much as possible from the runtime environment and not depend on a specific test environment or setting. This belongs also partly to "Repeatable".
No need to fillout twenty user dialogs before. No need to start the server. No need to make the database available. No need for another component. No need for a network. To accomplish that, often test doubles are used (stubs, mocks, fakes, dummies, spies, ..).

(Gerard Meszaros' classic work on: xUnit patterns, here coining the name 'test double' and defining different kinds of)

(Test double zoo quickly explained)

(Follow Martin Fowler 2007, thinking about stubs, mocks, etc. Classic)

While a unit test is never totally independant from it's SUT, ideally it should be independant as much as possible from the current implementation and only rely on the public interface of the function or class tested (SUT).

Conclusion: In this interpretations the word 'isolation' stresses more the physical location which often implies logical independence to some extent (e.g. class level isolation).

No completeness concerning potentially more accentuations and meanings claimed.

See also comments here.

But there are more properties of (good) unit tests: Roy Osherove found some more attributes in his book "The art of unit testing" which I don't find exactly in the F.I.I.R.S.T. principle (link to his book site), and which are cited here with my own words (and acronym):

Full control of SUT: the unit test should have full control of the SUT. I see this effectively identical as being independent from the test and runtime environment (e.g. using mocks, etc.). But because of independency is so ambigous, it makes sense to spend a separate letter.

Automated (related to repeatable and self-checking, but not the same)
identically). This one requires a test (runner) infrastructure.

Small, simple or in his words: "easy to implement" (again, related, but not identical). Often related to "Fast"

Relevant: The test should be relevant tomorrow. This one of the most difficult requirements to acchieve, and depending of the "school" there may be a need for temporary unit tests during TDD too. When a test is only testing the contracts, this is acchieved, but that may be not enough for high code coverage requirements.

Consistent result: Effectively a result of "enough" independency. Consistency is, what some people include in "Repeatable". There is an essential overlap, but they are not identical.

Self-explaining: In terms of naming, structure of the whole test, and specifically of the syntax of the assert as the key line, it should be clear what is tested, and what could be wrong if a test fails. Related to "Tests isolate failures", see above.

Given all these spedific points, it should be more clear than before, that it is all but simple to write (good) unit tests.

Title: TDD FIRST principle

Body:
I am not understanding how the TDD FIRST principle isn't being adhered to in the following code.

These are my notes about the FIRST principle:

Fast: run (subset of) tests quickly (since you'll be running them all the time)

Independent: no tests depend on others, so can run any subset in any order

Repeatable: run N times, get same result (to help isolate bugs and enable automation)

Self-checking: test can automatically detect if passed (no human checking of output)

Timely: written about the same time as code under test (with TDD, written first!)

The quiz question:

Sally wants her website to have a special layout on the first Tuesday of every month. She has the following controller and test code:

# HomeController
 def index
   if Time.now.tuesday?
     render 'special_index'
   else
     render 'index'
   end
 end

 # HomeControllerSpec
 it "should render special template on Tuesdays" do
   get 'index'
   if Time.now.tuesday?
     response.should render_template('special_index')
   else
     response.should render_template('index')
   end
 end

What FIRST principle is not being followed?

Fast

Independent

Repeatable

Self-checking

Timely

I'm not sure which FIRST principle  is not being adhered to:

Fast: The code seems to be fast because there is nothing complex about its tests.

Independent: The test doesn't depend on other tests.

Repeatable: The test will get the same result every time. 'special_index' if it's Tuesday and 'index' if it's not Tuesday.

Self-checking: The test can automatically detect if it's passed.

Timely: Both the code and the test code are presented here at the same time.

I chose Timely on the quiz because the test code was presented after the controller code. But I got the question wrong, and in retrospect, this wasn't a good choice. I'm not sure which FIRST principle isn't being followed here.


问:
On your very first program, which construct hooked you on programming?
To me it was the If statement, I'm psyched up, since then I believed that computers are very intelligent, or I can at least make it appear intelligent because of it.</p>

答:
Function pointers in C.

First I learned C, but not function pointers.

Then I began programming in assembler for about a semester in the university. I used function pointers then without even knowing about them. Somehow they seem like a natural thing in assembler for me. I had to explain them to my teachers a few times, because they didn't understand them :).

Then, I came back to C, and revelation hit me.

Now I laught at Java methods, generics, late polymorphism and such said "magic" things.

OwnerDisplayName: Michael Buen

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Triptych

OwnerDisplayName: alcortes


问:
How to cache everything but content using sw-precache
I'm using sw-precache in a jekyll website to add offline capabilities with the following configuration:

```<code>gulp.task('generate-service-worker', function(cb) {
  var path = require('path');
  var swPrecache = require('sw-precache');
  var rootDir = '_site';
  var packageJson = require('./package.json');

  swPrecache.write('./service-worker.js', {
    staticFileGlobs: [rootDir + '/**/*.{html,css,png,jpg,gif,svg}', rootDir + '/js/*'],
    stripPrefix: rootDir + '/',
    runtimeCaching: [{
      urlPattern: /\/$/,
      handler: 'networkOnly'
    }],
    handleFetch: argv.cacheAssets || false,
    maximumFileSizeToCacheInBytes: 10485760, // 10 mb
    cacheId: packageJson.name + '-v' + packageJson.version
  }, cb);
});
</code>```

The problem is that, when I change content in the website (for example, text in a blog post, or some text from the index page) the changes won't be shown until the new serviceworker version has been installed and the browser has been refreshed, which of course, is the expected behaviour of cacheFirst.

What I want is to make the request to the index of the site always network first, which is what I'm trying here:

```<code>runtimeCaching: [{
  urlPattern: /\/$/,
  handler: 'networkFirst'
}]
</code>```

But this isn't working, the index is always getting fetch from the serviceworker and not from network, how can I accomplish this?

答:
My problem is that I was including the actual page contents for precache: '/**/*.{html,css,png,jpg,gif,svg}'.

Excluding the html files works as expected:

```<code>'/**/*.{css,png,jpg,gif,svg}'
</code>```

Body:
I'm using sw-precache in a jekyll website to add offline capabilities with the following configuration:

gulp.task('generate-service-worker', function(cb) {
  var path = require('path');
  var swPrecache = require('sw-precache');
  var rootDir = '_site';
  var packageJson = require('./package.json');

  swPrecache.write('./service-worker.js', {
    staticFileGlobs: [rootDir + '/**/*.{html,css,png,jpg,gif,svg}', rootDir + '/js/*'],
    stripPrefix: rootDir + '/',
    runtimeCaching: [{
      urlPattern: /\/$/,
      handler: 'networkOnly'
    }],
    handleFetch: argv.cacheAssets || false,
    maximumFileSizeToCacheInBytes: 10485760, // 10 mb
    cacheId: packageJson.name + '-v' + packageJson.version
  }, cb);
});

The problem is that, when I change content in the website (for example, text in a blog post, or some text from the index page) the changes won't be shown until the new serviceworker version has been installed and the browser has been refreshed, which of course, is the expected behaviour of cacheFirst.

What I want is to make the request to the index of the site always network first, which is what I'm trying here:

runtimeCaching: [{
  urlPattern: /\/$/,
  handler: 'networkFirst'
}]

But this isn't working, the index is always getting fetch from the serviceworker and not from network, how can I accomplish this?

Body:
My problem is that I was including the actual page contents for precache: '/**/*.{html,css,png,jpg,gif,svg}'.

Excluding the html files works as expected:

'/**/*.{css,png,jpg,gif,svg}'


问:
Too many concurrently fired triggers (increase MaxNoOfFiredTriggers) from NDBCLUSTER
I'm making batch operations with MySQL Cluster NDB: insertion of 10000 or 5000 rows and removal in a single transaction. Insert works fine, but removal fails with an exception:

```<code>java.sql.SQLException: Got temporary error 221 'Too many concurrently fired triggers (increase MaxNoOfFiredTriggers)' from NDBCLUSTER
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1086) ~[mysql-connector-java-5.1.29-bin.jar:na]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4237) ~[mysql-connector-java-5.1.29-bin.jar:na]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4169) ~[mysql-connector-java-5.1.29-bin.jar:na]
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2617) ~[mysql-connector-java-5.1.29-bin.jar:na]
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2778) ~[mysql-connector-java-5.1.29-bin.jar:na]
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2828) ~[mysql-connector-java-5.1.29-bin.jar:na]
at com.mysql.jdbc.ConnectionImpl.commit(ConnectionImpl.java:1748) ~[mysql-connector-java-5.1.29-bin.jar:na]
at com.mchange.v2.c3p0.impl.NewProxyConnection.commit(NewProxyConnection.java:981) ~[c3p0-0.9.5.1.jar:0.9.5.1]
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.doCommit(JdbcTransaction.java:112) [hibernate-core-4.1.0.Final.jar:4.1.0.Final]
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:178) [hibernate-core-4.1.0.Final.jar:4.1.0.Final]
</code>```

Attempt to increase MaxNoOfFiredTriggers didn't result in any change of behaviour.

Sure I could split transactions into smaller batches, but 5000 rows doesn't sound that huge for a number and especially strange that insert is actually working fine.

答:
I think you are not taking the triggers fired to enforce the Foreign Key constraints into consideration while setting the MaxNoOfFiredTriggers.

Since the insertions are fine and the deletion is not, my guess is that atleast one column of the table you are doing DMLs on is being referred by another column (from the same or a different table) as a part of an FK relationship.

For example consider the following tables,

create table parent(id int, unique uk1(id) using hash) engine ndb;

create table child(id_ref int, foreign key fk1(id_ref) references parent(id)) engine ndb;

Now, when you are doing an insertion into the parent table, triggers will be fired in the backend to update the unique index uk1. But no FK triggers are needed here as there is nothing to check.

But when you are deleting from the parent table, the FK constraint has to be enforced. Deletion should be allowed iff the child table doesn't have the value that is being deleted from the parent. This might vary if the FK constraint had an on update cascade clause - in that case, the tuples with the same value being deleted from the parent has also to be deleted in the child.

All this is enforced through FK triggers. So during deletion from parent, in addition to the triggers fired to update the hash index, Foreign Key triggers will also be fired. In this case, for every row two triggers will be fired. So if you are deleting 5000 rows in batch in this setup, you would need atleast 10K maxNoOfFiredTriggers allowance. With multiple Foreign Keys and having multiple level of Foreign Key dependencies, this calculation will vary. So you have to check your schema for all Foreign Key dependencies and calculate MaxNoOfFiredTriggers accordingly.

Body:
I'm making batch operations with MySQL Cluster NDB: insertion of 10000 or 5000 rows and removal in a single transaction. Insert works fine, but removal fails with an exception:

java.sql.SQLException: Got temporary error 221 'Too many concurrently fired triggers (increase MaxNoOfFiredTriggers)' from NDBCLUSTER
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1086) ~[mysql-connector-java-5.1.29-bin.jar:na]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4237) ~[mysql-connector-java-5.1.29-bin.jar:na]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4169) ~[mysql-connector-java-5.1.29-bin.jar:na]
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2617) ~[mysql-connector-java-5.1.29-bin.jar:na]
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2778) ~[mysql-connector-java-5.1.29-bin.jar:na]
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2828) ~[mysql-connector-java-5.1.29-bin.jar:na]
at com.mysql.jdbc.ConnectionImpl.commit(ConnectionImpl.java:1748) ~[mysql-connector-java-5.1.29-bin.jar:na]
at com.mchange.v2.c3p0.impl.NewProxyConnection.commit(NewProxyConnection.java:981) ~[c3p0-0.9.5.1.jar:0.9.5.1]
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.doCommit(JdbcTransaction.java:112) [hibernate-core-4.1.0.Final.jar:4.1.0.Final]
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:178) [hibernate-core-4.1.0.Final.jar:4.1.0.Final]

Attempt to increase MaxNoOfFiredTriggers didn't result in any change of behaviour.

Sure I could split transactions into smaller batches, but 5000 rows doesn't sound that huge for a number and especially strange that insert is actually working fine.