问:
Changed rules for protected constructors in C++17?
I have this test case:

```<code>struct A{ protected: A(){} };
struct B: A{};
struct C: A{ C(){} };
struct D: A{ D() = default; };

int main(){
    (void)B{};
    (void)C{};
    (void)D{};
}
</code>```

Both gcc and clang compile it in C++11 and C++14 mode. Both fail in C++17 mode:

```<code>$ clang++ -std=c++17 main.cpp
main.cpp:7:10: error: base class 'A' has protected default constructor
        (void)B{};
                ^
main.cpp:1:22: note: declared protected here
struct A{ protected: A(){} };
                     ^
main.cpp:9:10: error: base class 'A' has protected default constructor
        (void)D{};
                ^
main.cpp:1:22: note: declared protected here
struct A{ protected: A(){} };
                     ^
2 errors generated.

$ clang++ --version
clang version 6.0.0 (http://llvm.org/git/clang.git 96c9689f478d292390b76efcea35d87cbad3f44d) (http://llvm.org/git/llvm.git 360f53a441902d19ce27d070ad028005bc323e61)
Target: x86_64-unknown-linux-gnu
Thread model: posix
</code>```

(clang compiled from master Branch 2017-12-05.)

```<code>$ g++ -std=c++17 main.cpp
main.cpp: In function 'int main()':
main.cpp:7:10: error: 'A::A()' is protected within this context
  (void)B{};
          ^
main.cpp:1:22: note: declared protected here
 struct A{ protected: A(){} };
                      ^
main.cpp:9:10: error: 'A::A()' is protected within this context
  (void)D{};
          ^
main.cpp:1:22: note: declared protected here
 struct A{ protected: A(){} };
                      ^

$ g++ --version
g++ (GCC) 8.0.0 20171201 (experimental)
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
</code>```

Is this change of behavior part of C++17 or is it a bug in both compilers?

答:
The definition of aggregate changed since C++17.

Before C++17

no base classes

Since C++17

no virtual, private, or protected (since C++17) base classes

That means, for B and D, they're not aggregate type before C++17, then for B{} and D{}, value-initialization will be performed, then the defaulted default constructor will be called; which is fine, because the protected constructor of base class could be called by derived class's constructor.

Since C++17, B and D become aggregate type (because they have only public base class, and note that for class D, the explicitly defaulted default constructor is allowed for aggregate type since C++11), then for B{} and D{}, aggregate-initialization will be performed,

Each direct public base, (since C++17) array element, or non-static class member, in order of array subscript/appearance in the class definition, is copy-initialized from the corresponding clause of the initializer list.

If the number of initializer clauses is less than the number of members and bases (since C++17) or initializer list is completely empty, the remaining members and bases (since C++17) are initialized by their default initializers, if provided in the class definition, and otherwise (since C++14) by empty lists, in accordance with the usual list-initialization rules (which performs value-initialization for non-class types and non-aggregate classes with default constructors, and aggregate initialization for aggregates). If a member of a reference type is one of these remaining members, the program is ill-formed.

That means the base class subobject will be value-initialized directly, the constructor of B and D are bypassed; but the default constructor of A is protected, then the code fails. (Note that A is not aggregate type because it has a user-provided constructor.)

BTW: C (with a user-provided constructor) is not an aggregate type before and after C++17, so it's fine for both cases.

Body:
I have this test case:

struct A{ protected: A(){} };
struct B: A{};
struct C: A{ C(){} };
struct D: A{ D() = default; };

int main(){
    (void)B{};
    (void)C{};
    (void)D{};
}

Both gcc and clang compile it in C++11 and C++14 mode. Both fail in C++17 mode:

$ clang++ -std=c++17 main.cpp
main.cpp:7:10: error: base class 'A' has protected default constructor
        (void)B{};
                ^
main.cpp:1:22: note: declared protected here
struct A{ protected: A(){} };
                     ^
main.cpp:9:10: error: base class 'A' has protected default constructor
        (void)D{};
                ^
main.cpp:1:22: note: declared protected here
struct A{ protected: A(){} };
                     ^
2 errors generated.

$ clang++ --version
clang version 6.0.0 (http://llvm.org/git/clang.git 96c9689f478d292390b76efcea35d87cbad3f44d) (http://llvm.org/git/llvm.git 360f53a441902d19ce27d070ad028005bc323e61)
Target: x86_64-unknown-linux-gnu
Thread model: posix

(clang compiled from master Branch 2017-12-05.)

$ g++ -std=c++17 main.cpp
main.cpp: In function 'int main()':
main.cpp:7:10: error: 'A::A()' is protected within this context
  (void)B{};
          ^
main.cpp:1:22: note: declared protected here
 struct A{ protected: A(){} };
                      ^
main.cpp:9:10: error: 'A::A()' is protected within this context
  (void)D{};
          ^
main.cpp:1:22: note: declared protected here
 struct A{ protected: A(){} };
                      ^

$ g++ --version
g++ (GCC) 8.0.0 20171201 (experimental)
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Is this change of behavior part of C++17 or is it a bug in both compilers?


来源: stackexchange

问:
Unable to display Upvote/Downvote count in Rail app views
I'm currently using the 'acts_as_votable' Ruby gem to give the Upvote/Downvote function to comments in a basic rails app. In the comments_controller.rb the functions look like this:

```<code>    def upvote
      @comment = Comment.find(params[:id])
      @comment.upvote_by current_user
      redirect_to comments_path
    end

    def downvote
      @comment = Comment.find(params[:id])
      @comment.downvote_by current_user
      redirect_to comment_path
    end
</code>```

and in the roputes.rb:

```<code>  resources :comments do
    member do
     put "like", to: "comments#upvote"
     put "dislike", to: "comments#downvote"
    end
  end
</code>```

and the loop in the views looks like this:

```<code> <div class="box">
 <% @comment.each do |w| %>
    <tr>
      <td><b><%= w.title %></b></td><br>
      <td><%= w.location %></td><br>
      <td><%= w.body %></td><br>
      <%= link_to "upvote", like_comment_path(w), method: :put %>
      <%= @comment.upvote_by.size %>
      <%= link_to "downvote", dislike_comment_path(w), method: :put %>
      </tr>
    <% end %>
 </div>
</code>```

There are no problems with this, except for with this line of code:

```<code><%= @comment.upvote_by.size %>
</code>```

which is returning the following error:

```<code>undefined method `upvote_by' for #
<Comment::ActiveRecord_Relation:0x007faa8dbf0560>
</code>```

I'm not sure why the method is undefined as I assume this is either a method that is built in to the gem, or a ruby method. I also don't know if this is an error message that is thrown up for some other reason, but I'm not sure what this could be. I've tried to use 'upvote_from' instead but this didn't work. If I remove the line then the app runs fine.

I can't work out what else could be causing this, so I would really appreciate some help here, thanks.

答:
Don't forget to run the migrations :

```<code>rails generate acts_as_votable:migration
rake db:migrate
</code>```

Add this in your comment model ( comment.rb )

```<code>acts_as_votable
</code>```

More details in the doc

Database Migrations

Acts As Votable uses a votes table to store all voting information. To
  generate and run the migration just use.

rails generate acts_as_votable:migration rake db:migrate

You will get a performance increase by adding in cached columns to
  your model's tables. You will have to do this manually through your
  own migrations. See the caching section of this document for more
  information.

Usage Votable Models

class Post < ActiveRecord::Base

     acts_as_votable

end

ContentLicense: CC BY-SA 3.0

Body:
I'm currently using the 'acts_as_votable' Ruby gem to give the Upvote/Downvote function to comments in a basic rails app. In the comments_controller.rb the functions look like this:

    def upvote
      @comment = Comment.find(params[:id])
      @comment.upvote_by current_user
      redirect_to comments_path
    end

    def downvote
      @comment = Comment.find(params[:id])
      @comment.downvote_by current_user
      redirect_to comment_path
    end

and in the roputes.rb:

  resources :comments do
    member do
     put "like", to: "comments#upvote"
     put "dislike", to: "comments#downvote"
    end
  end

and the loop in the views looks like this:

 <% @comment.each do |w| %>

      <%= w.title %>

      <%= w.location %>

      <%= w.body %>

      <%= link_to "upvote", like_comment_path(w), method: :put %>
      <%= @comment.upvote_by.size %>
      <%= link_to "downvote", dislike_comment_path(w), method: :put %>

    <% end %>

There are no problems with this, except for with this line of code:

<%= @comment.upvote_by.size %>

which is returning the following error:

undefined method `upvote_by' for #
<Comment::ActiveRecord_Relation:0x007faa8dbf0560>

I'm not sure why the method is undefined as I assume this is either a method that is built in to the gem, or a ruby method. I also don't know if this is an error message that is thrown up for some other reason, but I'm not sure what this could be. I've tried to use 'upvote_from' instead but this didn't work. If I remove the line then the app runs fine.

I can't work out what else could be causing this, so I would really appreciate some help here, thanks.

Body:
Don't forget to run the migrations :

rails generate acts_as_votable:migration
rake db:migrate

Add this in your comment model ( comment.rb )

acts_as_votable

More details in the doc

Database Migrations

Acts As Votable uses a votes table to store all voting information. To
  generate and run the migration just use.

rails generate acts_as_votable:migration rake db:migrate

You will get a performance increase by adding in cached columns to
  your model's tables. You will have to do this manually through your
  own migrations. See the caching section of this document for more
  information.

Usage Votable Models

class Post < ActiveRecord::Base

     acts_as_votable

end


问:
Reverse URL in Django 2.0
The new Django 2.0 update broke my way of reversing url and printing it to the template. Using regular expression, it would work fine but when using the new simplified way, it returns an error.

```<code>NoReverseMatch at /blog/archive/
Reverse for 'article' with keyword arguments '{'id': 1}' not found. 1 pattern(s) tried: ['blog/article/<int:id>/$']
</code>```

Here is what I use to print the url,

```<code><h3 class="item-title"><a href="{% url 'blog:article' id=article.id %}">{{ article.title }}</a></h3>
</code>```

Here is the url pattern,

```<code>    url(r'^blog/article/<int:id>/$', views.article, name='article'),
</code>```

and here is the article function,

```<code>def article(request, id):
    try:
        article = Article.objects.get(id=id)
    except ObjectDoesNotExist:
        article = None

    context = {
        'article': article,
        'error': None,
    }

    if not article:
        context['error'] = 'Oops! It seems that the article you requested does not exist!'

    return render(request, 'blog/article.html', context)
</code>```

I haven't found a solution to this yet. Hopefully this post will help others.

答:
In Django 2.0, url() is an alias for re_path() and still uses regular expressions.

Use path() for the simplified syntax.

```<code>from django.urls import path

urlpatterns = [
    path(r'^blog/article/<int:id>/$', views.article, name='article'),
]
</code>```

Title: Reverse URL in Django 2.0

Body:
The new Django 2.0 update broke my way of reversing url and printing it to the template. Using regular expression, it would work fine but when using the new simplified way, it returns an error.

NoReverseMatch at /blog/archive/
Reverse for 'article' with keyword arguments '{'id': 1}' not found. 1 pattern(s) tried: ['blog/article/<int:id>/$']

Here is what I use to print the url,

{{ article.title }}

Here is the url pattern,

    url(r'^blog/article/<int:id>/$', views.article, name='article'),

and here is the article function,

def article(request, id):
    try:
        article = Article.objects.get(id=id)
    except ObjectDoesNotExist:
        article = None

    context = {
        'article': article,
        'error': None,
    }

    if not article:
        context['error'] = 'Oops! It seems that the article you requested does not exist!'

    return render(request, 'blog/article.html', context)

I haven't found a solution to this yet. Hopefully this post will help others.

Body:
In Django 2.0, url() is an alias for re_path() and still uses regular expressions.

Use path() for the simplified syntax.

from django.urls import path

urlpatterns = [
    path(r'^blog/article/<int:id>/$', views.article, name='article'),
]


问:
What my Regexp should be?
I am trying to get all check constraints from string definition looking like this

```<code>  CREATE TABLE products(
     id INT PRIMARY KEY     NOT NULL,
     price         REAL,
     title         TEXT,
     CONSTRAINT price_check CHECK (  price > 0),
     constraint title_check CHECK (length(title) > 5 AND (price <= 100.0))
  );
</code>```

with following regexp /CONSTRAINT\s+(\w+)\s+CHECK\s+\((.+?)\)/i but it does't match second constraint, only constraint title_check CHECK (length(title) part of it.

How should I change my regexp (if can at all) to get this to work? Specific language dialect of regexp doesn't matter. Thanks for help.

答: console.log("CREATE TABLE products(\nid INT PRIMARYNULL,\npriceREAL,\ntitleTEXT,\nCONSTRAINT price_check CHECK (  price > 0),\nconstraint title_check CHECK (length(title) > 5 AND (price <= 100.0))\n  );".match(/^.*constraint.*check.*$/gim));```

Title: What my Regexp should be?

Body:
I am trying to get all check constraints from string definition looking like this

  CREATE TABLE products(
     id INT PRIMARY KEY     NOT NULL,
     price         REAL,
     title         TEXT,
     CONSTRAINT price_check CHECK (  price > 0),
     constraint title_check CHECK (length(title) > 5 AND (price <= 100.0))
  );

with following regexp /CONSTRAINT\s+(\w+)\s+CHECK\s+\((.+?)\)/i but it does't match second constraint, only constraint title_check CHECK (length(title) part of it.

How should I change my regexp (if can at all) to get this to work? Specific language dialect of regexp doesn't matter. Thanks for help.


问:
Liquibase Index "PRIMARY_KEY_xx" belongs to a constraint
I have the following table (let's call it TBL), that I'm trying to remove a primary key from. Underlying DB is H2.

```<code><createTable tableName="TBL">
        <column name="ID" type="BIGINT">
            <constraints primaryKey="true" primaryKeyName="TBL_PK"/>
        </column>
        ...
</code>```

Trying to use the following script in a later changeset, I run into the error below.

```<code><dropPrimaryKey tableName="TBL" constraintName="TBL_PK" />
</code>```

Error:

```<code>Caused by: org.h2.jdbc.JdbcSQLException: Index "PRIMARY_KEY_xx" belongs to a constraint; SQL statement:
ALTER TABLE TBL DROP PRIMARY KEY [90085-140]
</code>```

Any idea what I am missing?

I know that there is dropIndex, but I don't know how to target the PRIMARY_KEY_xx (to stay generic for later stages).

答:
I guess that problem is with H2 db. When you create PK it creates some constraint(s).
Try to find it with query:

select * from information_schema.constraints where table_name='TBL' and column_list='ID'

Body:
I have the following table (let's call it TBL), that I'm trying to remove a primary key from. Underlying DB is H2.

<createTable tableName="TBL">
        <column name="ID" type="BIGINT">
            <constraints primaryKey="true" primaryKeyName="TBL_PK"/>
        </column>
        ...

Trying to use the following script in a later changeset, I run into the error below.

<dropPrimaryKey tableName="TBL" constraintName="TBL_PK" />

Error:

Caused by: org.h2.jdbc.JdbcSQLException: Index "PRIMARY_KEY_xx" belongs to a constraint; SQL statement:
ALTER TABLE TBL DROP PRIMARY KEY [90085-140]

Any idea what I am missing?

I know that there is dropIndex, but I don't know how to target the PRIMARY_KEY_xx (to stay generic for later stages).


问:
Laravel 5.5 - login explained?
My problem, or rather question is regarding the actual Login function of the builtin Authenthication feature by Laravel (v5.5).

I simply do not understand where the magic happens regarding logging the user into the system.

Here the login method within the LoginController

```<code>public function login(Request $request)
    {
        $this->validateLogin($request);

        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }

        if ($this->attemptLogin($request)) {
            return $this->sendLoginResponse($request);
        }

        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }
</code>```

and here the attemptedLogin method butthis one still does not give me any closure.

```<code>protected function attemptLogin(Request $request)
{
    return $this->guard()->attempt(
        $this->credentials($request), $request->filled('remember')
    );
}
</code>```

Can ANYONE explain to me where exactly in laravel a user gets logged in into the application? i cant read it out of the documentation either.
Either i'm too blind or stupid but i really do not see it.

Thanks in advance!

答:
```<code>protected function sendLoginResponse(Request $request)
{
    $request->session()->regenerate();
    $this->clearLoginAttempts($request);
    return $this->authenticated($request, $this->guard()->user())
            ?: redirect()->intended($this->redirectPath());
}
</code>```

in /src/Illuminate/Foundation/Auth/AuthenticatesUsers.php

this is where the user finally gets logged in to the session.

You could also just add Auth::loginUsingId($userId) with the right user id to login a user. (Thats not safe)

Title: Laravel 5.5 - login explained?

Body:
My problem, or rather question is regarding the actual Login function of the builtin Authenthication feature by Laravel (v5.5).

I simply do not understand where the magic happens regarding logging the user into the system.

Here the login method within the LoginController

public function login(Request $request)
    {
        $this->validateLogin($request);

        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }

        if ($this->attemptLogin($request)) {
            return $this->sendLoginResponse($request);
        }

        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }

and here the attemptedLogin method butthis one still does not give me any closure.

protected function attemptLogin(Request $request)
{
    return $this->guard()->attempt(
        $this->credentials($request), $request->filled('remember')
    );
}

Can ANYONE explain to me where exactly in laravel a user gets logged in into the application? i cant read it out of the documentation either.
Either i'm too blind or stupid but i really do not see it.

Thanks in advance!

Body:
protected function sendLoginResponse(Request $request)
{
    $request->session()->regenerate();
    $this->clearLoginAttempts($request);
    return $this->authenticated($request, $this->guard()->user())
            ?: redirect()->intended($this->redirectPath());
}

in /src/Illuminate/Foundation/Auth/AuthenticatesUsers.php

this is where the user finally gets logged in to the session.

You could also just add Auth::loginUsingId($userId) with the right user id to login a user. (Thats not safe)


问:
How to query huge MySQL databases?
I have 2 tables, a purchases table and a users table. Records in the purchases table looks like this:

```<code>purchase_id | product_ids | customer_id
---------------------------------------
1           | (99)(34)(2) | 3
2           | (45)(3)(74) | 75
</code>```

Users table looks like this:

```<code>user_id  | email              | password
----------------------------------------
3        | joeShmoe@gmail.com | password
75       | nolaHue@aol.com    | password
</code>```

To get the purchase history of a user I use a query like this:

```<code>mysql_query(" SELECT * FROM purchases WHERE customer_id = '$users_id' ");
</code>```

The problem is, what will happen when tens of thousands of records are inserted into the purchases table. I feel like this will take a performance toll.

So I was thinking about storing the purchases in an additional field directly in the user's row:

```<code>user_id | email              | password  | purchases
------------------------------------------------------
1       | joeShmoe@gmail.com | password  | (99)(34)(2)
2       | nolaHue@aol.com    | password  | (45)(3)(74)
</code>```

And when I query the user's table for things like username, etc. I can just as easily grab their purchase history using that one query.

Is this a good idea, will it help better performance or will the benefit be insignificant and not worth making the database look messier?

I really want to know what the pros do in these situations, for example how does amazon query it's database for user's purchase history since they have millions of customers. How come there queries don't take hours?

EDIT

Ok, so I guess keeping them separate is the way to go. Now the question is a design one:

Should I keep using the "purchases" table I illustrated earlier. In that design I am separating the product ids of each purchase using parenthesis and using this as the delimiter to tell the ids apart when extracting them via PHP.

Instead should I be storing each product id separately in the "purchases" table so it looks like this?:

```<code>purchase_id | product_ids | customer_id
---------------------------------------
1           | 99          | 3
1           | 34          | 3
1           | 2           | 3
2           | 45          | 75
2           | 3           | 75
2           | 74          | 75
</code>```

答:
Your database already looks messy, since you are storing multiple product_ids in a single field, instead of creating an "association" table like this.

```<code>_____product_purchases____
purchase_id | product_id |
--------------------------
          1 |         99 |
          1 |         34 |
          1 |          2 |
</code>```

You can still fetch it in one query:

```<code>SELECT * FROM purchases p LEFT JOIN product_purchases pp USING (purchase_id)
   WHERE purchases.customer_id = $user_id
</code>```

But this also gives you more possibilities, like finding out how many product #99 were bought, getting a list of all customers that purchased product #34 etc.

And of course don't forget about indexes, that will make all of this much faster.

ContentLicense: CC BY-SA 2.5

Title: How to query huge MySQL databases?

Body:
I have 2 tables, a purchases table and a users table. Records in the purchases table looks like this:

purchase_id | product_ids | customer_id
---------------------------------------
1           | (99)(34)(2) | 3
2           | (45)(3)(74) | 75

Users table looks like this:

user_id  | email              | password
----------------------------------------
3        | joeShmoe@gmail.com | password
75       | nolaHue@aol.com    | password

To get the purchase history of a user I use a query like this:

mysql_query(" SELECT * FROM purchases WHERE customer_id = '$users_id' ");

The problem is, what will happen when tens of thousands of records are inserted into the purchases table. I feel like this will take a performance toll.

So I was thinking about storing the purchases in an additional field directly in the user's row:

user_id | email              | password  | purchases
------------------------------------------------------
1       | joeShmoe@gmail.com | password  | (99)(34)(2)
2       | nolaHue@aol.com    | password  | (45)(3)(74)

And when I query the user's table for things like username, etc. I can just as easily grab their purchase history using that one query.

Is this a good idea, will it help better performance or will the benefit be insignificant and not worth making the database look messier?

I really want to know what the pros do in these situations, for example how does amazon query it's database for user's purchase history since they have millions of customers. How come there queries don't take hours?

EDIT

Ok, so I guess keeping them separate is the way to go. Now the question is a design one:

Should I keep using the "purchases" table I illustrated earlier. In that design I am separating the product ids of each purchase using parenthesis and using this as the delimiter to tell the ids apart when extracting them via PHP.

Instead should I be storing each product id separately in the "purchases" table so it looks like this?:

purchase_id | product_ids | customer_id
---------------------------------------
1           | 99          | 3
1           | 34          | 3
1           | 2           | 3
2           | 45          | 75
2           | 3           | 75
2           | 74          | 75

Body:
Your database already looks messy, since you are storing multiple product_ids in a single field, instead of creating an "association" table like this.

_____product_purchases____
purchase_id | product_id |
--------------------------
          1 |         99 |
          1 |         34 |
          1 |          2 |

You can still fetch it in one query:

SELECT * FROM purchases p LEFT JOIN product_purchases pp USING (purchase_id)
   WHERE purchases.customer_id = $user_id

But this also gives you more possibilities, like finding out how many product #99 were bought, getting a list of all customers that purchased product #34 etc.

And of course don't forget about indexes, that will make all of this much faster.


问:
awk : extracting a data which is on several lines
so I have a file that looks like this :

```<code>/translation="MDGVTQQNAALVQEATTAAASLEEQARNLTAAVAAFDLGDKQTV
                 LITPRAAVPALKRPALKASLPASSSHGNWETF"
                 /product="Methyl-accepting chemotaxis protein I (serine
                 chemoreceptor protein)"
 CDS             complement(471..590)
                 /db_xref="SEED:fig|1240086.14.peg.2"
                 /translation="MHQYQSAILAKICRYGGIEKPEITPASVYKLDSHWRYVI"
                 /product="hypothetical protein"
 CDS             717..2354
                 /db_xref="SEED:fig|1240086.14.peg.3"
                 /translation="MGFFVVLWGGASGFSLYSLKQVTTLLHDNSTQGRTYTYLVYGND
                 QYFRSVTRMARVMDYSQFSDAAIASLEEQAQQLTKAVEVFHLGSEYQTAAS
                 RTRPAGNMALKRPALSGMAPALPPARTASDEGSWEKF"
                 /product="Methyl-accepting chemotaxis protein I (serine
                 chemoreceptor protein)"
                 /product="macromolecule metabolism; macromolecule
                 degradation; degradation of proteins, peptides,
                 glycopeptides"
</code>```

I need to extract the text that is between quotes after a "/product=", so I need this :

```<code>Methyl-accepting chemotaxis protein I (serine chemoreceptor protein)
hypothetical protein
Methyl-accepting chemotaxis protein I (serine chemoreceptor protein)
macromolecule metabolism; macromolecule degradation; degradation of proteins, peptides, glycopeptides
</code>```

I have to use awk, so I wrote this :

```<code>awk '/\/product/ {split($0, a, "\""); printf a[2] "\n"}'
</code>```

but this only takes the info on the same line as "/product", and some times the info is on two or three lines.. I'm out of ideas as to how to get the entire info between the quotes, anyone can help?

答:
awk to the rescue!  needs multi-char RS support (gawk)

```<code>$ awk -v RS='/| CDS' -F'"' '/^product/{gsub("\n +"," "); print $2}' file

Methyl-accepting chemotaxis protein I (serine chemoreceptor protein)
hypothetical protein
Methyl-accepting chemotaxis protein I (serine chemoreceptor protein)
macromolecule metabolism; macromolecule degradation; degradation of proteins, peptides, glycopeptides
</code>```

Explanation
set the record structure (either starts with "/" or " CDS", find related records (starting with product), trim extra spaces and print the field between two quotes (second field based on set field delimiter to double quotes).

Body:
so I have a file that looks like this :

/translation="MDGVTQQNAALVQEATTAAASLEEQARNLTAAVAAFDLGDKQTV
                 LITPRAAVPALKRPALKASLPASSSHGNWETF"
                 /product="Methyl-accepting chemotaxis protein I (serine
                 chemoreceptor protein)"
 CDS             complement(471..590)
                 /db_xref="SEED:fig|1240086.14.peg.2"
                 /translation="MHQYQSAILAKICRYGGIEKPEITPASVYKLDSHWRYVI"
                 /product="hypothetical protein"
 CDS             717..2354
                 /db_xref="SEED:fig|1240086.14.peg.3"
                 /translation="MGFFVVLWGGASGFSLYSLKQVTTLLHDNSTQGRTYTYLVYGND
                 QYFRSVTRMARVMDYSQFSDAAIASLEEQAQQLTKAVEVFHLGSEYQTAAS
                 RTRPAGNMALKRPALSGMAPALPPARTASDEGSWEKF"
                 /product="Methyl-accepting chemotaxis protein I (serine
                 chemoreceptor protein)"
                 /product="macromolecule metabolism; macromolecule
                 degradation; degradation of proteins, peptides,
                 glycopeptides"

I need to extract the text that is between quotes after a "/product=", so I need this :

Methyl-accepting chemotaxis protein I (serine chemoreceptor protein)
hypothetical protein
Methyl-accepting chemotaxis protein I (serine chemoreceptor protein)
macromolecule metabolism; macromolecule degradation; degradation of proteins, peptides, glycopeptides

I have to use awk, so I wrote this :

awk '/\/product/ {split($0, a, "\""); printf a[2] "\n"}'

but this only takes the info on the same line as "/product", and some times the info is on two or three lines.. I'm out of ideas as to how to get the entire info between the quotes, anyone can help?

Body:
awk to the rescue!  needs multi-char RS support (gawk)

$ awk -v RS='/| CDS' -F'"' '/^product/{gsub("\n +"," "); print $2}' file

Methyl-accepting chemotaxis protein I (serine chemoreceptor protein)
hypothetical protein
Methyl-accepting chemotaxis protein I (serine chemoreceptor protein)
macromolecule metabolism; macromolecule degradation; degradation of proteins, peptides, glycopeptides

Explanation
set the record structure (either starts with "/" or " CDS", find related records (starting with product), trim extra spaces and print the field between two quotes (second field based on set field delimiter to double quotes).


问:
Have a good hash function for a C++ hash table?
I am in need of a performance-oriented hash function implementation in C++ for a hash table that I will be coding. I looked around already and only found questions asking what's a good hash function "in general". I've considered CRC32 (but where to find good implementation?) and a few cryptography algorithms. My table, though, has very specific requirements.

Here's what the table will be like:

```<code>100,000 items max
200,000 capacity (so the load is 0.5)
hashing a 6-character string which is a part of English sentence
     examples: "become"    "and he"    ", not "
</code>```

The number one priority of my hash table is quick search (retrieval). Quick insertion is not important, but it will come along with quick search. Deletion is not important, and re-hashing is not something I'll be looking into. To handle collisions, I'll be probably using separate chaining as described here. I have already looked at this article, but would like an opinion of those who have handled such task before.

答:
Since C++11, C++ has provided a std::hash< string >( string ). That is likely to be an efficient hashing function that provides a good distribution of hash-codes for most strings.

Furthermore, if you are thinking of implementing a hash-table, you should now be considering using a C++ std::unordered_map instead.

OwnerDisplayName: DV

Body:
I am in need of a performance-oriented hash function implementation in C++ for a hash table that I will be coding. I looked around already and only found questions asking what's a good hash function "in general". I've considered CRC32 (but where to find good implementation?) and a few cryptography algorithms. My table, though, has very specific requirements.

Here's what the table will be like:

100,000 items max
200,000 capacity (so the load is 0.5)
hashing a 6-character string which is a part of English sentence
     examples: "become"    "and he"    ", not "

The number one priority of my hash table is quick search (retrieval). Quick insertion is not important, but it will come along with quick search. Deletion is not important, and re-hashing is not something I'll be looking into. To handle collisions, I'll be probably using separate chaining as described here. I have already looked at this article, but would like an opinion of those who have handled such task before.

LastEditorDisplayName: sth

ContentLicense: CC BY-SA 4.0


问:
Unable to load non-winning models in automl() use case
I'm using automl function with code snippet shown below

```<code>h2o.init()
h2o_train = as.h2o(train)
h2o_test = as.h2o(test)
aml <- h2o.automl(x=x, y=y, training_frame=h2o_train, leaderboard_frame=h2o_test)
print(aml@leaderboard)  # view top models
print(getParms(aml@leader))  #  get related info for top1 model
</code>```

After read through the doc, I couldn't find how to load the results for other models, the leaderboard shows their model_id. It would be valuable if we can load those models, or at least see their parameters.

答:
To get any model you can do m <- h2o.getModel(model_id). The model_id can be any model id from the leaderboard.

To see the list of non-default parameters, you can do h2o.getModel(model_id)@parameters or h2o.getModel(model_id)@allparameters to see all parameters, including default values.

Hope this helps.

-Navdeep

Body:
I'm using automl function with code snippet shown below

h2o.init()
h2o_train = as.h2o(train)
h2o_test = as.h2o(test)
aml <- h2o.automl(x=x, y=y, training_frame=h2o_train, leaderboard_frame=h2o_test)
print(aml@leaderboard)  # view top models
print(getParms(aml@leader))  #  get related info for top1 model

After read through the doc, I couldn't find how to load the results for other models, the leaderboard shows their model_id. It would be valuable if we can load those models, or at least see their parameters.


问:
Problem with PHP sessions
Update Solved problem!

After examining the code, the freaking problem was I was missing the }else{} after

```<code>header ('location:referraldone.php?say=blankfields');
}
</code>```

.

I'm really lost at the moment with this session code. I don't understand why the session isn't working. Where did I go wrong? I'm trying to take the data entered in the fields to the next page when someone makes an error not filling an required field. Codes are below:

```<code><?php

if (!$_POST['cname'] | !$_POST['cphone'] | !$_POST['caddress'] | !$_POST['ccity'] | !$_POST['cstate'] | !$_POST['czip'] | !$_POST['cbirthday']) {

$rname = $_REQUEST['rname'];
$rdate = $_REQUEST['rdate'];
$ragency = $_REQUEST['ragency'];
$rphone = $_REQUEST['rphone'];
$cname = $_REQUEST['cname'];
$cphone = $_REQUEST['cphone'];
$caddress = $_REQUEST['caddress'];
$ccity = $_REQUEST['ccity'];
$cstate = $_REQUEST['cstate'];
$czip = $_REQUEST['czip'];
$cbirthday = $_REQUEST['cbirthday'];
$medmemid = $_REQUEST['medmemid'];
$medclaim = $_REQUEST['medclaim'];
$marital = $_REQUEST['marital'];
$income = $_REQUEST['income'];
$gender = $_REQUEST['gender'];
$race = $_REQUEST['race'];
$caregiver = $_REQUEST['caregiver'];
$relationship = $_REQUEST['relationship'];
$memphone = $_REQUEST['memphone'];
$physician = $_REQUEST['physician'];
$phyphone = $_REQUEST['phyphone'];

session_start();
$_SESSION['rname'] = $rname;
$_SESSION['rdate'] = $rdate;
$_SESSION['ragency'] = $ragency;
$_SESSION['rphone'] = $rphone;
$_SESSION['cname'] = $cname;
$_SESSION['cphone'] = $cphone;
$_SESSION['caddress'] = $caddress;
$_SESSION['ccity'] = $ccity;
$_SESSION['cstate'] = $cstate;
$_SESSION['czip'] = $czip;
$_SESSION['cbirthday'] = $cbirthday;
$_SESSION['medmemid'] = $medmemid;
$_SESSION['medclaim'] = $medclaim;
$_SESSION['marital'] = $marital;
$_SESSION['income'] = $income;
$_SESSION['gender'] = $gender;
$_SESSION['race'] = $race;
$_SESSION['caregiver'] = $caregiver;
$_SESSION['relationship'] = $relationship;
$_SESSION['memphone'] = $memphone;
$_SESSION['physician'] = $physician;
$_SESSION['phyphone'] = $phyphone;

header ('location:referraldone.php?say=blankfields');
}

?>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
    <table style="text-align:left; width: 500px; left:45px; position:relative; padding:2px; border:1px solid #1A1A1A">
    <tr>
        <td colspan="2" style="vertical-align:top; text-align:center; border:1px solid #1A1A1A; background-color:#A52A2A; color:#FFFFFF;">REFERRAL FORM</td>
    </tr>
    <tr>
    <td colspan="2"><center>Choose us as your Home Care Agency!<br />We provide services 24 hours per day, 7 days a week.<br /><br />Please submit form below and your respond time<br />will be 48 hours.<br /><br /><strong>*Bold Fields Required</strong><br /><br /></td>
    </tr>
    <tr>
        <td valign="top">Reffered By:<br /><input name="rname" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Reffered Date:<br /><input name="rdate" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Reffered Agency:<br /><input name="ragency" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Phone:<br /><input name="rphone" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br /><strong>* Client Name:</strong><br /><input name="cname" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br /><strong>* Phone:</strong><br /><input name="cphone" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br /><strong>* Address:</strong><br /><input name="caddress" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br /><strong>* City:</strong><br /><input name="ccity" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br /><strong>* State:</strong><br /><input name="cstate" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br /><strong>* Zip Code:</strong><br /><input name="czip" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br /><strong>* Birthday:</strong><br /><input name="cbirthday" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Medicaid Member ID:<br /><input name="medmemid" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Medicare Claim:<br /><input name="medclaim" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Marital Status:<br /><input name="marital" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Monthly Income:<br /><input name="income" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Gender:<br /><input name="gender" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Race:<br /><input name="race" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Caregiver Name:<br /><input name="caregiver" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Relationship:<br /><input name="relationship" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Phone:<br /><input name="memphone" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Physician:<br /><input name="physician" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Phone:<br /><input name="phyphone" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top" style="color:#C00000"><br />Please make sure all the <strong>BOLD</strong> fields are completed before submitting form.<br /><br /></td>
    </tr>
    <tr>
        <td align="right"><input type="reset" value="Clear Fields"> <input type="submit" name="send" value="Send" /></td>
    </tr>
    </table>
</form>
</code>```

Here's the error page that should take the session data and fill the fields with it, but it doesn't:

```<code><?php
$sb = "5";

$say = $_REQUEST['say'];

$rname = $_SESSION['rname'];
$rdate = $_SESSION['rdate'];
$ragency = $_SESSION['ragency'];
$rphone = $_SESSION['rphone'];
$cname = $_SESSION['cname'];
$cphone = $_SESSION['cphone'];
$caddress = $_SESSION['caddress'];
$ccity = $_SESSION['ccity'];
$cstate = $_SESSION['cstate'];
$czip = $_SESSION['czip'];
$cbirthday = $_SESSION['cbirthday'];
$medmemid = $_SESSION['medmemid'];
$medclaim = $_SESSION['medclaim'];
$marital = $_SESSION['marital'];
$income = $_SESSION['income'];
$gender = $_SESSION['gender'];
$race = $_SESSION['race'];
$caregiver = $_SESSION['caregiver'];
$relationship = $_SESSION['relationship'];
$memphone = $_SESSION['memphone'];
$physician = $_SESSION['physician'];
$phyphone = $_SESSION['phyphone'];

if(isset($say)){
    switch ($say){
        case "formsent":
        $return = "Referral Form Sent. Your respond time will be 48 hours.";
        break;
        case "blankfields":
        $return = "All <strong>Bold</strong> Fields Required";
        break;
        default:
        break;
    }
}

if (isset($_POST['send'])) {

    if (!$_POST['cname'] | !$_POST['cphone'] | !$_POST['caddress'] | !$_POST['ccity'] | !$_POST['cstate'] | !$_POST['czip'] | !$_POST['cbirthday']) {

$rname = $_REQUEST['rname'];
$rdate = $_REQUEST['rdate'];
$ragency = $_REQUEST['ragency'];
$rphone = $_REQUEST['rphone'];
$cname = $_REQUEST['cname'];
$cphone = $_REQUEST['cphone'];
$caddress = $_REQUEST['caddress'];
$ccity = $_REQUEST['ccity'];
$cstate = $_REQUEST['cstate'];
$czip = $_REQUEST['czip'];
$cbirthday = $_REQUEST['cbirthday'];
$medmemid = $_REQUEST['medmemid'];
$medclaim = $_REQUEST['medclaim'];
$marital = $_REQUEST['marital'];
$income = $_REQUEST['income'];
$gender = $_REQUEST['gender'];
$race = $_REQUEST['race'];
$caregiver = $_REQUEST['caregiver'];
$relationship = $_REQUEST['relationship'];
$memphone = $_REQUEST['memphone'];
$physician = $_REQUEST['physician'];
$phyphone = $_REQUEST['phyphone'];

session_start();
$_SESSION['rname'] = $rname;
$_SESSION['rdate'] = $rdate;
$_SESSION['ragency'] = $ragency;
$_SESSION['rphone'] = $rphone;
$_SESSION['cname'] = $cname;
$_SESSION['cphone'] = $cphone;
$_SESSION['caddress'] = $caddress;
$_SESSION['ccity'] = $ccity;
$_SESSION['cstate'] = $cstate;
$_SESSION['czip'] = $czip;
$_SESSION['cbirthday'] = $cbirthday;
$_SESSION['medmemid'] = $medmemid;
$_SESSION['medclaim'] = $medclaim;
$_SESSION['marital'] = $marital;
$_SESSION['income'] = $income;
$_SESSION['gender'] = $gender;
$_SESSION['race'] = $race;
$_SESSION['caregiver'] = $caregiver;
$_SESSION['relationship'] = $relationship;
$_SESSION['memphone'] = $memphone;
$_SESSION['physician'] = $physician;
$_SESSION['phyphone'] = $phyphone;

header ('location:referraldone.php?say=blankfields');
}
?>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
    <table style="text-align:left; width: 500px; left:45px; position:relative; padding:2px; border:1px solid #1A1A1A">
    <tr>
        <td colspan="2" style="vertical-align:top; text-align:center; border:1px solid #1A1A1A; background-color:#A52A2A; color:#FFFFFF;">REFERRAL FORM</td>
    </tr>
    <tr>
    <td colspan="2"><center>Choose us as your Home Care Agency!<br />We provide services 24 hours per day, 7 days a week.<br /><br />Please submit form below and your respond time<br />will be 48 hours.<br /><br /><strong>*Bold Fields Required</strong><br /><br /></td>
    </tr>
    <tr>
        <td valign="top">Reffered By:<br /><input name="rname" type="text" value="<?php echo $rname; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Reffered Date:<br /><input name="rdate" type="text" value="<?php echo $rdate; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Reffered Agency:<br /><input name="ragency" type="text" value="<?php echo $ragency; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Phone:<br /><input name="rphone" type="text" style=value="rphone" "width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br /><strong>* Client Name:</strong><br /><input name="cname" type="text" value="<?php echo $cname; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br /><strong>* Phone:</strong><br /><input name="cphone" type="text" value="<?php echo $cphone; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br /><strong>* Address:</strong><br /><input name="caddress" type="text" value="<?php echo $caddress; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br /><strong>* City:</strong><br /><input name="ccity" type="text" value="<?php echo $ccity; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br /><strong>* State:</strong><br /><input name="cstate" type="text" value="<?php echo $cstate; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br /><strong>* Zip Code:</strong><br /><input name="czip" type="text" value="<?php echo $czip; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br /><strong>* Birthday:</strong><br /><input name="cbirthday" type="text" value="<?php echo $cbirthday; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Medicaid Member ID:<br /><input name="medmemid" type="text" value="<?php echo $medmemid; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Medicare Claim:<br /><input name="medclaim" type="text" value="<?php echo $medclaim; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Marital Status:<br /><input name="marital" type="text" value="<?php echo $marital; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Monthly Income:<br /><input name="income" type="text" value="<?php echo $income; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Gender:<br /><input name="gender" type="text" value="<?php echo $gender; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Race:<br /><input name="race" type="text" value="<?php echo $race; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Caregiver Name:<br /><input name="caregiver" type="text" value="<?php echo $caregiver; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Relationship:<br /><input name="relationship" type="text" value="<?php echo $relationship; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Phone:<br /><input name="memphone" type="text" value="<?php echo $phone; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Physician:<br /><input name="physician" type="text" value="<?php echo $physician; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Phone:<br /><input name="phyphone" type="text" value="<?php echo $phyphone; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top" style="color:#C00000"><br />Please make sure all the <strong>BOLD</strong> fields are completed before submitting form.<br /><br /></td>
    </tr>
    <tr>
        <td align="right"><input type="reset" value="Clear Fields"> <input type="submit" name="send" value="Send" /></td>
    </tr>
    </table>
</form>
</code>```

答: session_start must be called before you read from -or write to- the $_SESSION variable. In the second page "error page", you placed session_start but after you tried to read the $_SESSION var, so place it in the top of that "error page" instead of the middle.</p>

Title: Problem with PHP sessions

Body:
Update Solved problem!

After examining the code, the freaking problem was I was missing the }else{} after

header ('location:referraldone.php?say=blankfields');
}

.

I'm really lost at the moment with this session code. I don't understand why the session isn't working. Where did I go wrong? I'm trying to take the data entered in the fields to the next page when someone makes an error not filling an required field. Codes are below:

<?php

if (!$_POST['cname'] | !$_POST['cphone'] | !$_POST['caddress'] | !$_POST['ccity'] | !$_POST['cstate'] | !$_POST['czip'] | !$_POST['cbirthday']) {

$rname = $_REQUEST['rname'];
$rdate = $_REQUEST['rdate'];
$ragency = $_REQUEST['ragency'];
$rphone = $_REQUEST['rphone'];
$cname = $_REQUEST['cname'];
$cphone = $_REQUEST['cphone'];
$caddress = $_REQUEST['caddress'];
$ccity = $_REQUEST['ccity'];
$cstate = $_REQUEST['cstate'];
$czip = $_REQUEST['czip'];
$cbirthday = $_REQUEST['cbirthday'];
$medmemid = $_REQUEST['medmemid'];
$medclaim = $_REQUEST['medclaim'];
$marital = $_REQUEST['marital'];
$income = $_REQUEST['income'];
$gender = $_REQUEST['gender'];
$race = $_REQUEST['race'];
$caregiver = $_REQUEST['caregiver'];
$relationship = $_REQUEST['relationship'];
$memphone = $_REQUEST['memphone'];
$physician = $_REQUEST['physician'];
$phyphone = $_REQUEST['phyphone'];

session_start();
$_SESSION['rname'] = $rname;
$_SESSION['rdate'] = $rdate;
$_SESSION['ragency'] = $ragency;
$_SESSION['rphone'] = $rphone;
$_SESSION['cname'] = $cname;
$_SESSION['cphone'] = $cphone;
$_SESSION['caddress'] = $caddress;
$_SESSION['ccity'] = $ccity;
$_SESSION['cstate'] = $cstate;
$_SESSION['czip'] = $czip;
$_SESSION['cbirthday'] = $cbirthday;
$_SESSION['medmemid'] = $medmemid;
$_SESSION['medclaim'] = $medclaim;
$_SESSION['marital'] = $marital;
$_SESSION['income'] = $income;
$_SESSION['gender'] = $gender;
$_SESSION['race'] = $race;
$_SESSION['caregiver'] = $caregiver;
$_SESSION['relationship'] = $relationship;
$_SESSION['memphone'] = $memphone;
$_SESSION['physician'] = $physician;
$_SESSION['phyphone'] = $phyphone;

header ('location:referraldone.php?say=blankfields');
}

?>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">

        REFERRAL FORM

    Choose us as your Home Care Agency!
We provide services 24 hours per day, 7 days a week.

Please submit form below and your respond time
will be 48 hours.

*Bold Fields Required

        Reffered By:
<input name="rname" type="text" style="width:98%" />

Reffered Date:
<input name="rdate" type="text" style="width:98%" />

Reffered Agency:
<input name="ragency" type="text" style="width:98%" />

Phone:
<input name="rphone" type="text" style="width:98%" />

* Client Name:
<input name="cname" type="text" style="width:98%" />

* Phone:
<input name="cphone" type="text" style="width:98%" />

* Address:
<input name="caddress" type="text" style="width:98%" />

* City:
<input name="ccity" type="text" style="width:98%" />

* State:
<input name="cstate" type="text" style="width:98%" />

* Zip Code:
<input name="czip" type="text" style="width:98%" />

* Birthday:
<input name="cbirthday" type="text" style="width:98%" />

Medicaid Member ID:
<input name="medmemid" type="text" style="width:98%" />

Medicare Claim:
<input name="medclaim" type="text" style="width:98%" />

Marital Status:
<input name="marital" type="text" style="width:98%" />

Monthly Income:
<input name="income" type="text" style="width:98%" />

Gender:
<input name="gender" type="text" style="width:98%" />

Race:
<input name="race" type="text" style="width:98%" />

Caregiver Name:
<input name="caregiver" type="text" style="width:98%" />

Relationship:
<input name="relationship" type="text" style="width:98%" />

Phone:
<input name="memphone" type="text" style="width:98%" />

Physician:
<input name="physician" type="text" style="width:98%" />

Phone:
<input name="phyphone" type="text" style="width:98%" />

Please make sure all the BOLD fields are completed before submitting form.

        <input type="reset" value="Clear Fields"> <input type="submit" name="send" value="Send" />

</form>

Here's the error page that should take the session data and fill the fields with it, but it doesn't:

<?php
$sb = "5";

$say = $_REQUEST['say'];

$rname = $_SESSION['rname'];
$rdate = $_SESSION['rdate'];
$ragency = $_SESSION['ragency'];
$rphone = $_SESSION['rphone'];
$cname = $_SESSION['cname'];
$cphone = $_SESSION['cphone'];
$caddress = $_SESSION['caddress'];
$ccity = $_SESSION['ccity'];
$cstate = $_SESSION['cstate'];
$czip = $_SESSION['czip'];
$cbirthday = $_SESSION['cbirthday'];
$medmemid = $_SESSION['medmemid'];
$medclaim = $_SESSION['medclaim'];
$marital = $_SESSION['marital'];
$income = $_SESSION['income'];
$gender = $_SESSION['gender'];
$race = $_SESSION['race'];
$caregiver = $_SESSION['caregiver'];
$relationship = $_SESSION['relationship'];
$memphone = $_SESSION['memphone'];
$physician = $_SESSION['physician'];
$phyphone = $_SESSION['phyphone'];

if(isset($say)){
    switch ($say){
        case "formsent":
        $return = "Referral Form Sent. Your respond time will be 48 hours.";
        break;
        case "blankfields":
        $return = "All Bold Fields Required";
        break;
        default:
        break;
    }
}

if (isset($_POST['send'])) {

    if (!$_POST['cname'] | !$_POST['cphone'] | !$_POST['caddress'] | !$_POST['ccity'] | !$_POST['cstate'] | !$_POST['czip'] | !$_POST['cbirthday']) {

$rname = $_REQUEST['rname'];
$rdate = $_REQUEST['rdate'];
$ragency = $_REQUEST['ragency'];
$rphone = $_REQUEST['rphone'];
$cname = $_REQUEST['cname'];
$cphone = $_REQUEST['cphone'];
$caddress = $_REQUEST['caddress'];
$ccity = $_REQUEST['ccity'];
$cstate = $_REQUEST['cstate'];
$czip = $_REQUEST['czip'];
$cbirthday = $_REQUEST['cbirthday'];
$medmemid = $_REQUEST['medmemid'];
$medclaim = $_REQUEST['medclaim'];
$marital = $_REQUEST['marital'];
$income = $_REQUEST['income'];
$gender = $_REQUEST['gender'];
$race = $_REQUEST['race'];
$caregiver = $_REQUEST['caregiver'];
$relationship = $_REQUEST['relationship'];
$memphone = $_REQUEST['memphone'];
$physician = $_REQUEST['physician'];
$phyphone = $_REQUEST['phyphone'];

session_start();
$_SESSION['rname'] = $rname;
$_SESSION['rdate'] = $rdate;
$_SESSION['ragency'] = $ragency;
$_SESSION['rphone'] = $rphone;
$_SESSION['cname'] = $cname;
$_SESSION['cphone'] = $cphone;
$_SESSION['caddress'] = $caddress;
$_SESSION['ccity'] = $ccity;
$_SESSION['cstate'] = $cstate;
$_SESSION['czip'] = $czip;
$_SESSION['cbirthday'] = $cbirthday;
$_SESSION['medmemid'] = $medmemid;
$_SESSION['medclaim'] = $medclaim;
$_SESSION['marital'] = $marital;
$_SESSION['income'] = $income;
$_SESSION['gender'] = $gender;
$_SESSION['race'] = $race;
$_SESSION['caregiver'] = $caregiver;
$_SESSION['relationship'] = $relationship;
$_SESSION['memphone'] = $memphone;
$_SESSION['physician'] = $physician;
$_SESSION['phyphone'] = $phyphone;

header ('location:referraldone.php?say=blankfields');
}
?>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">

        REFERRAL FORM

    Choose us as your Home Care Agency!
We provide services 24 hours per day, 7 days a week.

Please submit form below and your respond time
will be 48 hours.

*Bold Fields Required

        Reffered By:
<input name="rname" type="text" value="<?php echo $rname; ?>" style="width:98%" />

Reffered Date:
<input name="rdate" type="text" value="<?php echo $rdate; ?>" style="width:98%" />

Reffered Agency:
<input name="ragency" type="text" value="<?php echo $ragency; ?>" style="width:98%" />

Phone:
<input name="rphone" type="text" style=value="rphone" "width:98%" />

* Client Name:
<input name="cname" type="text" value="<?php echo $cname; ?>" style="width:98%" />

* Phone:
<input name="cphone" type="text" value="<?php echo $cphone; ?>" style="width:98%" />

* Address:
<input name="caddress" type="text" value="<?php echo $caddress; ?>" style="width:98%" />

* City:
<input name="ccity" type="text" value="<?php echo $ccity; ?>" style="width:98%" />

* State:
<input name="cstate" type="text" value="<?php echo $cstate; ?>" style="width:98%" />

* Zip Code:
<input name="czip" type="text" value="<?php echo $czip; ?>" style="width:98%" />

* Birthday:
<input name="cbirthday" type="text" value="<?php echo $cbirthday; ?>" style="width:98%" />

Medicaid Member ID:
<input name="medmemid" type="text" value="<?php echo $medmemid; ?>" style="width:98%" />

Medicare Claim:
<input name="medclaim" type="text" value="<?php echo $medclaim; ?>" style="width:98%" />

Marital Status:
<input name="marital" type="text" value="<?php echo $marital; ?>" style="width:98%" />

Monthly Income:
<input name="income" type="text" value="<?php echo $income; ?>" style="width:98%" />

Gender:
<input name="gender" type="text" value="<?php echo $gender; ?>" style="width:98%" />

Race:
<input name="race" type="text" value="<?php echo $race; ?>" style="width:98%" />

Caregiver Name:
<input name="caregiver" type="text" value="<?php echo $caregiver; ?>" style="width:98%" />

Relationship:
<input name="relationship" type="text" value="<?php echo $relationship; ?>" style="width:98%" />

Phone:
<input name="memphone" type="text" value="<?php echo $phone; ?>" style="width:98%" />

Physician:
<input name="physician" type="text" value="<?php echo $physician; ?>" style="width:98%" />

Phone:
<input name="phyphone" type="text" value="<?php echo $phyphone; ?>" style="width:98%" />

Please make sure all the BOLD fields are completed before submitting form.

        <input type="reset" value="Clear Fields"> <input type="submit" name="send" value="Send" />

</form>


问:
Why is the Firebase `accessToken` under such a strange heading?

Background

I have authenticated a user successfully with firebase in the client.

```<code>let fbAuthCreds = await this.props.firebase.auth().signInWithEmailAndPassword(email, password);
</code>```

When I log this I get an object full of very strange looking keys example

Ac, D, Ga, Sa, Yd, ba, fa, g, refreshToken, vc, ze

Most of these I have no idea what they mean (except refreshToken, email .etc)

I found that the actual accessToken id the one that says Yd

Question

Why does firebase send back such strange objects with non human readable names?

Also I would like to send the token to my node server but writing fbAuthCreds.Yd seems not right, how should I retrieve it?

Additional Note

I did get this auth process into redux with react-redux-firebase (Awesome library) and can see a much nicer path to retrieve the data but it fails and says undefined when I try to get hold of it.

Look at line 23-27 there are proper names for the tokens and they should be retrievable

答:
Why does firebase send back such strange objects with non human readable names?

The code is minified to save bandwidth and memory. Methods and fields that are part of the public API are left unmodified during this process.

Note that the minified names may change between builds, so you should not rely on them staying the same. Instead use the methods from the public API of the user object, e.g. User.getToken.

Body:
Background

I have authenticated a user successfully with firebase in the client.

let fbAuthCreds = await this.props.firebase.auth().signInWithEmailAndPassword(email, password);

When I log this I get an object full of very strange looking keys example

Ac, D, Ga, Sa, Yd, ba, fa, g, refreshToken, vc, ze

Most of these I have no idea what they mean (except refreshToken, email .etc)

I found that the actual accessToken id the one that says Yd

Question

Why does firebase send back such strange objects with non human readable names?

Also I would like to send the token to my node server but writing fbAuthCreds.Yd seems not right, how should I retrieve it?

Additional Note

I did get this auth process into redux with react-redux-firebase (Awesome library) and can see a much nicer path to retrieve the data but it fails and says undefined when I try to get hold of it.

Look at line 23-27 there are proper names for the tokens and they should be retrievable


问:
output(c) for writing a function
```<code>#include <stdio.h>
#include <cs50.h>

float euro (float usd);

int main (void)
{
    float usd = 1.00;
    do
    {
        printf("How many USD you got?\n");
        usd = get_float();
    }
    while(usd < 0);
    {
    printf("enter something greater than zero please!\n");
    }

}

float euro (float usd)
{

    float d = usd * 0.84;

    return(d);
}
</code>```

this is my code. Im trying to write a function that converts USD to euros and then can recall the function but i got confused and now no matter what every output is "enter something greater than zero please!

答:
Your while is not grouped with the printf below it, but with the do above it.

Let's reformat to make the distinction more clear:

```<code>do
{
    printf("How many USD you got?\n");
    usd = get_float();
} while(usd < 0);

{
    printf("enter something greater than zero please!\n");
}
</code>```

The do..while loop continues until you input a positive value.  After that, you have a block that always runs.

You probably want to put an if check inside the loop to see if the error message should be printed:

```<code>do
{
    printf("How many USD you got?\n");
    usd = get_float();
    if (usd < 0) {
        printf("enter something greater than zero please!\n");
    }
} while(usd < 0);
</code>```

Title: output(c) for writing a function

Body:
#include <stdio.h>
#include <cs50.h>

float euro (float usd);

int main (void)
{
    float usd = 1.00;
    do
    {
        printf("How many USD you got?\n");
        usd = get_float();
    }
    while(usd < 0);
    {
    printf("enter something greater than zero please!\n");
    }

}

float euro (float usd)
{

    float d = usd * 0.84;

    return(d);
}

this is my code. Im trying to write a function that converts USD to euros and then can recall the function but i got confused and now no matter what every output is "enter something greater than zero please!

Body:
Your while is not grouped with the printf below it, but with the do above it.

Let's reformat to make the distinction more clear:

do
{
    printf("How many USD you got?\n");
    usd = get_float();
} while(usd < 0);

{
    printf("enter something greater than zero please!\n");
}

The do..while loop continues until you input a positive value.  After that, you have a block that always runs.

You probably want to put an if check inside the loop to see if the error message should be printed:

do
{
    printf("How many USD you got?\n");
    usd = get_float();
    if (usd < 0) {
        printf("enter something greater than zero please!\n");
    }
} while(usd < 0);


问:
Angular nested http request with previous request as parameter
I'm building an application where i list events in an html table. An event holds some information about itself but also a user-id, this user-id is the identifier for the user in the mongodb database i'm using

I want to use the $http service provided by angular to first get the events, then looping through the data in the response and issue another get to fetch the user object for each user-id. Every event carries exactly one user-id. The user object is then appended onto the existing event object as a nested object.

However when i do this the user-id variable i use for the calls turns out to be unassigned, as the http calls are async. I've read something about trailing/chaining the calls but i don't get it to work.

Below is the code i've tried amongst what seems to be 100 tries..

Controller

```<code>"use strict";
(function () {
    var app = angular.module("app-test");

    app.controller("testController", function ($scope, $log, $http, $route) {

    var getAllQualityEvents = function () {
        return $http.get("http://localhost:5001/api/qualityevent")
            .then(function (response) {
                return response.data;
            });
    };

    var getUserForEvents = function (data) {
        var result;
        for (var d in data) {
            $http.get("http://localhost:5001/api/user/" + d.userId)
                .then(function (response) {
                    $scope.qualityEvent[d]["user"] = response.data;
                });
        };
    };

    // Run every loop.
    getAllQualityEvents()
        .then(function (data) {
            $scope.qualityEvent = data;
            getUserForEvents(data);
            });
    });
})();
</code>```

Html document (only the path using the controller)

```<code><div class="row">
    <div class="col-xl">
        <h1>Test events</h1>
    </div>
</div>
<div class="row">
    <div class="col-xl">
        <table class="table">
            <thead>
                <tr>
                    <th>Username</th>
                    <th>User Id</th>
                    <th>Something</th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="qualityEvent in qualityEvents" class="{{qualityEvent.isQualityOk ? 'bg-success' : 'bg-danger'}}">
                    <td scope="row">{{qualityEvent.user}}</td>
                    <td>{{qualityEvent}}</td>
                    <td></td>
                </tr>
            </tbody>
        </table>
    </div>
</div>
</code>```

Error message

My api returning an error message telling me "undefined" is not a valid id.

答: data in the getUserForEvents() method is most likely an array so you would need data[d].userId not d.userId

Body:
I'm building an application where i list events in an html table. An event holds some information about itself but also a user-id, this user-id is the identifier for the user in the mongodb database i'm using

I want to use the $http service provided by angular to first get the events, then looping through the data in the response and issue another get to fetch the user object for each user-id. Every event carries exactly one user-id. The user object is then appended onto the existing event object as a nested object.

However when i do this the user-id variable i use for the calls turns out to be unassigned, as the http calls are async. I've read something about trailing/chaining the calls but i don't get it to work.

Below is the code i've tried amongst what seems to be 100 tries..

Controller

"use strict";
(function () {
    var app = angular.module("app-test");

    app.controller("testController", function ($scope, $log, $http, $route) {

    var getAllQualityEvents = function () {
        return $http.get("http://localhost:5001/api/qualityevent")
            .then(function (response) {
                return response.data;
            });
    };

    var getUserForEvents = function (data) {
        var result;
        for (var d in data) {
            $http.get("http://localhost:5001/api/user/" + d.userId)
                .then(function (response) {
                    $scope.qualityEvent[d]["user"] = response.data;
                });
        };
    };

    // Run every loop.
    getAllQualityEvents()
        .then(function (data) {
            $scope.qualityEvent = data;
            getUserForEvents(data);
            });
    });
})();

Html document (only the path using the controller)

Test events

                    Username
                    User Id
                    Something

                    {{qualityEvent.user}}
                    {{qualityEvent}}

Error message

My api returning an error message telling me "undefined" is not a valid id.


答:
You can try this way</p>

```<code>df_prod = spark.read.csv('/path/to/sample.csv',inferSchema=True,header=True)
rdd = df_prod.rdd.map(lambda x: {x['FromComponentID']:{x['ToComponentID']:x['Cost']}})
rdd.collect()
</code>```

Title: Dataframe pyspark to dict

Body:
I have this dataframe path_df:

path_df.show()
+---------------+-------------+----+
|FromComponentID|ToComponentID|Cost|
+---------------+-------------+----+
|            160|          163|27.0|
|            160|          183|27.0|
|            161|          162|22.0|
|            161|          170|31.0|
|            162|          161|22.0|
|            162|          167|24.0|
|            163|          160|27.0|
|            163|          164|27.0|
|            164|          163|27.0|
|            164|          165|35.0|
|            165|          164|35.0|
|            165|          166|33.0|
|            166|          165|33.0|
|            166|          167|31.0|
|            167|          162|24.0|
|            167|          166|31.0|
|            167|          168|27.0|
|            168|          167|27.0|
|            168|          169|23.0|
|            169|          168|23.0|
+---------------+-------------+----+
only showing top 20 rows

From this, I want to make a dictionnary, as follow:
{FromComponentID:{ToComponentID:Cost}}

For my current data, it would be:

{160 : {163 : 27,
        183 : 27},
 161 : {162 : 22,
        170 : 31},
 162 : {161 : 22
        167 : 24},
 ...
 167 : {162 : 24,
        166 : 31,
        168 : 27}
 168 : {167 : 27,
        169 : 23},
 169 : {168 : 23}
}

Can I do that using only PySpark and how ? Or maybe it's better to extract my data and process them directly with python.

Body:
You can try this way

df_prod = spark.read.csv('/path/to/sample.csv',inferSchema=True,header=True)
rdd = df_prod.rdd.map(lambda x: {x['FromComponentID']:{x['ToComponentID']:x['Cost']}})
rdd.collect()


问:
Update whole table in one query
If there's duplicated topic - please, forgive me, but i haven't found a solution yet. First of all, I've got one php file (update.php). This file contains:

```<code><form action='update.php' method='post'>
<table border='1'>
    <?php
        $servername = "localhost";
        $username = "root";
        $password = "";
        $dbname = "exchange";
        $conn = new mysqli($servername, $username, $password, $dbname);
        if (mysqli_connect_errno()) {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }
        mysqli_set_charset($conn,"utf8");
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }
        $sql = "SELECT ID, name, symbol, buy, sell FROM exchangevalues";
        $result = $conn->query($sql);
        if ($result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {
                echo "<tr>";
                echo "<td><input type='text' name='ID' value='".$row["ID"]."'>";
                echo "<td>".$row["name"]."</td>";
                echo "<td>Buy: <input type='text' name='buy' value='".$row['buy']."'></td>";
                echo "<td>Sell: <input type='text' name='sell' value='".$row['sell']."'></td>";
                echo "</tr>";
            }
        }
        $conn->close();
    ?>
<table>
</code>```

There's 14 rows and 5 columns in my db. How do i update every row in columns 'buy' and 'sell' on 'click' (isset submit button) with new values? I've tried with ID[], buy[], but I've got problems with loop and i cannot handle it. I'm running MySQL on localhost, also i know that only last row will be updated without running loop, but still...

答:
I am assuming you have corresponding php code to process the input, here is a sample of what you'll need to do for the HTML when creating the form:

```<code>if ($result->num_rows > 0) {
    $i=0;
    while($row = $result->fetch_assoc()) {
        echo "<tr>";
        echo "<td><input type='text' name='ID[" . $i . "]' value='".$row["ID"]."'>";
        echo "<td>".$row["name"]."</td>";
        echo "</tr>";
        }
    }
</code>```

On the php side to process the input, you can do something like this:

```<code>$id_array = $_REQUEST["ID"];
foreach($id_array as $id){
    //do insert with $id
}
</code>```

Title: Update whole table in one query

Body:
If there's duplicated topic - please, forgive me, but i haven't found a solution yet. First of all, I've got one php file (update.php). This file contains:

<form action='update.php' method='post'>

    <?php
        $servername = "localhost";
        $username = "root";
        $password = "";
        $dbname = "exchange";
        $conn = new mysqli($servername, $username, $password, $dbname);
        if (mysqli_connect_errno()) {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }
        mysqli_set_charset($conn,"utf8");
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }
        $sql = "SELECT ID, name, symbol, buy, sell FROM exchangevalues";
        $result = $conn->query($sql);
        if ($result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {
                echo "
";
                echo "<input type='text' name='ID' value='".$row["ID"]."'>";
                echo "".$row["name"]."	";
                echo "Buy: <input type='text' name='buy' value='".$row['buy']."'>	";
                echo "Sell: <input type='text' name='sell' value='".$row['sell']."'>	";
                echo "
";
            }
        }
        $conn->close();
    ?>

There's 14 rows and 5 columns in my db. How do i update every row in columns 'buy' and 'sell' on 'click' (isset submit button) with new values? I've tried with ID[], buy[], but I've got problems with loop and i cannot handle it. I'm running MySQL on localhost, also i know that only last row will be updated without running loop, but still...

Body:
I am assuming you have corresponding php code to process the input, here is a sample of what you'll need to do for the HTML when creating the form:

if ($result->num_rows > 0) {
    $i=0;
    while($row = $result->fetch_assoc()) {
        echo "<tr>";
        echo "<td><input type='text' name='ID[" . $i . "]' value='".$row["ID"]."'>";
        echo "<td>".$row["name"]."</td>";
        echo "</tr>";
        }
    }

On the php side to process the input, you can do something like this:

$id_array = $_REQUEST["ID"];
foreach($id_array as $id){
    //do insert with $id
}


问:
"no tag was found" Error
I am trying to implement a very simple RichFaces application (following the example at the developer guide, but am encountering an error I cannot solve.

My code appears to build and deploy correctly to Tomcat (localhost), but when the index page is opened I get the exception:

```<code>javax.faces.view.facelets.TagException: /index.xhtml @13,19 <a4j:form> Tag Library supports namespace: http://richfaces.org/a4j, but no tag was defined for name: form
</code>```

The index page I am attempting to load is as follows:

```<code><?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:a4j="http://richfaces.org/a4j"
  xmlns:rich="http://richfaces.org/rich"
  xmlns:f="http://java.sun.com/jsf/core">
<h:head>
    <title>Facelet Title</title>
</h:head>
<h:body><f:view>
    <a4j:form>
        <rich:panel header="This is the title" style="width:400px;">
            <h:outputText value="Enter your name:"/>
            <h:inputText value="#{MyBean.message}">
                <f:validateLength minimum="1" maximum="20"/>
            </h:inputText>
        </rich:panel>
    </f:view></a4j:form>
</h:body>
</html>
</code>```

This is the same as the example in the developer guide, as far as I can tell.  I am developing within Netbeans 6.8, using the MyFaces implementation of JSF 2.0, and have added RichFaces and Apache Commons jar's as libraries, and the tag the exception is stating is actually auto-suggested by Netbeans!

From Apache Commons, I have added:

    beanutils, collections, digester, logging

From RichFaces, I have added:
    richfaces-api, richfaces-impl, richfaces-impl-jsf2, richfaces-ui

If it would be useful to provide the bean code and/or web.xml, please say so, I just wanted to avoid a huge post for what may be a simple mistake.

答: I see you have added both richfaces-impl and richfaces-impl-jsf2 jars. As per the recommendation you should only add the latter if you are using jsf 2.0.</p>

Title: "no tag was found" Error

Body:
I am trying to implement a very simple RichFaces application (following the example at the developer guide, but am encountering an error I cannot solve.

My code appears to build and deploy correctly to Tomcat (localhost), but when the index page is opened I get the exception:

javax.faces.view.facelets.TagException: /index.xhtml @13,19 <a4j:form> Tag Library supports namespace: http://richfaces.org/a4j, but no tag was defined for name: form

The index page I am attempting to load is as follows:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<h:head>
    <title>Facelet Title</title>
</h:head>
<h:body><f:view>
    <a4j:form>
        <rich:panel header="This is the title" style="width:400px;">
            <h:outputText value="Enter your name:"/>
            <h:inputText value="#{MyBean.message}">
                <f:validateLength minimum="1" maximum="20"/>
            </h:inputText>
        </rich:panel>
    </f:view></a4j:form>
</h:body>

This is the same as the example in the developer guide, as far as I can tell.  I am developing within Netbeans 6.8, using the MyFaces implementation of JSF 2.0, and have added RichFaces and Apache Commons jar's as libraries, and the tag the exception is stating is actually auto-suggested by Netbeans!

From Apache Commons, I have added:

    beanutils, collections, digester, logging

From RichFaces, I have added:
    richfaces-api, richfaces-impl, richfaces-impl-jsf2, richfaces-ui

If it would be useful to provide the bean code and/or web.xml, please say so, I just wanted to avoid a huge post for what may be a simple mistake.


问:
How to define an automatically unfoldable definition
I sometimes want to define some shortcut for existing functions like in the following example:

```<code>Parameter T : Set.
Parameter zero one: T.
Parameter f : T -> T -> option T.
Hypothesis f_unit : forall t, f zero t = None.

Definition g (t : T) := f t one.
</code>```

However, this definition seems to be abstract since I cannot use theorems about f on instances of g without first unfolding:

```<code>Goal (g zero = None).
  unfold g.
  rewrite f_unit.
  reflexivity.
Qed.
</code>```

Is there a way to mark definitions as automatically unfoldable?

答:
There are a couple of ways to accomplish what you ask, and here is an explanation of the ones I know:

Use an abbreviation.  To quote the reference manual:

An abbreviation is a name, possibly applied to arguments, that denotes a (presumably) more complex expression.

[...]

Abbreviations are bound to an absolute name as an ordinary definition is, and they can be referred by qualified names too.

Abbreviations are syntactic in the sense that they are bound to expressions which are not typed at the time of the definition of the abbreviation but at the time it is used.

In your case, this would be

```<code>Notation g t := (f t one).
</code>```

This is much like Daniel Schepler's suggestion of a Notation, except that it does not reserve g as a global keyword.

Use setoid_rewrite.  Coq's setoid_rewrite tactic is similar to rewrite, except that it looks for occurrences modulo δ (unfolding), can rewrite under binders, and a few other minor things.

For your example, this is:

```<code>Require Import Coq.Setoids.Setoid.
Goal (g zero = None).
Proof.
  setoid_rewrite f_unit.
  reflexivity.
Qed.
</code>```

In some cases, you can use Set Keyed Unification and Declare Equivalent Keys, though this does not work in your case (I've opened an issue on GitHub here.  This tells rewrite to "unfold" one head constant to another, though it apparently isn't quite good enough to handle your case.  There's a bit of documentation on the relevant commit message, and an open issue to add proper documentation.

Here is an example this is useful:

```<code>Parameter T : Set.
Parameter zero one: T.
Parameter f : T -> T -> option T.
Hypothesis f_unit : forall t, f zero t = None.

Definition g := f zero zero.

Set Keyed Unification.
Goal (g = None).
Proof.
  Fail rewrite f_unit.
  Declare Equivalent Keys g f.
  rewrite f_unit.
  reflexivity.
Qed.
</code>```

Body:
I sometimes want to define some shortcut for existing functions like in the following example:

Parameter T : Set.
Parameter zero one: T.
Parameter f : T -> T -> option T.
Hypothesis f_unit : forall t, f zero t = None.

Definition g (t : T) := f t one.

However, this definition seems to be abstract since I cannot use theorems about f on instances of g without first unfolding:

Goal (g zero = None).
  unfold g.
  rewrite f_unit.
  reflexivity.
Qed.

Is there a way to mark definitions as automatically unfoldable?

Body:
There are a couple of ways to accomplish what you ask, and here is an explanation of the ones I know:

Use an abbreviation.  To quote the reference manual:

An abbreviation is a name, possibly applied to arguments, that denotes a (presumably) more complex expression.

[...]

Abbreviations are bound to an absolute name as an ordinary definition is, and they can be referred by qualified names too.

Abbreviations are syntactic in the sense that they are bound to expressions which are not typed at the time of the definition of the abbreviation but at the time it is used.

In your case, this would be

Notation g t := (f t one).

This is much like Daniel Schepler's suggestion of a Notation, except that it does not reserve g as a global keyword.

Use setoid_rewrite.  Coq's setoid_rewrite tactic is similar to rewrite, except that it looks for occurrences modulo δ (unfolding), can rewrite under binders, and a few other minor things.

For your example, this is:

Require Import Coq.Setoids.Setoid.
Goal (g zero = None).
Proof.
  setoid_rewrite f_unit.
  reflexivity.
Qed.

In some cases, you can use Set Keyed Unification and Declare Equivalent Keys, though this does not work in your case (I've opened an issue on GitHub here.  This tells rewrite to "unfold" one head constant to another, though it apparently isn't quite good enough to handle your case.  There's a bit of documentation on the relevant commit message, and an open issue to add proper documentation.

Here is an example this is useful:

Parameter T : Set.
Parameter zero one: T.
Parameter f : T -> T -> option T.
Hypothesis f_unit : forall t, f zero t = None.

Definition g := f zero zero.

Set Keyed Unification.
Goal (g = None).
Proof.
  Fail rewrite f_unit.
  Declare Equivalent Keys g f.
  rewrite f_unit.
  reflexivity.
Qed.


问:
What means an InvalidOperationException on Process.ExitTime "Process was not started by this object, so requested information cannot be determined."
We have a tool that manages several processes of a computer and from time to time in uncertain conditions we get an InvalidOperationExceptionwhen accessing the MSDN: Process.ExitTime property.

The exception message says

process was not started by this object, so requested information
  cannot be determined

Does that mean that I can only get the exit time of a process that I've started myself? That's not documented anywhere.

答:
In order to access the exit time information, the Process class needs to have an open Handle for the processa. Whilst e.g. WaitForExit will temporarily create a handle, unfortunately it closes that handle before returning.

We can force the Process class to permanently open a handle to the process by accessing its Handle or SafeHandle properties1. However, we should notice that there is still some raciness here since between constructing the Process object and accessing the SafeHandle property the process could exit.

Start an instance of Notepad, find its process ID and edit it into the first line of Main here:

```<code>using System;
using System.Diagnostics;

namespace PlayAreaCSCon
{
  internal class Program
  {
    public static void Main(string[] args)
    {
      var p = Process.GetProcessById(18148);
      //var sh = p.SafeHandle;
      p.WaitForExit();

      Console.WriteLine(p.ExitTime);
      Console.ReadLine();
    }
  }
}
</code>```

Once this program is running, exit Notepad and observe that we get the exception you've mentioned. Clean up and start another copy of Notepad. This time, after editing the process ID in, also uncomment the line that mentions SafeHandle.

Once this program is running once again, exit Notepad. Observe that this time we get the exit time. So you can hopefully see how this exception can arise and I think we'd both agree that the message is woefully incomplete.

aAnd it cannot magic one into existence for a process that has already exited.

1There are probably lots of extra entry points that indirectly cause these properties to be accessed and so side-effect the Handle into existence - but these are the most obvious routes for forcing the handle open.

Body:
In order to access the exit time information, the Process class needs to have an open Handle for the processa. Whilst e.g. WaitForExit will temporarily create a handle, unfortunately it closes that handle before returning.

We can force the Process class to permanently open a handle to the process by accessing its Handle or SafeHandle properties1. However, we should notice that there is still some raciness here since between constructing the Process object and accessing the SafeHandle property the process could exit.

Start an instance of Notepad, find its process ID and edit it into the first line of Main here:

using System;
using System.Diagnostics;

namespace PlayAreaCSCon
{
  internal class Program
  {
    public static void Main(string[] args)
    {
      var p = Process.GetProcessById(18148);
      //var sh = p.SafeHandle;
      p.WaitForExit();

      Console.WriteLine(p.ExitTime);
      Console.ReadLine();
    }
  }
}

Once this program is running, exit Notepad and observe that we get the exception you've mentioned. Clean up and start another copy of Notepad. This time, after editing the process ID in, also uncomment the line that mentions SafeHandle.

Once this program is running once again, exit Notepad. Observe that this time we get the exit time. So you can hopefully see how this exception can arise and I think we'd both agree that the message is woefully incomplete.

aAnd it cannot magic one into existence for a process that has already exited.

1There are probably lots of extra entry points that indirectly cause these properties to be accessed and so side-effect the Handle into existence - but these are the most obvious routes for forcing the handle open.


问:
Python - Identify non ascii characters in dataframe
Goal: Need a process for identifying non-ascii characters in various csv files

I have csv files with non-ascii characters in some of the data (e.g. one or two employee ids out of thousands will have a random non-ascii character). I want to identify these for cleanup, but I'm getting a unicode error when I try to read in the csv which I believe is due to the same non-ascii characters. The emp_id column is normally a number and I'm converting it to a string in this example because the function I'm using won't work with integers. I need to be able to apply this code to strings and integers.

```<code>import pandas as pd
import numpy as np
isascii = lambda s: len(s) ==len(s.encode())

df = pd.read_csv("C:\\python_files\\data.csv", dtype={'EMP_ID': object})

for x in df['EMP_ID']:
    if not isascii(x):
        print(x)
</code>```

Error

```<code>UnicodeDecodeError: 'utf-8' codec can't decode byte 0x85 in position 3: invalid start byte
</code>```

Sample Data

EMP_ID

34998

34994

A2…

04™Œ

00`,

99999

答:
You should add encoding to your read_csv code:

```<code>df = pd.read_csv("C:\\python_files\\data.csv", dtype={'EMP_ID': object}, encoding='utf8')
</code>```

Body:
Goal: Need a process for identifying non-ascii characters in various csv files

I have csv files with non-ascii characters in some of the data (e.g. one or two employee ids out of thousands will have a random non-ascii character). I want to identify these for cleanup, but I'm getting a unicode error when I try to read in the csv which I believe is due to the same non-ascii characters. The emp_id column is normally a number and I'm converting it to a string in this example because the function I'm using won't work with integers. I need to be able to apply this code to strings and integers.

import pandas as pd
import numpy as np
isascii = lambda s: len(s) ==len(s.encode())

df = pd.read_csv("C:\\python_files\\data.csv", dtype={'EMP_ID': object})

for x in df['EMP_ID']:
    if not isascii(x):
        print(x)

Error

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x85 in position 3: invalid start byte

Sample Data

EMP_ID

34998

34994

A2…

04™Œ

00`,

99999

Body:
You should add encoding to your read_csv code:

df = pd.read_csv("C:\\python_files\\data.csv", dtype={'EMP_ID': object}, encoding='utf8')


问:
Why CUDA shared memory is slower than global memory in tiled matrix multiplication?
I have tiled matrix multiplication code with and without shared memory. Below is matrix multiplication using global memory:

```<code>__global__
void MatrixMulKernel(float* M, float* N, float* P, int Width)
{
int Row = blockIdx.y*blockDim.y + threadIdx.y;
int Col = blockIdx.x*blockDim.x + threadIdx.x;
if ((Row < Width) && (Col < Width)) {
    float Pvalue = 0;
    for (int k = 0; k < Width; ++k)
    {
        Pvalue += M[Row*Width + k] * N[k*Width + Col];
    }

    P[Row*Width + Col] = Pvalue;
}
}
</code>```

Below is matrix multiplication using shared memory:

```<code>__global__
void MatrixMulKernel(float* d_M, float* d_N, float* d_P, int Width)
{
__shared__ float Mds[blockWidth][blockWidth];
__shared__ float Nds[blockWidth][blockWidth];
int tx = threadIdx.x; int ty = threadIdx.y;
int bx = blockIdx.x; int by = blockIdx.y;

int row = by * blockWidth + ty;
int col = bx * blockWidth + tx;
float pvalue = 0;

for (int m = 0; m < Width / blockWidth; ++m)
{
    Mds[ty][tx] = d_M[row * Width + m*blockWidth + tx];
    Nds[ty][tx] = d_N[(m*blockWidth + ty)*Width + col];
    __syncthreads();
    for (int k = 0; k < blockWidth; ++k)
    {
        pvalue += Mds[ty][k]*Nds[k][tx];
    }
    __syncthreads();
}
d_P[row*Width + col] = pvalue;
}
</code>```

As much as I know using shared memory should be faster but in comparing this two codes I found code without shared memory runs about 2 seconds faster for 1600x1600 matrices. Is there any explanation for this speed difference or something goes wrong with my code?

My teacher uses "Programming Massively Parallel Processors" Book as main text resource these two codes comes from that.

Edit:

Launch-configuration for kernel:

```<code>int NumBlocks =ceil( Width / blockWidth);  // blockWidth = 16
dim3 dimGrid(NumBlocks, NumBlocks,1); // Width = 1600
dim3 dimBlock(blockWidth, blockWidth,1);
clock_t startGpuCalculation = clock();
MatrixMulKernel <<<dimGrid, dimBlock >>>(d_M, d_N, d_P, Width);
cudaThreadSynchronize();
clock_t endGpuCalculation = clock();
</code>```

答: I was Running Project In Debug Mode (VS 2017 & CUDA 9). I Run Code in Release Mode and Shared Memory Is Much Faster Than Global Memory. My Bad. </p>

Body:
I have tiled matrix multiplication code with and without shared memory. Below is matrix multiplication using global memory:

__global__
void MatrixMulKernel(float* M, float* N, float* P, int Width)
{
int Row = blockIdx.y*blockDim.y + threadIdx.y;
int Col = blockIdx.x*blockDim.x + threadIdx.x;
if ((Row < Width) && (Col < Width)) {
    float Pvalue = 0;
    for (int k = 0; k < Width; ++k)
    {
        Pvalue += M[Row*Width + k] * N[k*Width + Col];
    }

    P[Row*Width + Col] = Pvalue;
}
}

Below is matrix multiplication using shared memory:

__global__
void MatrixMulKernel(float* d_M, float* d_N, float* d_P, int Width)
{
__shared__ float Mds[blockWidth][blockWidth];
__shared__ float Nds[blockWidth][blockWidth];
int tx = threadIdx.x; int ty = threadIdx.y;
int bx = blockIdx.x; int by = blockIdx.y;

int row = by * blockWidth + ty;
int col = bx * blockWidth + tx;
float pvalue = 0;

for (int m = 0; m < Width / blockWidth; ++m)
{
    Mds[ty][tx] = d_M[row * Width + m*blockWidth + tx];
    Nds[ty][tx] = d_N[(m*blockWidth + ty)*Width + col];
    __syncthreads();
    for (int k = 0; k < blockWidth; ++k)
    {
        pvalue += Mds[ty][k]*Nds[k][tx];
    }
    __syncthreads();
}
d_P[row*Width + col] = pvalue;
}

As much as I know using shared memory should be faster but in comparing this two codes I found code without shared memory runs about 2 seconds faster for 1600x1600 matrices. Is there any explanation for this speed difference or something goes wrong with my code?

My teacher uses "Programming Massively Parallel Processors" Book as main text resource these two codes comes from that.

Edit:

Launch-configuration for kernel:

int NumBlocks =ceil( Width / blockWidth);  // blockWidth = 16
dim3 dimGrid(NumBlocks, NumBlocks,1); // Width = 1600
dim3 dimBlock(blockWidth, blockWidth,1);
clock_t startGpuCalculation = clock();
MatrixMulKernel <<<dimGrid, dimBlock >>>(d_M, d_N, d_P, Width);
cudaThreadSynchronize();
clock_t endGpuCalculation = clock();


问:
how do you organize your programming work
I'm a newbie in the field, but in the near future I have to develop an application for a friend(I've already did some work of the app and the friend is happy).

I assume that I need 3 places to store my work, but I'm not sure if this is the best approach. I need your advice, opinion, link,book, blog about this subject.

I plan to have:

a place where I develop the application

a place where I keep a back-up of the application

a place with the application ready for use

I'll use git in the development stage, but for the later I don't know what tools to use, or which are the good practices. Can you give me an advice?

PS: at this moment I'm using cakephp to build some webapps, but I play with C++ from time to time too.

答:
External version control (github, bitbucket)

Eg. rsync to Dropbox folder

Production stuff should be generated programmatically from some tool version controlled in step 1


问:
Take the mean of values in a list if a duplicate is found
I have 2 lists which are associated with each other. E.g., here, 'John' is associated with '1', 'Bob' is associated with 4, and so on:

```<code>l1 = ['John', 'Bob', 'Stew', 'John']
l2 = [1, 4, 7, 3]
</code>```

My problem is with the duplicate John. Instead of adding the duplicate John, I want to take the mean of the values associated with the Johns, i.e., 1 and 3, which is (3 + 1)/2 = 2. Therefore, I would like the lists to actually be:

```<code>l1 = ['John', 'Bob', 'Stew']
l2 = [2, 4, 7]
</code>```

I have experimented with some solutions including for-loops and the "contains" function, but can't seem to piece it together. I'm not very experienced with Python, but linked lists sound like they could be used for this.

Thank you

答:
Hope following code helps</p>

```<code>l1 = ['John', 'Bob', 'Stew', 'John']
l2 = [1, 4, 7, 3]

def remove_repeating_names(names_list, numbers_list):
    new_names_list = []
    new_numbers_list = []
    for first_index, first_name in enumerate(names_list):
        amount_of_occurencies = 1
        number = numbers_list[first_index]
        for second_index, second_name in enumerate(names_list):
            # Check if names match and
            # if this name wasn't read in earlier cycles or is not same element.
            if (second_name == first_name):
                if (first_index < second_index):
                    number += numbers_list[second_index]
                    amount_of_occurencies += 1
            # Break the loop if this name was read earlier.
                elif (first_index > second_index):
                    amount_of_occurencies = -1
                    break
        if amount_of_occurencies is not -1:
            new_names_list.append(first_name)
            new_numbers_list.append(number/amount_of_occurencies)
    return [new_names_list, new_numbers_list]

# Unmodified arrays
print(l1)
print(l2)

l1, l2 = remove_repeating_names(l1, l2)

# If you want numbers list to be integer, not float, uncomment following line:
# l2 = [int(number) for number in l2]

# Modified arrays
print(l1)
print(l2)
</code>```

Body:
I have 2 lists which are associated with each other. E.g., here, 'John' is associated with '1', 'Bob' is associated with 4, and so on:

l1 = ['John', 'Bob', 'Stew', 'John']
l2 = [1, 4, 7, 3]

My problem is with the duplicate John. Instead of adding the duplicate John, I want to take the mean of the values associated with the Johns, i.e., 1 and 3, which is (3 + 1)/2 = 2. Therefore, I would like the lists to actually be:

l1 = ['John', 'Bob', 'Stew']
l2 = [2, 4, 7]

I have experimented with some solutions including for-loops and the "contains" function, but can't seem to piece it together. I'm not very experienced with Python, but linked lists sound like they could be used for this.

Thank you

Body:
Hope following code helps

l1 = ['John', 'Bob', 'Stew', 'John']
l2 = [1, 4, 7, 3]

def remove_repeating_names(names_list, numbers_list):
    new_names_list = []
    new_numbers_list = []
    for first_index, first_name in enumerate(names_list):
        amount_of_occurencies = 1
        number = numbers_list[first_index]
        for second_index, second_name in enumerate(names_list):
            # Check if names match and
            # if this name wasn't read in earlier cycles or is not same element.
            if (second_name == first_name):
                if (first_index < second_index):
                    number += numbers_list[second_index]
                    amount_of_occurencies += 1
            # Break the loop if this name was read earlier.
                elif (first_index > second_index):
                    amount_of_occurencies = -1
                    break
        if amount_of_occurencies is not -1:
            new_names_list.append(first_name)
            new_numbers_list.append(number/amount_of_occurencies)
    return [new_names_list, new_numbers_list]

# Unmodified arrays
print(l1)
print(l2)

l1, l2 = remove_repeating_names(l1, l2)

# If you want numbers list to be integer, not float, uncomment following line:
# l2 = [int(number) for number in l2]

# Modified arrays
print(l1)
print(l2)