问:
Convert all records in postgres to Titlecase, first letter uppercase
I have a simple table in PostgreSQL called keywords with a simple text field called name. I want to convert all names of keywords in first letter uppercase. Is there a way to do it from psql console? </p>

答:
@denis, Gave the Right Answer!

But in my case I use PgAdmin3 , so after selecting the database there is SQL query Options , So there we can directly add the above query in it.

I had a table called subcategory_subcategory(name of table) in that i wanted to change a column values whose name was Item_name(name of column ) , so my query was like this

```<code>update subcategory_subcategory
set Item_name = initcap(Item_name)
</code>```

Body:
@denis, Gave the Right Answer!

But in my case I use PgAdmin3 , so after selecting the database there is SQL query Options , So there we can directly add the above query in it.

I had a table called subcategory_subcategory(name of table) in that i wanted to change a column values whose name was Item_name(name of column ) , so my query was like this

update subcategory_subcategory
set Item_name = initcap(Item_name)


来源: stackexchange

问:
Rails Blog being saved as 'nil' after publishing
I am beginner to rails and I was creating a blog post with a header image, title, author, excerpt and body text. The blog post seems to be created correctly but does not show any of the blog post. When I checked the rails console the blog posts show but they are saved as nil for everything. Please lend any support you can!

Thank you,

#app/controllers/posts_controller.rb

```<code>class PostsController < ApplicationController
  before_action :find_post, only: [:edit, :update, :show, :delete]

  # Index action to render all posts
  def index
    @posts = Post.all
  end

  # New action for creating post
  def new
    @post = Post.new
  end

  # Create action saves the post into database
  def create
    @post = Post.new
    if @post.save(post_params)
      flash[:notice] = "Successfully created post!"
      redirect_to post_path(@post)
    else
      flash[:alert] = "Error creating new post!"
      render :new
    end
  end

  # Edit action retrives the post and renders the edit page
  def edit
  end

  # Update action updates the post with the new information
  def update
    if @post.update_attributes(post_params)
      flash[:notice] = "Successfully updated post!"
      redirect_to post_path(@posts)
    else
      flash[:alert] = "Error updating post!"
      render :edit
    end
  end

  # The show action renders the individual post after retrieving the the id
  def show
    @post = Post.find(params[:id])
  end

  # The destroy action removes the post permanently from the database
  def destroy
    if @post.destroy
      flash[:notice] = "Successfully deleted post!"
      redirect_to posts_path
    else
      flash[:alert] = "Error updating post!"
    end
  end

  private

  def post_params
    params.require(:post).permit(:title, :excerpt, :image, :author, :body)
  end

  def find_post
    @post = Post.find(params[:id])
  end
end
</code>```

rails console

```<code>irb(main):002:0> @posts = Post.all
  Post Load (0.2ms)  SELECT "posts".* FROM "posts"
=> #<ActiveRecord::Relation [#<Post id: 1, title: nil, excerpt: nil, author: nil, body: nil, created_at: "2017-03-31 17:27:18", updated_at: "2017-03-31 17:27:18", image_file_name: nil, image_content_type: nil, image_file_size: nil, image_updated_at: nil>, #<Post id: 2, title: nil, excerpt: nil, author: nil, body: nil, created_at: "2017-03-31 17:46:04", updated_at: "2017-03-31 17:46:04", image_file_name: nil, image_content_type: nil, image_file_size: nil, image_updated_at: nil>]>
</code>```

show.html.erb

```<code><div class="col-sm-11 col-xs-12 blog-content">
  <h2><%= @post.title %></h2>
  <h5><%= @post.created_at.strftime('%b %d, %Y') %></h5>
  <%= image_tag(@post.image.url(:large)) %>
  <div><%= @post.body %></div>
</div>
</code>```

index.html.erb

```<code><% @posts.each do |post| %>
  <%= post.title %>
  <%= post.created_at.strftime('%b %d, %Y') %>
  <%= image_tag post.image %>
  <%= post.body %>
  <%= link_to "READ MORE", post_path(post) %>
<% end %>
</code>```

_form.html.erb

```<code><%= simple_form_for @post, html: { multipart: true } do |f| %>
  <% if @post.errors.any? %>
    <div id="error_explanation">
      <h2>
        <%= "#{pluralize(@post.errors.count, "error")} prohibited this post from being saved:" %>
      </h2>
      <ul>
        <% @post.errors.full_messages.each do |msg| %>
          <li>
            <%= msg %>
          </li>
          <% end %>
      </ul>
    </div>
  <% end %>

  <div class="form-group">
    <%= f.input :title, class: "form-control" %>
  </div>

  <div class="form-group">
    <%= f.input :excerpt, class: "form-control" %>
  </div>

  <div class="form-group">
    <%= f.input :author, class: "form-control" %>
  </div>

  <div class="form-group">
    <%= f.label :image %>
    <%= f.file_field :image, class: 'form-control' %>
  </div>

  <div class="form-group">
    <%= f.input :body, :as => :ckeditor, input_html: {:ckeditor => {:toolbar => 'FULL'}}, class: "form-control" %>
  </div>

  <div class="form-group">
    <%= f.button :submit %>
  </div>
<% end %>
</code>```

post.rb

```<code>class Post < ApplicationRecord
  has_attached_file :image, styles: { icon: "150x150", small: "350x350", med: "500x500", large: "750x750" }
  validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/
end
</code>```

If you have any suggestions or if you need more information to help solve this problem please let me know.

Thank you,

答:
You should be passing the post_params to Post.new in your controller instead of Post#save your create action should look like this:

```<code># Create action saves the post into database
def create
  @post = Post.new(post_params)
  if @post.save
    flash[:notice] = "Successfully created post!"
    redirect_to post_path(@post)
  else
    flash[:alert] = "Error creating new post!"
    render :new
  end
end
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am beginner to rails and I was creating a blog post with a header image, title, author, excerpt and body text. The blog post seems to be created correctly but does not show any of the blog post. When I checked the rails console the blog posts show but they are saved as nil for everything. Please lend any support you can!

Thank you,

#app/controllers/posts_controller.rb

class PostsController < ApplicationController
  before_action :find_post, only: [:edit, :update, :show, :delete]

  # Index action to render all posts
  def index
    @posts = Post.all
  end

  # New action for creating post
  def new
    @post = Post.new
  end

  # Create action saves the post into database
  def create
    @post = Post.new
    if @post.save(post_params)
      flash[:notice] = "Successfully created post!"
      redirect_to post_path(@post)
    else
      flash[:alert] = "Error creating new post!"
      render :new
    end
  end

  # Edit action retrives the post and renders the edit page
  def edit
  end

  # Update action updates the post with the new information
  def update
    if @post.update_attributes(post_params)
      flash[:notice] = "Successfully updated post!"
      redirect_to post_path(@posts)
    else
      flash[:alert] = "Error updating post!"
      render :edit
    end
  end

  # The show action renders the individual post after retrieving the the id
  def show
    @post = Post.find(params[:id])
  end

  # The destroy action removes the post permanently from the database
  def destroy
    if @post.destroy
      flash[:notice] = "Successfully deleted post!"
      redirect_to posts_path
    else
      flash[:alert] = "Error updating post!"
    end
  end

  private

  def post_params
    params.require(:post).permit(:title, :excerpt, :image, :author, :body)
  end

  def find_post
    @post = Post.find(params[:id])
  end
end

rails console

irb(main):002:0> @posts = Post.all
  Post Load (0.2ms)  SELECT "posts".* FROM "posts"
=> #<ActiveRecord::Relation [#<Post id: 1, title: nil, excerpt: nil, author: nil, body: nil, created_at: "2017-03-31 17:27:18", updated_at: "2017-03-31 17:27:18", image_file_name: nil, image_content_type: nil, image_file_size: nil, image_updated_at: nil>, #<Post id: 2, title: nil, excerpt: nil, author: nil, body: nil, created_at: "2017-03-31 17:46:04", updated_at: "2017-03-31 17:46:04", image_file_name: nil, image_content_type: nil, image_file_size: nil, image_updated_at: nil>]>

show.html.erb

<%= @post.title %>

<%= @post.created_at.strftime('%b %d, %Y') %>

  <%= image_tag(@post.image.url(:large)) %>

<%= @post.body %>

index.html.erb

<% @posts.each do |post| %>
  <%= post.title %>
  <%= post.created_at.strftime('%b %d, %Y') %>
  <%= image_tag post.image %>
  <%= post.body %>
  <%= link_to "READ MORE", post_path(post) %>
<% end %>

_form.html.erb

<%= simple_form_for @post, html: { multipart: true } do |f| %>
  <% if @post.errors.any? %>

        <%= "#{pluralize(@post.errors.count, "error")} prohibited this post from being saved:" %>

        <% @post.errors.full_messages.each do |msg| %>

            <%= msg %>

          <% end %>

  <% end %>

    <%= f.input :title, class: "form-control" %>

    <%= f.input :excerpt, class: "form-control" %>

    <%= f.input :author, class: "form-control" %>

    <%= f.label :image %>
    <%= f.file_field :image, class: 'form-control' %>

    <%= f.input :body, :as => :ckeditor, input_html: {:ckeditor => {:toolbar => 'FULL'}}, class: "form-control" %>

    <%= f.button :submit %>

<% end %>

post.rb

class Post < ApplicationRecord
  has_attached_file :image, styles: { icon: "150x150", small: "350x350", med: "500x500", large: "750x750" }
  validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/
end

If you have any suggestions or if you need more information to help solve this problem please let me know.

Thank you,

Body:
You should be passing the post_params to Post.new in your controller instead of Post#save your create action should look like this:

# Create action saves the post into database
def create
  @post = Post.new(post_params)
  if @post.save
    flash[:notice] = "Successfully created post!"
    redirect_to post_path(@post)
  else
    flash[:alert] = "Error creating new post!"
    render :new
  end
end


问:
Command line - Convert any string into an identifier?
Often I'd like to be able to take a string at the command line (bash), and convert it into an identifier. Usually this is for use in a filename, branch name, or variable name, and I prefer that it:

has no spaces in it

has no special characters in it

So for example, I could take a string like so:

bug fix for #PROJECT1 item 52, null pointer

and convert it to something like this:

bug_fix_for_PROJECT1_item_52__null_pointer

I'm open to solutions in any language, e.g. bash, node, perl, python, etc, but prefer languages that are installed by default on most linux/osx machines.

答:
Just an alternate variation in perl command-line substitution, to have exactly one _ between words and not have consecutive characters like __

```<code>perl -ple 's/[^\w]/_/g;' -pe 's/__/_/g' <<<"bug fix for #PROJECT1 item 52, null pointer"
bug_fix_for_PROJECT1_item_52_null_pointer
</code>```

and a simple snippet in python as

```<code>>>> import re
>>> re.sub('[^0-9a-zA-Z]+','_','bug fix for #PROJECT1 item 52, null pointer')
'bug_fix_for_PROJECT1_item_52_null_pointer'
</code>```

Body:
Just an alternate variation in perl command-line substitution, to have exactly one _ between words and not have consecutive characters like __

perl -ple 's/[^\w]/_/g;' -pe 's/__/_/g' <<<"bug fix for #PROJECT1 item 52, null pointer"
bug_fix_for_PROJECT1_item_52_null_pointer

and a simple snippet in python as

>>> import re
>>> re.sub('[^0-9a-zA-Z]+','_','bug fix for #PROJECT1 item 52, null pointer')
'bug_fix_for_PROJECT1_item_52_null_pointer'


问:
How expensive is it to dereference a pointer?
How expensive is it to perform the dereference operation on a pointer?

I can imagine that the memory transfer is somehow proportional to the object size, but I want to know how expensive the dereference operation part is.

答: Dereferencing can be expensive mostly because it costs an instruction to fetch data from memory which might be far away and do not exhibit locality of reference. In that case, the processor should fetch data from non-cached memory and even hard disk (in case of a hard page fault).</p>

OwnerDisplayName: Tunnuz

LastEditorDisplayName: ChrisN

OwnerDisplayName: Mehrdad Afshari

ContentLicense: CC BY-SA 2.5


问:
jQuery Array problem
I am trying to create an array images to preload by getting each of the image link in the rel attributes.

I have on a page:

```<code><div id="gallery_thumbs">
  <a><img src="images/image-1-thumb.jpg" rel="images/image-1.jpg" /></a>
  <a><img src="images/image-2-thumb.jpg" rel="images/image-2.jpg" /></a>
  <a><img src="images/image-3-thumb.jpg" rel="images/image-3.jpg" /></a>
  <a><img src="images/image-4-thumb.jpg" rel="images/image-4.jpg" /></a>
</div>
</code>```

When the page loads I need to get all the rel attributes in the #gallery_thumbs a img and append these to an array like so:

```<code>preload([ 'images/image-1.jpg', 'images/image-2.jpg', 'images/image-3.jpg', 'images/image-4.jpg']);
</code>```

Can anyone help?

答:
You can use .map() to get an array of the strings you want, like this:

```<code>var arr = $("#gallery_thumbs img").map(function() {
            return $(this).attr("rel");
          }).get();
preload(arr);
</code>```

An  without a name or href is invalid though, why not have the href to go the image you want (which would degrade gracefully), and prevent that action in JavaScript?  Your markup would look like this:

```<code><div id="gallery_thumbs">
  <a href="images/image-1.jpg"><img src="images/image-1-thumb.jpg" /></a>
  <a href="images/image-2.jpg"><img src="images/image-2-thumb.jpg" /></a>
  <a href="images/image-3.jpg"><img src="images/image-3-thumb.jpg" /></a>
  <a href="images/image-4.jpg"><img src="images/image-4-thumb.jpg" /></a>
</div>
</code>```

Making the script above simpler too:

```<code>var arr = $("#gallery_thumbs a").map(function() { return this.href; }).get();
preload(arr);
</code>```

Title: jQuery Array problem

Body:
I am trying to create an array images to preload by getting each of the image link in the rel attributes.

I have on a page:

When the page loads I need to get all the rel attributes in the #gallery_thumbs a img and append these to an array like so:

preload([ 'images/image-1.jpg', 'images/image-2.jpg', 'images/image-3.jpg', 'images/image-4.jpg']);

Can anyone help?

Body:
You can use .map() to get an array of the strings you want, like this:

var arr = $("#gallery_thumbs img").map(function() {
            return $(this).attr("rel");
          }).get();
preload(arr);

An <a> without a name or href is invalid though, why not have the href to go the image you want (which would degrade gracefully), and prevent that action in JavaScript?  Your markup would look like this:

<div id="gallery_thumbs">
  <a href="images/image-1.jpg"><img src="images/image-1-thumb.jpg" /></a>
  <a href="images/image-2.jpg"><img src="images/image-2-thumb.jpg" /></a>
  <a href="images/image-3.jpg"><img src="images/image-3-thumb.jpg" /></a>
  <a href="images/image-4.jpg"><img src="images/image-4-thumb.jpg" /></a>
</div>

Making the script above simpler too:

var arr = $("#gallery_thumbs a").map(function() { return this.href; }).get();
preload(arr);


问:
How do you serve static files when using the django runserver development server?
I am using django 1.5

I am able to serve the files in production because it is being handled at the apache level. Here is my httpd.conf file:

```<code><VirtualHost *:80>
WSGIScriptAlias / /home/membership/membership/wsgi.py

Alias /static/ "/home/membership/static/"

<Directory /home/membership/static>
Order deny,allow
Allow from all
</Directory>

<Directory "/usr/lib/python2.6/site-packages/django/contrib/admin/static/admin">
    Order deny,allow
    Allow from all
</Directory>

<Directory /home/membership/membership>
<Files wsgi.py>
Order deny,allow
Satisfy Any
Allow from all
</Files>
</Directory>
</VirtualHost>
</code>```

This works fine in production because of the Alias /static/ "/home/membership/static/"

When I try and run the app in my local development environment I can't get it to serve static files I just get a page not found 404 error. I am guess that this is because when I develop locally the requests are going straight to the development server since apache is not being used.

I do have a file at /static/me.png .

Is there somewhere that I am supposed to specify to serve static files in development?

When running python manage.py collectstatic it seems to collect only the static files for the admin app. I have a file directly in the /app/static directory that I am trying to serve.

答:
If you're Serving static files during development

On your settings.py file:

```<code># Add it on your settings.py file
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"), # your static/ files folder
]
</code>```

Example:

On your root urls.py file:

```<code># add these lines
from django.conf import settings
from django.conf.urls.static import static

# Add +static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
</code>```

Example:

This is not suitable for production use! See more: https://docs.djangoproject.com/en/dev/howto/static-files/#serving-static-files-during-development

For media files on media/ directory:
https://docs.djangoproject.com/en/dev/howto/static-files/#serving-files-uploaded-by-a-user-during-development

Body:
I am using django 1.5

I am able to serve the files in production because it is being handled at the apache level. Here is my httpd.conf file:

<VirtualHost *:80>
WSGIScriptAlias / /home/membership/membership/wsgi.py

Alias /static/ "/home/membership/static/"

<Directory /home/membership/static>
Order deny,allow
Allow from all
</Directory>

<Directory "/usr/lib/python2.6/site-packages/django/contrib/admin/static/admin">
    Order deny,allow
    Allow from all
</Directory>

<Directory /home/membership/membership>
<Files wsgi.py>
Order deny,allow
Satisfy Any
Allow from all
</Files>
</Directory>
</VirtualHost>

This works fine in production because of the Alias /static/ "/home/membership/static/"

When I try and run the app in my local development environment I can't get it to serve static files I just get a page not found 404 error. I am guess that this is because when I develop locally the requests are going straight to the development server since apache is not being used.

I do have a file at /static/me.png .

Is there somewhere that I am supposed to specify to serve static files in development?

When running python manage.py collectstatic it seems to collect only the static files for the admin app. I have a file directly in the /app/static directory that I am trying to serve.

Body:
If you're Serving static files during development

On your settings.py file:

# Add it on your settings.py file
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"), # your static/ files folder
]

Example:

On your root urls.py file:

# add these lines
from django.conf import settings
from django.conf.urls.static import static

# Add +static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

Example:

This is not suitable for production use! See more: https://docs.djangoproject.com/en/dev/howto/static-files/#serving-static-files-during-development

For media files on media/ directory:
https://docs.djangoproject.com/en/dev/howto/static-files/#serving-files-uploaded-by-a-user-during-development


问:
Implicit conversion in wrapper class
I have confusion in Number Wrapper Class in Java.

These two assignments look symmetric - a char is assigned to Integer, and an int is assigned to Character. However, the first assignment

```<code>Integer i = 'a';
</code>```

gives Compilation Error, while the second assignment

```<code>Character ch2 = 97;
</code>```

is allowed. Why?

答: This is because when setting a character to an integer it's returning the ASCII code number which is a primitive int.</p>

Title: Implicit conversion in wrapper class

Body:
I have confusion in Number Wrapper Class in Java.

These two assignments look symmetric - a char is assigned to Integer, and an int is assigned to Character. However, the first assignment

Integer i = 'a';

gives Compilation Error, while the second assignment

Character ch2 = 97;

is allowed. Why?


问:
BASH_REMATCH empty
I'm trying capture the some input regex in Bash but BASH_REMATCH comes EMPTY

```<code>#!/usr/bin/env /bin/bash
INPUT=$(cat input.txt)
TASK_NAME="MailAccountFetch"

MATCH_PATTERN="(${TASK_NAME})\s+([0-9]{4}-[0-9]{2}-[0-9]{2}\s[0-9]{2}:[0-9]{2}:[0-9]{2})"

while read -r line; do
    if [[ $line =~ $MATCH_PATTERN ]]; then
        TASK_RESULT=${BASH_REMATCH[3]}
        TASK_LAST_RUN=${BASH_REMATCH[2]}
        TASK_EXECUTION_DURATION=${BASH_REMATCH[4]}
    fi
done <<< "$INPUT"
</code>```

My input is:

```<code>    MailAccountFetch                         2017-03-29 19:00:00  Success      5.0 Second(s)      2017-03-29 19:03:00
</code>```

By debugging the script (VS Code+Bash ext) I can see the INPUT string matches as the code goes inside the IF but BASH_REMATCH is not populated with my two capture groups.

I'm on:

```<code>GNU bash, version 4.4.0(1)-release (x86_64-pc-linux-gnu)
</code>```

What could be the issue?

LATER EDIT

Accepted Answer

Accepting most explanatory answer.

What finally resolved the issue:

bashdb/VS Code environment are causing the empty BASH_REMATCH. The code works OK when ran alone.

答:
As Cyrus shows in his answer, a simplified version of your code - with the same input - does work on Linux in principle.

That said, your code references capture groups  3 and 4, whereas your regex only defines 2.

In other words: ${BASH_REMATCH[3]} and ${BASH_REMATCH[4]} are empty by definition.

Note, however, that if =~ signals success, BASH_REMATCH is never fully empty: at the very least - in the absence of any capture groups - ${BASH_REMATCH[0]} will be defined.

There are some general points worth making:

Your shebang line reads #!/usr/bin/env /bin/bash, which is effectively the same as #!/bin/bash.

/usr/bin/env is typically used if you want a version other than /bin/bash to execute, one you've installed later and put in the PATH (too):

#!/usr/bin/env bash

ghoti points out that another reason for using #!/usr/bin/env bash is to also support less common platforms such as FreeBSD, where bash, if installed, is located in /usr/local/bin rather than the usual /bin.

In either scenario it is less predictable which bash binary will be executed, because it depends on the effective $PATH value at the time of invocation.

=~ is one of the few Bash features that are platform-dependent: it uses the particular regex dialect implemented by the platform's regex libraries.

\s is a character class shortcut that is not available on all platforms, notably not on macOS; the POSIX-compliant equivalent is [[:space:]].

(In your particular case, \s should work, however, because your Bash --version output suggests that you are on a Linux distro.)

It's better not to use all-uppercase shell variable names such as INPUT, so as to avoid conflicts with environment variables and special shell variables.

ContentLicense: CC BY-SA 4.0

Title: BASH_REMATCH empty

Body:
I'm trying capture the some input regex in Bash but BASH_REMATCH comes EMPTY

#!/usr/bin/env /bin/bash
INPUT=$(cat input.txt)
TASK_NAME="MailAccountFetch"

MATCH_PATTERN="(${TASK_NAME})\s+([0-9]{4}-[0-9]{2}-[0-9]{2}\s[0-9]{2}:[0-9]{2}:[0-9]{2})"

while read -r line; do
    if [[ $line =~ $MATCH_PATTERN ]]; then
        TASK_RESULT=${BASH_REMATCH[3]}
        TASK_LAST_RUN=${BASH_REMATCH[2]}
        TASK_EXECUTION_DURATION=${BASH_REMATCH[4]}
    fi
done <<< "$INPUT"

My input is:

    MailAccountFetch                         2017-03-29 19:00:00  Success      5.0 Second(s)      2017-03-29 19:03:00

By debugging the script (VS Code+Bash ext) I can see the INPUT string matches as the code goes inside the IF but BASH_REMATCH is not populated with my two capture groups.

I'm on:

GNU bash, version 4.4.0(1)-release (x86_64-pc-linux-gnu)

What could be the issue?

LATER EDIT

Accepted Answer

Accepting most explanatory answer.

What finally resolved the issue:

bashdb/VS Code environment are causing the empty BASH_REMATCH. The code works OK when ran alone.


问:
VCOS does not name a type
I'm, trying to output video from raspicam to framebuffer 0, and I'm having an issue with BCM_HOST, where I get a ton of errors from the included vcos.h.
All the errors are of the same 2 types:

```<code>'VCHPRE_' does not name a type,
'vcos_boot_t' has not been declared,
</code>```

In files: connection.h vc_ispmanx.h, message.h etc.

etc.
I'll link to a full pastebin of errors below

I don't even know where to begin solving these, I moved /opt/vc from raspbian to my sysroot folder using VisualGDB's synchronize sysroot feature, and all the include files are there.

Is this a problem with the files themselves? It can't be,

Thanks for any help,
-D

Pastebin link: https://mypastebin.com/xQdN7mZZInHx

Example:

```<code>#include <stdio.h>
#include <syslog.h>
#include <fcntl.h>
#include <linux/fb.h>
#include <sys/mman.h>

#include "bcm_host.h"
using namespace std;

int main(int argc, char **argv) {
{
    DISPMANX_DISPLAY_HANDLE_T display;
    DISPMANX_MODEINFO_T display_info;
    DISPMANX_RESOURCE_HANDLE_T screen_resource;
    VC_IMAGE_TRANSFORM_T transform;
    uint32_t image_prt;
    VC_RECT_T rect1;
    int ret;
    int fbfd = 0;
    char *fbp = 0;

    struct fb_var_screeninfo vinfo;
    struct fb_fix_screeninfo finfo;

    return 0;
}
</code>```

答: Ok, it seems that using VisualGDB sysroot synchronize tool causes some files to be copied with 0 length. I checked vcos.h and it was empty, but on my linux system it had data. Fixed by copying all the files manually. </p>

Title: VCOS does not name a type

Body:
I'm, trying to output video from raspicam to framebuffer 0, and I'm having an issue with BCM_HOST, where I get a ton of errors from the included vcos.h.
All the errors are of the same 2 types:

'VCHPRE_' does not name a type,
'vcos_boot_t' has not been declared,

In files: connection.h vc_ispmanx.h, message.h etc.

etc.
I'll link to a full pastebin of errors below

I don't even know where to begin solving these, I moved /opt/vc from raspbian to my sysroot folder using VisualGDB's synchronize sysroot feature, and all the include files are there.

Is this a problem with the files themselves? It can't be,

Thanks for any help,
-D

Pastebin link: https://mypastebin.com/xQdN7mZZInHx

Example:

#include <stdio.h>
#include <syslog.h>
#include <fcntl.h>
#include <linux/fb.h>
#include <sys/mman.h>

#include "bcm_host.h"
using namespace std;

int main(int argc, char **argv) {
{
    DISPMANX_DISPLAY_HANDLE_T display;
    DISPMANX_MODEINFO_T display_info;
    DISPMANX_RESOURCE_HANDLE_T screen_resource;
    VC_IMAGE_TRANSFORM_T transform;
    uint32_t image_prt;
    VC_RECT_T rect1;
    int ret;
    int fbfd = 0;
    char *fbp = 0;

    struct fb_var_screeninfo vinfo;
    struct fb_fix_screeninfo finfo;

    return 0;
}


问:
GoogleMock and GoogleTest in Visual Studio 2010
Has anyone successfully built gmock and gtest in Visual Studio 2010? I've tried with version 1.5.0, but I only get incomprehensible compilation errors.</p>

答:
I found this thread in google groups about issues found when building gmock-1.5.0 under VS2010. Following the thread, I've created a short readme file, which worked for me, so here it is:

Download gmock 1.5.0 from Google Mock.

Extract to library folder on the machine (e.g. C:\Libs\gmock-1.5.0). From now on, this folder will be reffered as 'GMOCK_ROOT'.

Open VS2010, and load the solution: GMOCK_ROOT\msvc\gmock.sln. Let VS convert it from VS2008 to VS2010.  Important! DO NOT double-click the solution file under GMOCK_ROOT\msvc. This resulted in a bad conversion.

Perform the following changes to sources according to the thread:

in project gmock --> Private Header Files --> gmock-internal-utils.h:

lines 201, 202: comment out the 'Helper' functions:

char Helper(To);

static char (&Helper(...))[2];  // NOLINT

lines 210-219: replace the entire #ifdef..#endif section with:

static const bool value = std::is_convertible<From, To>::value;

in project gmock_test --> Source Files --> gmock-printers_test.cc, line 848:
perform an explicit casting of the NULL argument to void*, otherwise VS will automatically regard it is a null int. The resulting line should look like this:

t10(false, 'a', 3, 4, 5, 1.5F, -2.5, str, static_cast<void*>(NULL), "10");

Build the solution. This should result in 4 warnings, which, as described below, are (probably) OK.

Hope this helps,

Boaz

VS2010 compiler warnings from step 5 (see remarks at the end):

Warning   1   warning C4996:
  'std::_Copy_impl': Function call with
  parameters that may be unsafe - this
  call relies on the caller to check
  that the passed values are correct. To
  disable this warning, use
  -D_SCL_SECURE_NO_WARNINGS. See documentation on how to use Visual C++
  'Checked Iterators'   C:\Program Files
  (x86)\Microsoft Visual Studio
  10.0\VC\include\xutility  2227    1

Warning   2   warning C4996:
  'std::_Copy_impl': Function call with
  parameters that may be unsafe - this
  call relies on the caller to check
  that the passed values are correct. To
  disable this warning, use
  -D_SCL_SECURE_NO_WARNINGS. See documentation on how to use Visual C++
  'Checked Iterators'   C:\Program Files
  (x86)\Microsoft Visual Studio
  10.0\VC\include\xutility  2227    1

Warning   4   warning C4413:
  'std::tr1::_Cons_node<_Car,_Cdr>::_Value'
  : reference member is initialized to a
  temporary that doesn't persist after
  the constructor exits C:\Program Files
  (x86)\Microsoft Visual Studio
  10.0\VC\include\tuple 137 1

Warning   3   warning C4373:
  'testing::gmock_generated_function_mockers_test::MockFoo::TakesConst':
  virtual function overrides
  'testing::gmock_generated_function_mockers_test::FooInterface::TakesConst',
  previous versions of the compiler did
  not override when parameters only
  differed by const/volatile
  qualifiers    C:\Libs\gmock-1.5.0\test\gmock-generated-function-mockers_test.cc   133 1

Remarks regarding warnings:

Warnings 1,2 are about Copy() in xutility being deprecated due to safty. As the mock library is not a part of the production release, this is OK by me.

Warning 4 is OK according to the thread.

Warning 3: not sure, but all seems to work well.


问:
Python3: What is an efficient way to compare a bunch of variables, if one of the comparison fails, do X otherwise do Y?
Say you have 10 v_t1, v_t2, v_t3, etc, threshold variables and 10 variables for current values v_c1, v_c2, v_c3, etc,, all threshold variables contain integers, all current values contain an integer or a string of "Not found". I need to compare the thresholds against the current values. If any of the current value variables are greater than the threshold, I want to run function_a otherwise run function_b

I could write out 10 different if statements and checking their return values, with a check to see if the current value contains "Not found", but that seems wrong and inefficient. Is there a better way? Maybe compare two lists together?

答:
Assuming you have a list of thresholds and a list of corresponding values, you could make a list of threshold-value pairs, using namedtuple:

```<code>from collections import namedtuple
Pair = namedtuple('Pair', ['threshold', 'value'])
pairs = [Pair(t, v) for t, v in zip(thresholds, values)]
</code>```

and loop over the pairs:

```<code>for pair in pairs:
    if pair.value != "Not found" and pair.value > pair.threshold:
        function_a()
    else:
        function_b()
</code>```

Body:
Assuming you have a list of thresholds and a list of corresponding values, you could make a list of threshold-value pairs, using namedtuple:

from collections import namedtuple
Pair = namedtuple('Pair', ['threshold', 'value'])
pairs = [Pair(t, v) for t, v in zip(thresholds, values)]

and loop over the pairs:

for pair in pairs:
    if pair.value != "Not found" and pair.value > pair.threshold:
        function_a()
    else:
        function_b()


问:
rfc6749 4.3 - Resource Owner to Auth Server direct communication?
Background

I'm building an spa and mobile app that will communicate with a rest api. I'd like to run a separate auth server to manage users (resource owners) and think the oAuth2 4.3 Resource Owner Password Credentials grant makes sense for my application.

As described in the specification, the user (resource owner) is supposed to communicate directly with my rest api (client), and my rest api (client) is then supposed to communicate with the auth server.

```<code>     +----------+
     | Resource |
     |  Owner   |
     |          |
     +----------+
          v
          |    Resource Owner
         (A) Password Credentials
          |
          v
     +---------+                                  +---------------+
     |         |>--(B)---- Resource Owner ------->|               |
     |         |         Password Credentials     | Authorization |
     | Client  |                                  |     Server    |
     |         |<--(C)---- Access Token ---------<|               |
     |         |    (w/ Optional Refresh Token)   |               |
     +---------+                                  +---------------+

            Figure 5: Resource Owner Password Credentials Flow
</code>```

However, I'd like to change that flow. I'd prefer that the user (resource owner) communicate directly with the auth server, receive tokens, and then use those tokens to communicate with my rest api (client):

```<code>                                                  +----------+
                                                  | Resource |
                                                  |  Owner   |
                                                  |          |
                                                  +----------+
                                                   v
                                Resource Owner     |
                             Password Credentials (A)
                                                   |
                                                   v
                                                  +-----------+
      ------------(G)-------- JSON -------------->| SPA / APP |
      |      -----(D)---- Access Token ----------<|           |
      |      |                                    +-----------+
      |      |                                     v         ^
      |      |                  Resource Owner     |         |
      |      |               Password Credentials (B)       (C) Access token
      |      |                                     |         |
      ^      V                                     v         ^
     +---------+                                  +---------------+
     |         |>--(E)--- Token Introspection --->|               |
     |         |                                  | Authorization |
     |  REST   |                                  |     Server    |
     |  API    |<--(F)----- Token Metadata ------<|               |
     |         |                                  |               |
     +---------+                                  +---------------+

      Figure 5: Resource Owner Password Credentials Flow (modified)
</code>```

FYI Steps (E) and (F) are as defined in RFC 7662.

Questions

I'm wondering what your thoughts are on this design. I know it's a bastardization of RFC 6749 but I think it's better suited for my needs.

Is there a better flow as defined in RFC 6749 that would meet my needs?

Is there another specification, other that RFC 6749, that would better suite my needs?

I think the pros of my flow are:

Doesn't require me to store passwords in the spa or mobile app

Allows my users to communicate directly with the auth server for login / logout, etc. completely separating the concern from my rest api(s)

Allows me to more easily add other rest api's (micro-services) without having to deal with user auth.

I think the cons are:

Requires my auth server to be public facing

Requires a few more steps

Doesn't conform to the spec, perfectly

答:
OAuth 2.0 consists of two protocol parts: how to "obtain" an access token from the Authorization Server and how to "use" an access token against a protected Resource served by a Resource Server.

The picture you've pasted from the spec just doesn't contain the leg of "using an access token" since that is generic across all grants; it just focuses on the leg of "obtaining an access token".

Your diagram puts both together in a single picture but you're mixing up the roles: the REST API is not a Client. The Client is your SPA. The API is the Resource Server. Your picture then represents a (full) standard OAuth 2.0 Resource Owner Password Credentials flow + the additional token introspection part.

Body:
Background

I'm building an spa and mobile app that will communicate with a rest api. I'd like to run a separate auth server to manage users (resource owners) and think the oAuth2 4.3 Resource Owner Password Credentials grant makes sense for my application.

As described in the specification, the user (resource owner) is supposed to communicate directly with my rest api (client), and my rest api (client) is then supposed to communicate with the auth server.

     +----------+
     | Resource |
     |  Owner   |
     |          |
     +----------+
          v
          |    Resource Owner
         (A) Password Credentials
          |
          v
     +---------+                                  +---------------+
     |         |>--(B)---- Resource Owner ------->|               |
     |         |         Password Credentials     | Authorization |
     | Client  |                                  |     Server    |
     |         |<--(C)---- Access Token ---------<|               |
     |         |    (w/ Optional Refresh Token)   |               |
     +---------+                                  +---------------+

            Figure 5: Resource Owner Password Credentials Flow

However, I'd like to change that flow. I'd prefer that the user (resource owner) communicate directly with the auth server, receive tokens, and then use those tokens to communicate with my rest api (client):

                                                  +----------+
                                                  | Resource |
                                                  |  Owner   |
                                                  |          |
                                                  +----------+
                                                   v
                                Resource Owner     |
                             Password Credentials (A)
                                                   |
                                                   v
                                                  +-----------+
      ------------(G)-------- JSON -------------->| SPA / APP |
      |      -----(D)---- Access Token ----------<|           |
      |      |                                    +-----------+
      |      |                                     v         ^
      |      |                  Resource Owner     |         |
      |      |               Password Credentials (B)       (C) Access token
      |      |                                     |         |
      ^      V                                     v         ^
     +---------+                                  +---------------+
     |         |>--(E)--- Token Introspection --->|               |
     |         |                                  | Authorization |
     |  REST   |                                  |     Server    |
     |  API    |<--(F)----- Token Metadata ------<|               |
     |         |                                  |               |
     +---------+                                  +---------------+

      Figure 5: Resource Owner Password Credentials Flow (modified)

FYI Steps (E) and (F) are as defined in RFC 7662.

Questions

I'm wondering what your thoughts are on this design. I know it's a bastardization of RFC 6749 but I think it's better suited for my needs.

Is there a better flow as defined in RFC 6749 that would meet my needs?

Is there another specification, other that RFC 6749, that would better suite my needs?

I think the pros of my flow are:

Doesn't require me to store passwords in the spa or mobile app

Allows my users to communicate directly with the auth server for login / logout, etc. completely separating the concern from my rest api(s)

Allows me to more easily add other rest api's (micro-services) without having to deal with user auth.

I think the cons are:

Requires my auth server to be public facing

Requires a few more steps

Doesn't conform to the spec, perfectly


问:
Time on server since client sent packet
I'm currently working on a game with a client and server, and am trying to figure out a way to tell the amount of time from a client sending a packet and the server receiving it (so I can check where the enemies were at that point).

I attempted sending

```<code>DateTime.Now.Subtract(DateTime.MinValue.AddYears(1969)).TotalMilliseconds
</code>```

With then client, then just check that same value on the server when it recieves the packet, and subtract them, but the issue with this is that timezones could completely break this, if the client and server are on different timezones. Also it seemed not the most accurate.

Is there a "proper" way to do this?

答:
Well sending the epoch time will not account for leap seconds, but timezone changes should not be affected if you use DateTime.UtcNow and do all processing in UTC. Using this method would allow for users to manipulate that number, since it is based of of the computers time setting. There is not real proper way to handle this. Look at many games with latency issues. This occurs for both clientside and server-side processing.

The other issue with this method, depending on the type of game, is that the reaction of a user depends on events in real time. So if you reverse time for a calculation, the result of that could have affected another players actions.

For a complex handling, I think the game 'Eve online' will slow down 'Game Time' for large fights.

Title: Time on server since client sent packet

Body:
I'm currently working on a game with a client and server, and am trying to figure out a way to tell the amount of time from a client sending a packet and the server receiving it (so I can check where the enemies were at that point).

I attempted sending

DateTime.Now.Subtract(DateTime.MinValue.AddYears(1969)).TotalMilliseconds

With then client, then just check that same value on the server when it recieves the packet, and subtract them, but the issue with this is that timezones could completely break this, if the client and server are on different timezones. Also it seemed not the most accurate.

Is there a "proper" way to do this?


问:
Change text of a cell on dataGridView_CellFormatting
I have a Datagridview column with a value as int. I have a condition for the value status, if(status == 1) then change text to Active, else change text to Not Active.

Any help would be much appreciated.

```<code>private void bindListToGridView(List<Employee> list)
{
     // DataTable dt2 = convertListToDataTable(list);
     // more codes here.
     using (dt2)
     {
        // more codes here.
        dataGridView1.Columns[8].Name = "Status";
        dataGridView1.Columns[8].HeaderText = "Status";
        dataGridView1.Columns[8].DataPropertyName = "status";

       dataGridView1.DataSource = dt2;
     }
 }
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    string columnName = dataGridView1.Columns[e.ColumnIndex].Name;
    if (columnName == "Status")
    {
        int value = (int)dataGridView1.Rows[e.RowIndex].Cells["Status"].Value;
        if (value == 1)
        {
           // set the cell text = Active
        }
        else
        {
            // set the cell text = Not Active
        }
    }
}
</code>```

答:
To avoid changing the underlying integer value, you can set the cell's format to the desired text:

```<code>if (value == 1)
{
    dataGridView1.Rows[e.RowIndex].Cells["Status"].Style.Format = "Active";
}
else
{
    dataGridView1.Rows[e.RowIndex].Cells["Status"].Style.Format = "Not Active";
}
</code>```

Or more easily, as LarsTech pointed out, just equivalently set:

```<code>e.Value = "Active";
</code>```

This works because we are already in the CellFormatting event handler and the Value property of DataGridViewCellFormattingEventArgs is the formatted converted value.

Body:
I have a Datagridview column with a value as int. I have a condition for the value status, if(status == 1) then change text to Active, else change text to Not Active.

Any help would be much appreciated.

private void bindListToGridView(List<Employee> list)
{
     // DataTable dt2 = convertListToDataTable(list);
     // more codes here.
     using (dt2)
     {
        // more codes here.
        dataGridView1.Columns[8].Name = "Status";
        dataGridView1.Columns[8].HeaderText = "Status";
        dataGridView1.Columns[8].DataPropertyName = "status";

       dataGridView1.DataSource = dt2;
     }
 }
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    string columnName = dataGridView1.Columns[e.ColumnIndex].Name;
    if (columnName == "Status")
    {
        int value = (int)dataGridView1.Rows[e.RowIndex].Cells["Status"].Value;
        if (value == 1)
        {
           // set the cell text = Active
        }
        else
        {
            // set the cell text = Not Active
        }
    }
}

Body:
To avoid changing the underlying integer value, you can set the cell's format to the desired text:

if (value == 1)
{
    dataGridView1.Rows[e.RowIndex].Cells["Status"].Style.Format = "Active";
}
else
{
    dataGridView1.Rows[e.RowIndex].Cells["Status"].Style.Format = "Not Active";
}

Or more easily, as LarsTech pointed out, just equivalently set:

e.Value = "Active";

This works because we are already in the CellFormatting event handler and the Value property of DataGridViewCellFormattingEventArgs is the formatted converted value.


问:
Spring SAML - Using multiple IDP certificates from keystore instead of metadata XML

I was able to integrate my application (SP) with Okta (IDP).

I will be only performing IDP-initiated logins.

But Okta will not be my only IDP and I do not want to keep adding new IDP metadata XML's to my applications (because that means I need to edit my spring XML file and add a new IDP and restart the server).

So I just want to import the IDP x509certificates (public key) into my keystore and use them to verify my SAML responses. Is that possible?
Or in other words, I want to register an IDP at runtime without making any changes to my application or restarting it.

If yes, can you provide resources on how to do that?

Currently I have provided Okta's metadata XML like below in my application's spring xml file.

```<code><bean id="metadata" class="org.springframework.security.saml.metadata.MetadataManager">
    <constructor-arg>
        <list>
        <bean class="org.opensaml.saml2.metadata.provider.FilesystemMetadataProvider">
            <constructor-arg>
                <value type="java.io.File">C:\\DEV\\idp_metadata\\metadata.xml</value>
            </constructor-arg>
                <property name="parserPool" ref="parserPool" />
        </bean>
        </list>
    </constructor-arg>

</bean>
</code>```

Thanks,

Abhishek

答:
I completed the changes to my application to make it dependent on an IDP's certificate present in a keystore.
But with a caveat, if a new IDP certificate is added in future, it requires a server restart.

I changed the securityProfile to pkix instead of the default metaIOP

<bean class="org.springframework.security.saml.metadata.ExtendedMetadataDelegate">
   <constructor-arg>
      <bean class="org.opensaml.saml2.metadata.provider.ResourceBackedMetadataProvider">
         <constructor-arg>
            <bean class="java.util.Timer" />
         </constructor-arg>
         <constructor-arg>
            <bean class="org.opensaml.util.resource.FilesystemResource">
               <constructor-arg value="${path.to.SP.metadata}" />
            </bean>
         </constructor-arg>
         <property name="parserPool" ref="parserPool" />
      </bean>
   </constructor-arg>
   <constructor-arg>
      <bean class="org.springframework.security.saml.metadata.ExtendedMetadata">
         <property name="local" value="true" />
         <property name="securityProfile" value="pkix" />
         <property name="sslSecurityProfile" value="pkix" />
         <property name="requireArtifactResolveSigned" value="false" />
         <property name="requireLogoutRequestSigned" value="false" />
         <property name="requireLogoutResponseSigned" value="false" />
         <property name="idpDiscoveryEnabled" value="false" />
         <property name="supportUnsolicitedResponse" value="true" />
      </bean>
   </constructor-arg>
</bean>

Added the certificate to a .jks file: keytool -importcert -file certificate.txt -keystore keystore.jks -alias "Alias"

Implemented a SAMLContextProviderLB and injected pkixresolver

<bean id="contextProvider" class="org.springframework.security.saml.context.SAMLContextProviderLB">
   <property name="scheme" value="${saml.loadBalancer.scheme}" />
   <property name="serverName" value="${saml.loadBalancer.serverName}" />
   <property name="serverPort" value="${saml.loadBalancer.serverPort}" />
   <property name="includeServerPortInRequestURL" value="${saml.loadBalancer.includeServerPortInRequestURL}" />
   <property name="contextPath" value="/contextPath" />
   <property name="pkixResolver">
      <bean class="org.springframework.security.saml.trust.PKIXInformationResolver">
         <constructor-arg index="0" ref="metadataCredResolver" />
         <constructor-arg index="1" ref="metadata" />
         <constructor-arg index="2" ref="trustedKeyManager" />
      </bean>
   </property>
   <property name="storageFactory">
      <bean class="org.springframework.security.saml.storage.EmptyStorageFactory" />
   </property>
</bean>

<bean id="metadataCredResolver" class="org.springframework.security.saml.trust.MetadataCredentialResolver">
   <constructor-arg index="0" ref="metadata" />
   <constructor-arg index="1" ref="trustedKeyManager" />
   <property name="useXmlMetadata" value="false" />
</bean>

<bean id="trustedKeyManager" class="org.springframework.security.saml.key.JKSKeyManager">
   <constructor-arg value="${saml.trust.jks.filePath}" />
   <constructor-arg type="java.lang.String" value="${saml.trust.jks.password}" />
   <constructor-arg>
      <map>
         <entry key="${saml.trust.jks.defaultKey.name}" value="${saml.trust.jks.defaultKey.password}" />
      </map>
   </constructor-arg>
   <constructor-arg type="java.lang.String" value="${saml.trust.jks.defaultKey.name}" />
</bean>

Implemented a few classes to override the need of a metadata XML.
SAMLProcessorImpl and WebSSOProfileConsumerImpl

I remove the dependency on getPeerEntityID / getPeerEntityMetadata.getEntityID() and replace it with response.getIssuer().getValue() because both have to be the same for SAML to work.
The trust certificates are obtained from the keystore which is loaded once during startup.

In my next update I will try to figure out how to perform a timed refresh of the .jks file to load new certificates.

Body:
I was able to integrate my application (SP) with Okta (IDP).

I will be only performing IDP-initiated logins.

But Okta will not be my only IDP and I do not want to keep adding new IDP metadata XML's to my applications (because that means I need to edit my spring XML file and add a new IDP and restart the server).

So I just want to import the IDP x509certificates (public key) into my keystore and use them to verify my SAML responses. Is that possible?
Or in other words, I want to register an IDP at runtime without making any changes to my application or restarting it.

If yes, can you provide resources on how to do that?

Currently I have provided Okta's metadata XML like below in my application's spring xml file.

<bean id="metadata" class="org.springframework.security.saml.metadata.MetadataManager">
    <constructor-arg>
        <list>
        <bean class="org.opensaml.saml2.metadata.provider.FilesystemMetadataProvider">
            <constructor-arg>
                <value type="java.io.File">C:\\DEV\\idp_metadata\\metadata.xml</value>
            </constructor-arg>
                <property name="parserPool" ref="parserPool" />
        </bean>
        </list>
    </constructor-arg>

</bean>

Thanks,

Abhishek


问:
How can I make both columns same height in Bootstrap?
I have 2 columns in bootstrap side-by-side, col-md-4 and col-md-8 but one is taller than the other.

How can I shrink the taller one to match the height of the smaller column?

The css class listing-top is using flex box.

DEMO https://jsfiddle.net/halnex/3dw85L1r/1/

HTML

```<code><section class="listing listing-top with-feature">
    <div class="col-md-4">
        <article class="tease top-latest tease-" data-post-id="1069327">

            <a class="overlay" href="#"></a>
            <div class="tag"></div>
            <figure style="background-image:url('http://i.imgur.com/WDCTb5S.jpg');">
                <div></div>
            </figure>
            <header>
                <h2><a href="#">Galaxy S8 face recognition already defeated with a simple picture</a></h2>
                <p class="excerpt">Face unlock feature once again defeated with anything resembling owner's face. </p>

                <p class="byline" itemprop="author creator" itemscope="" itemtype="#">
                    <a itemprop="url" href="#"><span itemprop="name">Author</span></a>
                    –  <time class="date" data-time="1490974219" datetime="2017-03-31T15:30:19+00:00">3/31/2017, 6:30 PM</time>
                </p>

            </header>
            <footer>
                <aside class="comments-hotness ">
                    <a title="25 posters participating" class="comment-count icon-comment-bubble-up" href="#">
                        <span class="comment-count-number">31</span>
                    </a>    </aside>

            </footer>
        </article>
    </div>

    <div class="col-md-8">
        <article class="tease top-latest tease-" data-post-id="1069327">

            <a class="overlay" href="#"></a>
            <div class="tag"></div>
            <figure style="background-image:url('http://i.imgur.com/WDCTb5S.jpg');">
                <div></div>
            </figure>
            <header>
                <h2><a href="#">Galaxy S8 face recognition already defeated with a simple picture</a></h2>
                <p class="excerpt">Face unlock feature once again defeated with anything resembling owner's face. </p>

                <p class="byline" itemprop="author creator" itemscope="" itemtype="#">
                    <a itemprop="url" href="#"><span itemprop="name">Author</span></a>
                    –  <time class="date" data-time="1490974219" datetime="2017-03-31T15:30:19+00:00">3/31/2017, 6:30 PM</time>
                </p>

            </header>
            <footer>
                <aside class="comments-hotness ">
                    <a title="25 posters participating" class="comment-count icon-comment-bubble-up" href="#">
                        <span class="comment-count-number">31</span>
                    </a>    </aside>

            </footer>
        </article>
    </div>
</section>
</code>```

CSS

```<code>.listing-top {
    -js-display: flex;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
    -ms-flex-flow: row wrap;
    flex-flow: row wrap;
    -webkit-box-pack: justify;
    -ms-flex-pack: justify;
    justify-content: space-between;
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
}
.listing-top.with-feature article.top-latest {
    margin-bottom: 20px;
    position: relative;
    cursor: pointer;
    cursor: hand;
    display: block;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -ms-flex-flow: none;
    flex-flow: none;
}
.listing-top.with-feature article.top-latest .overlay {
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 14;
}
.listing-top.with-feature article.top-latest .tag {
    -js-display: flex;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
    -ms-flex-flow: row nowrap;
    flex-flow: row nowrap;
}
.listing-top.with-feature article.top-latest .tag {
    pointer-events: none;
    position: absolute;
    height: 36px;
    z-index: 15;
    background-color: #fff;
    color: #000;
    text-transform: uppercase;
    font-size: 20px;
    font-family: economica;
    top: 15px;
    left: 0;
    display: none;
}
.listing-top.with-feature article .tag {
    pointer-events: none;
    position: absolute;
    height: 36px;
    z-index: 15;
    background-color: #fff;
    color: #000;
    text-transform: uppercase;
    font-size: 20px;
    font-family: economica;
    top: 15px;
    left: 0;
    display: none;
}
.listing-top.with-feature article.top-latest figure {
    width: 100%;
    height: 0;
    padding-bottom: 55.55556%;
}
.listing-top.with-feature article.top-latest figure {
    -webkit-transition: all .17s;
    transition: all .17s;
    background-repeat: no-repeat;
    background-size: cover;
    background-position: top;
    background-color: #f0f1f2;
    background-blend-mode: multiply;
    margin: 0;
}
.listing-top.with-feature article figure {
    width: 100%;
    height: 0;
    padding-bottom: 55.55556%;
}
.listing-top.with-feature article figure {
    -webkit-transition: all .17s;
    transition: all .17s;
    background-repeat: no-repeat;
    background-size: cover;
    background-position: top;
    background-color: #f0f1f2;
    background-blend-mode: multiply;
    margin: 0;
}
figure {
    margin: 1em 40px;
}
article, aside, details, figcaption, figure, footer, header, main, menu, nav, section, summary {
    display: block;
}
.listing-top.with-feature article.top-latest header {
    background: -webkit-linear-gradient(top,#fff 15px,hsla(210,7%,95%,0));
    background: linear-gradient(180deg,#fff 15px,hsla(210,7%,95%,0));
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr="#ffffff",endColorstr="#00f0f1f2",GradientType=0);
    margin: 15px;
    margin-top: -15px;
    padding: 15px;
    border-bottom: none;
    position: relative;
}
.listing-top.with-feature article header {
    background: -webkit-linear-gradient(top,#fff 15px,hsla(210,7%,95%,0));
    background: linear-gradient(180deg,#fff 15px,hsla(210,7%,95%,0));
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr="#ffffff",endColorstr="#00f0f1f2",GradientType=0);
    margin: 15px;
    margin-top: -15px;
    padding: 15px;
    border-bottom: none;
    position: relative;
}
.listing-top.with-feature article.top-latest footer {
    width: 100%;
    margin-top: -25px;
    bottom: -10px;
}
.listing-top.with-feature article.top-latest footer {
    position: absolute;
    z-index: 15;
}
.listing-top.with-feature article.top-latest:after {
    content: "";
    position: absolute;
    bottom: 0;
    height: 30px;
    width: 100%;
    border: 15px solid #ccc;
    border-top: none;
}
.listing-top.with-feature article:after {
    content: "";
    position: absolute;
    bottom: 0;
    height: 30px;
    width: 100%;
    border: 15px solid #ccc;
    border-top: none;
}
.listing-top.with-feature article.top-latest footer .comments-hotness .comment-count {
    background-size: cover;
    width: 34px;
    height: 34px;
    display: block;
    margin: 0 auto;
    text-align: center;
    background-position: 50%;
}
.listing-top.with-feature article.top-latest footer .comments-hotness .comment-count .comment-count-number {
    padding: 0;
    margin: 0;
    line-height: 34px;
    font-size: 18px;
    color: #fff;
}
.listing-top.with-feature article.top-latest footer .comments-hotness .comment-count {
    font-family: economica;
    color: #fff;
    background-repeat: no-repeat;
    display: block;
    background-image: url('../img/comments.svg');
}
@media (min-width: 1000px) {
    .listing-top.with-feature article.top-latest .tag:before {
        top: 11px;
        height: 14px;
        width: 18px;
        background-image: url('../img/arrow.svg');
    }
}
.listing-top.with-feature article.top-latest .tag:before {
    background-image: url('../img/arrows.svg');
    height: 9px;
    width: 18px;
    top: 13px;
    right: 10px;
}
.listing-top.with-feature article.top-latest .tag:before {
    content: "";
    position: absolute;
    background-repeat: no-repeat;
    background-size: cover;
}
.listing-top.with-feature article .tag:before {
    content: "";
    position: absolute;
    background-repeat: no-repeat;
    background-size: cover;
}
.listing-top.with-feature article.top-latest .tag:after {
    content: "Latest stories";
    margin-left: 10px;
    margin-right: 36px;
}
.listing-top.with-feature article.top-latest .tag:after {
    content: "";
    -ms-flex-item-align: center;
    -ms-grid-row-align: center;
    align-self: center;
}
.listing-top.with-feature article .tag:after {
    content: "";
    -ms-flex-item-align: center;
    -ms-grid-row-align: center;
    align-self: center;
}
</code>```

答: You could use Foundation instead and use data-equalizer. Awesome tool :)</p>

Body:
I have 2 columns in bootstrap side-by-side, col-md-4 and col-md-8 but one is taller than the other.

How can I shrink the taller one to match the height of the smaller column?

The css class listing-top is using flex box.

DEMO https://jsfiddle.net/halnex/3dw85L1r/1/

HTML

Galaxy S8 face recognition already defeated with a simple picture

Face unlock feature once again defeated with anything resembling owner's face.

                    Author
                    –  <time class="date" data-time="1490974219" datetime="2017-03-31T15:30:19+00:00">3/31/2017, 6:30 PM</time>

                        31

Galaxy S8 face recognition already defeated with a simple picture

Face unlock feature once again defeated with anything resembling owner's face.

                    Author
                    –  <time class="date" data-time="1490974219" datetime="2017-03-31T15:30:19+00:00">3/31/2017, 6:30 PM</time>

                        31

CSS

.listing-top {
    -js-display: flex;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
    -ms-flex-flow: row wrap;
    flex-flow: row wrap;
    -webkit-box-pack: justify;
    -ms-flex-pack: justify;
    justify-content: space-between;
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
}
.listing-top.with-feature article.top-latest {
    margin-bottom: 20px;
    position: relative;
    cursor: pointer;
    cursor: hand;
    display: block;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -ms-flex-flow: none;
    flex-flow: none;
}
.listing-top.with-feature article.top-latest .overlay {
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 14;
}
.listing-top.with-feature article.top-latest .tag {
    -js-display: flex;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
    -ms-flex-flow: row nowrap;
    flex-flow: row nowrap;
}
.listing-top.with-feature article.top-latest .tag {
    pointer-events: none;
    position: absolute;
    height: 36px;
    z-index: 15;
    background-color: #fff;
    color: #000;
    text-transform: uppercase;
    font-size: 20px;
    font-family: economica;
    top: 15px;
    left: 0;
    display: none;
}
.listing-top.with-feature article .tag {
    pointer-events: none;
    position: absolute;
    height: 36px;
    z-index: 15;
    background-color: #fff;
    color: #000;
    text-transform: uppercase;
    font-size: 20px;
    font-family: economica;
    top: 15px;
    left: 0;
    display: none;
}
.listing-top.with-feature article.top-latest figure {
    width: 100%;
    height: 0;
    padding-bottom: 55.55556%;
}
.listing-top.with-feature article.top-latest figure {
    -webkit-transition: all .17s;
    transition: all .17s;
    background-repeat: no-repeat;
    background-size: cover;
    background-position: top;
    background-color: #f0f1f2;
    background-blend-mode: multiply;
    margin: 0;
}
.listing-top.with-feature article figure {
    width: 100%;
    height: 0;
    padding-bottom: 55.55556%;
}
.listing-top.with-feature article figure {
    -webkit-transition: all .17s;
    transition: all .17s;
    background-repeat: no-repeat;
    background-size: cover;
    background-position: top;
    background-color: #f0f1f2;
    background-blend-mode: multiply;
    margin: 0;
}
figure {
    margin: 1em 40px;
}
article, aside, details, figcaption, figure, footer, header, main, menu, nav, section, summary {
    display: block;
}
.listing-top.with-feature article.top-latest header {
    background: -webkit-linear-gradient(top,#fff 15px,hsla(210,7%,95%,0));
    background: linear-gradient(180deg,#fff 15px,hsla(210,7%,95%,0));
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr="#ffffff",endColorstr="#00f0f1f2",GradientType=0);
    margin: 15px;
    margin-top: -15px;
    padding: 15px;
    border-bottom: none;
    position: relative;
}
.listing-top.with-feature article header {
    background: -webkit-linear-gradient(top,#fff 15px,hsla(210,7%,95%,0));
    background: linear-gradient(180deg,#fff 15px,hsla(210,7%,95%,0));
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr="#ffffff",endColorstr="#00f0f1f2",GradientType=0);
    margin: 15px;
    margin-top: -15px;
    padding: 15px;
    border-bottom: none;
    position: relative;
}
.listing-top.with-feature article.top-latest footer {
    width: 100%;
    margin-top: -25px;
    bottom: -10px;
}
.listing-top.with-feature article.top-latest footer {
    position: absolute;
    z-index: 15;
}
.listing-top.with-feature article.top-latest:after {
    content: "";
    position: absolute;
    bottom: 0;
    height: 30px;
    width: 100%;
    border: 15px solid #ccc;
    border-top: none;
}
.listing-top.with-feature article:after {
    content: "";
    position: absolute;
    bottom: 0;
    height: 30px;
    width: 100%;
    border: 15px solid #ccc;
    border-top: none;
}
.listing-top.with-feature article.top-latest footer .comments-hotness .comment-count {
    background-size: cover;
    width: 34px;
    height: 34px;
    display: block;
    margin: 0 auto;
    text-align: center;
    background-position: 50%;
}
.listing-top.with-feature article.top-latest footer .comments-hotness .comment-count .comment-count-number {
    padding: 0;
    margin: 0;
    line-height: 34px;
    font-size: 18px;
    color: #fff;
}
.listing-top.with-feature article.top-latest footer .comments-hotness .comment-count {
    font-family: economica;
    color: #fff;
    background-repeat: no-repeat;
    display: block;
    background-image: url('../img/comments.svg');
}
@media (min-width: 1000px) {
    .listing-top.with-feature article.top-latest .tag:before {
        top: 11px;
        height: 14px;
        width: 18px;
        background-image: url('../img/arrow.svg');
    }
}
.listing-top.with-feature article.top-latest .tag:before {
    background-image: url('../img/arrows.svg');
    height: 9px;
    width: 18px;
    top: 13px;
    right: 10px;
}
.listing-top.with-feature article.top-latest .tag:before {
    content: "";
    position: absolute;
    background-repeat: no-repeat;
    background-size: cover;
}
.listing-top.with-feature article .tag:before {
    content: "";
    position: absolute;
    background-repeat: no-repeat;
    background-size: cover;
}
.listing-top.with-feature article.top-latest .tag:after {
    content: "Latest stories";
    margin-left: 10px;
    margin-right: 36px;
}
.listing-top.with-feature article.top-latest .tag:after {
    content: "";
    -ms-flex-item-align: center;
    -ms-grid-row-align: center;
    align-self: center;
}
.listing-top.with-feature article .tag:after {
    content: "";
    -ms-flex-item-align: center;
    -ms-grid-row-align: center;
    align-self: center;
}


问:
Using variable 'i' outside of its function
Okay, I was playing around javascript.  I wanted to create a webpage with a "change background" button that cycled between different colors.  So I wrote it like this (script tag starts out of view)

```<code> var bgcolors = ["pink", "beige", "wheat", "white", "brown"];

        var i = 0;

        function cyclebg(){

            document.body.style.backgroundColor = bgcolors[i];

            i++;

            if (i > (bgcolors.length - 1))
            {
                i = 0;
            }

        }

        //other ideas:
        //-say color next to button
    </script>
    <br>
    <br>
    <button type="button"  style="background-color:red; border-color: red;" OnClick="cyclebg()">Change Background Color</button>
</code>```

That worked just fine.  Then I decided to make an edition, and have the name of the color displayed right next to the button.  So I added...

```<code><script>document.write(bgcolors[i]);

    </script>
</code>```

However, "pink" is always written.  It seems like this "document.write" script is only capable of reading what "i" is outside the function.  Why is this?  Aren't all variables global in javaSCRIPT?  How can I get it to read what "i" is inside the function, so it displays the name of the color being used in the background?

答:
You could use a closure over the bgcolors and i by returning a function for changing the color. Then use a span tag for the color name.

var cyclebg = function() {
    var bgcolors = ["pink", "beige", "wheat", "white", "brown"],
        i = 0;

    return function() {
        document.body.style.backgroundColor = bgcolors[i];
        document.getElementById('color').innerHTML = bgcolors[i];
        i++;
        i %= bgcolors.length;
    };
}();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><br><br><button type="button" style="background-color:red; border-color: red;" onclick="cyclebg()">Change Background Color</button> <span id="color"></span></code>```

Body:
Okay, I was playing around javascript.  I wanted to create a webpage with a "change background" button that cycled between different colors.  So I wrote it like this (script tag starts out of view)

 var bgcolors = ["pink", "beige", "wheat", "white", "brown"];

        var i = 0;

        function cyclebg(){

            document.body.style.backgroundColor = bgcolors[i];

            i++;

            if (i > (bgcolors.length - 1))
            {
                i = 0;
            }

        }

        //other ideas:
        //-say color next to button
    </script>

    <button type="button"  style="background-color:red; border-color: red;" OnClick="cyclebg()">Change Background Color</button>

That worked just fine.  Then I decided to make an edition, and have the name of the color displayed right next to the button.  So I added...

However, "pink" is always written.  It seems like this "document.write" script is only capable of reading what "i" is outside the function.  Why is this?  Aren't all variables global in javaSCRIPT?  How can I get it to read what "i" is inside the function, so it displays the name of the color being used in the background?

Body:
You could use a closure over the bgcolors and i by returning a function for changing the color. Then use a span tag for the color name.

var cyclebg = function() {
    var bgcolors = ["pink", "beige", "wheat", "white", "brown"],
        i = 0;

    return function() {
        document.body.style.backgroundColor = bgcolors[i];
        document.getElementById('color').innerHTML = bgcolors[i];
        i++;
        i %= bgcolors.length;
    };
}();

<br><br><button type="button" style="background-color:red; border-color: red;" onclick="cyclebg()">Change Background Color</button> <span id="color"></span>


问:
Rails 4+, ordering list of parent records by children
I have a page that displays a lot of data and I'm working on optimizing it and I'm struggling with balancing reducing DB queries with getting the proper data in the order I need.

A Transaction is the top-level element, and each transaction has multiple workflows and each workflow has many milestones.  I order the workflows and milestones by a position:integer attribute.

```<code># Top-level element
class Transaction < ApplicationRecord
  has_many :workflows
  has_many :team_members
end

# Parent element for milestones
class Workflow < ApplicationRecord
  belongs_to :transaction
  has_many :milestones
end

# Unique individual
class Person < ApplicationRecord
  has_many :team_members
end

# Acts as a join between Transactions and Persons
class TeamMember < ApplicationRecord
  belongs_to :transaction
  belongs_to :person
  belongs_to :team_member_type
end

class TeamMemberType < ApplicationRecord
  has_many :team_members
end
</code>```

In my controller this is what I have:

```<code>def show
  @transaction = Transaction.includes(
    team_members: [:person, :team_member_type],
    workflows: [:milestones]
  ).find(params[id])
end
</code>```

This gathers all the data I need in 1 DB query, but the problem is when I iterate over the milestones for a workflow, I need it to be sorted by the position attribute.

I can grab the data from the DB and then sort it with Ruby, but that seems inefficient and I would prefer to get it all done in the DB properly (if possible).

If I were to write it with an N+1 issue, it would look like this:

```<code><% @workflows.order(:position).each do |workflow| %>
  <%= workflow.name %>
  <% workflow.milestones.order(:position).each do |milestone| %>
    <%= milestone.name %>
  <% end %>
<% end %>
</code>```

I think everyone agrees that's a bad idea, but I'm struggling to figure out how to sort the data and optimize my DB calls at the same time.

I also sort the team_members by the team_member_type.value attribute, but that's the same question as above.

```<code><% @team_members.includes(:team_member_type, :person).order("team_member_types.value").each do |team_member| %>
  ...
<% end %>
</code>```

My main objective is efficiency.  If I need to use some Query objects to clean it up and raw SQL, I'm ok with that, I'm just not extremely proficient at SQL and would prefer using ActiveRecord if reasonable.

答:
You can order by those two attributes in the controller method:

```<code>def show
  @transaction = Transaction.includes(
    team_members: [:person, :team_member_type],
    workflows: [:milestones]
  ).order('milestones.position, team_member_types.value').find(params[id])
end
</code>```

Let me know if this helps.

Body:
I have a page that displays a lot of data and I'm working on optimizing it and I'm struggling with balancing reducing DB queries with getting the proper data in the order I need.

A Transaction is the top-level element, and each transaction has multiple workflows and each workflow has many milestones.  I order the workflows and milestones by a position:integer attribute.

# Top-level element
class Transaction < ApplicationRecord
  has_many :workflows
  has_many :team_members
end

# Parent element for milestones
class Workflow < ApplicationRecord
  belongs_to :transaction
  has_many :milestones
end

# Unique individual
class Person < ApplicationRecord
  has_many :team_members
end

# Acts as a join between Transactions and Persons
class TeamMember < ApplicationRecord
  belongs_to :transaction
  belongs_to :person
  belongs_to :team_member_type
end

class TeamMemberType < ApplicationRecord
  has_many :team_members
end

In my controller this is what I have:

def show
  @transaction = Transaction.includes(
    team_members: [:person, :team_member_type],
    workflows: [:milestones]
  ).find(params[id])
end

This gathers all the data I need in 1 DB query, but the problem is when I iterate over the milestones for a workflow, I need it to be sorted by the position attribute.

I can grab the data from the DB and then sort it with Ruby, but that seems inefficient and I would prefer to get it all done in the DB properly (if possible).

If I were to write it with an N+1 issue, it would look like this:

<% @workflows.order(:position).each do |workflow| %>
  <%= workflow.name %>
  <% workflow.milestones.order(:position).each do |milestone| %>
    <%= milestone.name %>
  <% end %>
<% end %>

I think everyone agrees that's a bad idea, but I'm struggling to figure out how to sort the data and optimize my DB calls at the same time.

I also sort the team_members by the team_member_type.value attribute, but that's the same question as above.

<% @team_members.includes(:team_member_type, :person).order("team_member_types.value").each do |team_member| %>
  ...
<% end %>

My main objective is efficiency.  If I need to use some Query objects to clean it up and raw SQL, I'm ok with that, I'm just not extremely proficient at SQL and would prefer using ActiveRecord if reasonable.

Body:
You can order by those two attributes in the controller method:

def show
  @transaction = Transaction.includes(
    team_members: [:person, :team_member_type],
    workflows: [:milestones]
  ).order('milestones.position, team_member_types.value').find(params[id])
end

Let me know if this helps.


问:
json_encode PHP array as JSON array not JSON object
I have the following array in PHP:

```<code>Array
(
    [0] => Array
        (
            [id] => 0
            [name] => name1
            [short_name] => n1
        )

    [2] => Array
        (
            [id] => 2
            [name] => name2
            [short_name] => n2
        )
)
</code>```

I want to JSON encode it as a JSON array, producing a string like the following:

```<code>[
    {
        "id":0,
        "name":"name1",
        "short_name":"n1"
    },
    {
        "id":2,
        "name":"name2",
        "short_name":"n2"
    }
]
</code>```

But when I call json_encode on this array, I get the following:

```<code>{
    "0":{
        "id":0,
        "name":"name1",
        "short_name":"n1"
    },
    "2":{
        "id":2,
        "name":"name2",
        "short_name":"n2"
    }
}
</code>```

Which is an object instead of an array.

How can I get json_encode to encode my array as an array, instead?

答:
json_decode($jsondata, true);

true turns all properties to array (sequential or not)

Body:
I have the following array in PHP:

Array
(
    [0] => Array
        (
            [id] => 0
            [name] => name1
            [short_name] => n1
        )

    [2] => Array
        (
            [id] => 2
            [name] => name2
            [short_name] => n2
        )
)

I want to JSON encode it as a JSON array, producing a string like the following:

[
    {
        "id":0,
        "name":"name1",
        "short_name":"n1"
    },
    {
        "id":2,
        "name":"name2",
        "short_name":"n2"
    }
]

But when I call json_encode on this array, I get the following:

{
    "0":{
        "id":0,
        "name":"name1",
        "short_name":"n1"
    },
    "2":{
        "id":2,
        "name":"name2",
        "short_name":"n2"
    }
}

Which is an object instead of an array.

How can I get json_encode to encode my array as an array, instead?


问:
Disable Appstats logging
I'm using Appstats as documented here:

http://code.google.com/appengine/docs/python/tools/appstats.html

It works fine, but every request now logs an info message like this:

Saved; key: appstats:039300, part: 65 bytes, full: 12926 bytes, overhead: 0.000 + 0.004; link: http://example.com/stats/details?time=1290733239309

Is there a way to disable the log messages, while leaving Appstats running?

Maybe I could just take my own copy of ext/appstats/recording.py and comment out the call to logging.info()? Or is there a better way?

Thanks.

答:
In case anyone else is interested, here's how I removed the logging using Robert's monkey-patch suggestion.

The standard approach to insert appstats is like this:

```<code>def webapp_add_wsgi_middleware(app):
    from google.appengine.ext.appstats import recording
    app = recording.appstats_wsgi_middleware(app)
    return app
</code>```

This is what I did instead:

```<code>def webapp_add_wsgi_middleware(app):

    from google.appengine.ext.appstats import recording

    def save(self):
        try:
            self._save()
        except Exception:
            pass

    recording.Recorder.save = save

    app = recording.appstats_wsgi_middleware(app)

    return app
</code>```

This retains the original save() function's "ignore all exceptions" behaviour, but removes all of the logging around it.

Title: Disable Appstats logging

Body:
In case anyone else is interested, here's how I removed the logging using Robert's monkey-patch suggestion.

The standard approach to insert appstats is like this:

def webapp_add_wsgi_middleware(app):
    from google.appengine.ext.appstats import recording
    app = recording.appstats_wsgi_middleware(app)
    return app

This is what I did instead:

def webapp_add_wsgi_middleware(app):

    from google.appengine.ext.appstats import recording

    def save(self):
        try:
            self._save()
        except Exception:
            pass

    recording.Recorder.save = save

    app = recording.appstats_wsgi_middleware(app)

    return app

This retains the original save() function's "ignore all exceptions" behaviour, but removes all of the logging around it.


问:
Psycopg2 image not found
Trying to setup postgres with the postgres mac app and hit this error, which I haven't been able to solve. Any thoughts?</p>

```<code>    ImportError: dlopen(/Users/Craig/pyenv/mysite/lib/python2.7/site-packages/psycopg2/_psycopg.so, 2): Library not loaded: @executable_path/../lib/libssl.1.0.0.dylib
  Referenced from: /Applications/Postgres.app/Contents/MacOS/lib/libpq.dylib
  Reason: image not found
</code>```

答:
I'm experiencing a similar issue with mysql. The library requested is is failing to load /usr/local/mysql/lib/libmysqlclient_r.16.dylib

However, in this directory, there is a later version of the library:
/usr/local/mysql/lib/libmysqlclient.20.dylib

I am working in a virtualenvwrapper and have attempted to reinstall all of the previously install dependencies to no avail. Any assistance would be greatly appreciated.

Title: Psycopg2 image not found

Body:
Trying to setup postgres with the postgres mac app and hit this error, which I haven't been able to solve. Any thoughts?

    ImportError: dlopen(/Users/Craig/pyenv/mysite/lib/python2.7/site-packages/psycopg2/_psycopg.so, 2): Library not loaded: @executable_path/../lib/libssl.1.0.0.dylib
  Referenced from: /Applications/Postgres.app/Contents/MacOS/lib/libpq.dylib
  Reason: image not found


问:
Get users by name property using Firebase
I'm trying to create an application where I can get/set data in specific users accounts and I was tempted by Firebase.

The problem I'm having is that I don't know how to target specific users data when my structure looks like this:

```<code>online-b-cards
  - users
    - InnROTBVv6FznK81k3m
       - email: "hello@hello"
       - main:  "Hello world this is a text"
       - name:  "Alex"
       - phone: 12912912
</code>```

I've looked around and I can't really find anything on how to access individual data let alone when they're given some random hash as their ID.

How would I go about grabbing individual user information based of their name? If there is a better way of doing this please tell me!

答:
The simplest and better way to add unique Id to ur database according to authenticated user is this:

```<code>private FirebaseAuth auth;

String UId=auth.getCurrentUser().getUid();

FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Users");

User user = new User(name,email,phone,address,dob,bloodgroup);

myRef.child(UId).setValue(user);
</code>```

The UId will be a unique Id for a specific authenticated email/user

Body:
I'm trying to create an application where I can get/set data in specific users accounts and I was tempted by Firebase.

The problem I'm having is that I don't know how to target specific users data when my structure looks like this:

online-b-cards
  - users
    - InnROTBVv6FznK81k3m
       - email: "hello@hello"
       - main:  "Hello world this is a text"
       - name:  "Alex"
       - phone: 12912912

I've looked around and I can't really find anything on how to access individual data let alone when they're given some random hash as their ID.

How would I go about grabbing individual user information based of their name? If there is a better way of doing this please tell me!

Body:
The simplest and better way to add unique Id to ur database according to authenticated user is this:

private FirebaseAuth auth;

String UId=auth.getCurrentUser().getUid();

FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Users");

User user = new User(name,email,phone,address,dob,bloodgroup);

myRef.child(UId).setValue(user);

The UId will be a unique Id for a specific authenticated email/user


问:
Command line - Convert any string into an identifier?
Often I'd like to be able to take a string at the command line (bash), and convert it into an identifier. Usually this is for use in a filename, branch name, or variable name, and I prefer that it:

has no spaces in it

has no special characters in it

So for example, I could take a string like so:

bug fix for #PROJECT1 item 52, null pointer

and convert it to something like this:

bug_fix_for_PROJECT1_item_52__null_pointer

I'm open to solutions in any language, e.g. bash, node, perl, python, etc, but prefer languages that are installed by default on most linux/osx machines.

答:
You could so something like this :

```<code>original="bug fix for #PROJECT1 item 52, null pointer"
sanitized=${original//[^[:alnum:]]/_}
echo "$sanitized"
</code>```

Le me break that down a bit :

${VAR_NAME//SEARCH/REPLACE} searches and replaces all occurrences of SEARCH and performs the replacement.

[^[:alnum:]] means any character that is NOT alphabetic or numeric.  The "NOT" part is the ^

The outer brackets indicate that the expression refers to one character chosen among the different possibilities listed inside the bracket (see below for how to use this to your advantage).

This could be tailored to do something a bit more subtle if desired.  Remember UNIX-like systems accept almost any character in file names (even newlines), so you are not restricted to letters and digits.

For instance, suppose you want to keep periods and commas in file names.  You could change the replacement statement :

```<code>sanitized=${original//[^[:alnum:].,]/_}
</code>```

The modified part ([^[:alnum:].,]) means "anything that is not an alphanumeric character, and not a period, and not a comma".  You can add any other character you want to avoid replacing using regular expression syntax, but it is key that you keep the outer brackets.

Body:
You could so something like this :

original="bug fix for #PROJECT1 item 52, null pointer"
sanitized=${original//[^[:alnum:]]/_}
echo "$sanitized"

Le me break that down a bit :

${VAR_NAME//SEARCH/REPLACE} searches and replaces all occurrences of SEARCH and performs the replacement.

[^[:alnum:]] means any character that is NOT alphabetic or numeric.  The "NOT" part is the ^

The outer brackets indicate that the expression refers to one character chosen among the different possibilities listed inside the bracket (see below for how to use this to your advantage).

This could be tailored to do something a bit more subtle if desired.  Remember UNIX-like systems accept almost any character in file names (even newlines), so you are not restricted to letters and digits.

For instance, suppose you want to keep periods and commas in file names.  You could change the replacement statement :

sanitized=${original//[^[:alnum:].,]/_}

The modified part ([^[:alnum:].,]) means "anything that is not an alphanumeric character, and not a period, and not a comma".  You can add any other character you want to avoid replacing using regular expression syntax, but it is key that you keep the outer brackets.


问:
Is it possible to discard insertion in specific condidions in HSQLDB?
I need to restrict insertion of new rows by certain conditions. The database have to throw an exception if insertable values mismatch certain condition.
First I've tried to use CONSTRAINT object, but got the following error:
"SQLException: feature not supported: subquery in check constraint in statement".

Then I tried to use the trigger:

CREATE TRIGGER tg_val BEFORE INSERT ON valuta
 REFERENCING NEW ROW AS new
 FOR EACH ROW WHEN (new.simvol IS NULL)
 SIGNAL SQL_STATE '45000'

And got another error: SQLException: unexpected token: SIGNAL.

答:
The error probably indicates the version of HSQLDB used does not support the SIGNAL statement in this context. HSQLDB 2.0.1 (at the moment RC2) supports this, with SQLSTATE (not SQL_STATE as currently mentioned in the Guide) :

```<code>CREATE TRIGGER tg_val BEFORE INSERT ON valuta REFERENCING NEW ROW AS new FOR EACH ROW WHEN (new.simvol IS NULL) SIGNAL SQLSTATE '45000'
</code>```

It is clear from your attempt to use a check constraint with subquery that you want to use a more complex check condition than a NOT NULL constraint. In this case, use a BEGIN ... END block for the trigger in order to perform any SELECT statement from different tables (including the target table) to verify your condition.

Body:
The error probably indicates the version of HSQLDB used does not support the SIGNAL statement in this context. HSQLDB 2.0.1 (at the moment RC2) supports this, with SQLSTATE (not SQL_STATE as currently mentioned in the Guide) :

CREATE TRIGGER tg_val BEFORE INSERT ON valuta REFERENCING NEW ROW AS new FOR EACH ROW WHEN (new.simvol IS NULL) SIGNAL SQLSTATE '45000'

It is clear from your attempt to use a check constraint with subquery that you want to use a more complex check condition than a NOT NULL constraint. In this case, use a BEGIN ... END block for the trigger in order to perform any SELECT statement from different tables (including the target table) to verify your condition.


问:
How to confirm Data (Dates) from a database and show a image?
So i have a website and i want to connect my database to the html.

I want my website to works like this, when there is an event the website shows a image. but in order to do this, i need to  make a database which store the dates of the events, it should work with JavaScript, So the JavaScript takes current time and then goes to SQL Server and look for the Current dates, if the Date matches the Dates in the Database then the JavaScript will Show a image in the html, if it doesn't match then it will show anotherimage..

I Don't know how to do this, if someone kind provide me source code for this..
If Anyone Helpfull please help me.

答:
you need to have some knowledge about

SQL Query for storing data

Server side programming language "you need to choose one such as php, python, asp.net, and so on"

Ajax to communicate between server-side and client side "without reloading the page for example"

client-side web development HTML CSS and javascript.

there are a lot of tutorials to start with.

good luck


问:
Cannot read propery 'unsubscribe of undefined' on changing route
In my angular 2 app I have a parent component where I have made a subscription to a data source that passes this data down the line to multiple child components. In one of my child components I attempt to navigate to a different route in my app with parameters received from my subscription made in the top component. Whenever I do this in my app I get this error:

Error in ./CompanyPromoCardComponent class CompanyPromoCardComponent -
  inline template:6:10 caused by: Cannot read property 'unsubscribe' of
  undefined

This is my: CompanyPromoCardComponent

```<code>export class CompanyPromoCardComponent implements OnInit {

  @Input() company:Object;
  constructor(private router: Router) { }

  ngOnInit() {
  }

  gotoDetail(_id: String) {
    let link = ['/företag/' + _id + '/företagsinformation'];
    this.router.navigate(link);
  }

}
<div *ngIf="company">
  <div class="panel panel-default">
    <div class="panel-body">
      <div class="row">
        <div class="col-md-4">
          <app-company-industry [company]='company' [sub]='sub'></app-company-industry>
        </div>
        <div class="col-md-8">
          <app-company-targetgroup [company]='company'></app-company-targetgroup>
        </div>
      </div>
      <app-company-description [company]='company'></app-company-description>
      <app-company-tags [company]='company'></app-company-tags>
    </div>
    <div class="panel-footer">
      <div>
      <a class="btn btn-primary" (click)="gotoDetail(company._id)">Info</a>
      </div>
    </div>
  </div>
</div>
</code>```

And this is my parent component where I subscribe to my data:

```<code>    export class SearchResultsComponent implements OnInit {

      companies:Array<Object>;
      user:Object;
      sub:any;
      constructor(
        private companyService:CompanyService,
        private authService:AuthService,
        private flashMessage:FlashMessagesService
      ) { }

      ngOnInit() {
        this.sub = this.companyService.getCompaniesSearch().subscribe(data => {
          console.log('data.companies: ' + data.companies);
          this.companies = data.companies;
        },
        err => {
          console.log(err);
          return false;
        });
      }

      ngOnDestroy(){
        this.sub.unsubsribe();
      }

    }
</code>```

company.industry component - child component

```<code>import { Component, OnInit, Input, OnDestroy } from '@angular/core';

@Component({
  selector: 'app-company-industry',
  templateUrl: './company-industry.component.html',
  styleUrls: ['./company-industry.component.css']
})
export class CompanyIndustryComponent implements OnInit {

  error: any;
  @Input() sub: any;
  navigated = false;
  @Input() company:Object;
  constructor(
  ) { }

  ngOnInit() {
    console.log(this.sub);
  }

  ngOnDestroy(){
    this.sub.unsubscribe();
  }

}
</code>```

What causes this error to occur? I simple want to navigate to another route that depends on the id returned from my company object.

答:
Its always a good practise to check if the variable is undefined or not before performing action as below,

```<code>ngOnDestroy(){
    if(this.sub){
         this.sub.unsubscribe();
    }
  }
</code>```

How ever your problem is because @input variables are assigned through attributes. So, you can

```<code>this.companyService.getCompaniesSearch()
     .skipWhile(data => {
         return _.isEmpty(data);
      })
     .subscribe(data => {
          console.log('data.companies: ' + data.companies);
          this.companies = data.companies;
        },
        err => {
          console.log(err);
          return false;
        }).unsubscribe();
</code>```

Note:

Adding a skip while makes you not subscribe till your data is available.

After completion of subscribing to the data you can unsubscribe() as above.

Body:
In my angular 2 app I have a parent component where I have made a subscription to a data source that passes this data down the line to multiple child components. In one of my child components I attempt to navigate to a different route in my app with parameters received from my subscription made in the top component. Whenever I do this in my app I get this error:

Error in ./CompanyPromoCardComponent class CompanyPromoCardComponent -
  inline template:6:10 caused by: Cannot read property 'unsubscribe' of
  undefined

This is my: CompanyPromoCardComponent

export class CompanyPromoCardComponent implements OnInit {

  @Input() company:Object;
  constructor(private router: Router) { }

  ngOnInit() {
  }

  gotoDetail(_id: String) {
    let link = ['/företag/' + _id + '/företagsinformation'];
    this.router.navigate(link);
  }

}

          <app-company-industry [company]='company' [sub]='sub'></app-company-industry>

          <app-company-targetgroup [company]='company'></app-company-targetgroup>

      <app-company-description [company]='company'></app-company-description>
      <app-company-tags [company]='company'></app-company-tags>

      Info

And this is my parent component where I subscribe to my data:

    export class SearchResultsComponent implements OnInit {

      companies:Array<Object>;
      user:Object;
      sub:any;
      constructor(
        private companyService:CompanyService,
        private authService:AuthService,
        private flashMessage:FlashMessagesService
      ) { }

      ngOnInit() {
        this.sub = this.companyService.getCompaniesSearch().subscribe(data => {
          console.log('data.companies: ' + data.companies);
          this.companies = data.companies;
        },
        err => {
          console.log(err);
          return false;
        });
      }

      ngOnDestroy(){
        this.sub.unsubsribe();
      }

    }

company.industry component - child component

import { Component, OnInit, Input, OnDestroy } from '@angular/core';

@Component({
  selector: 'app-company-industry',
  templateUrl: './company-industry.component.html',
  styleUrls: ['./company-industry.component.css']
})
export class CompanyIndustryComponent implements OnInit {

  error: any;
  @Input() sub: any;
  navigated = false;
  @Input() company:Object;
  constructor(
  ) { }

  ngOnInit() {
    console.log(this.sub);
  }

  ngOnDestroy(){
    this.sub.unsubscribe();
  }

}

What causes this error to occur? I simple want to navigate to another route that depends on the id returned from my company object.

Body:
Its always a good practise to check if the variable is undefined or not before performing action as below,

ngOnDestroy(){
    if(this.sub){
         this.sub.unsubscribe();
    }
  }

How ever your problem is because @input variables are assigned through attributes. So, you can

this.companyService.getCompaniesSearch()
     .skipWhile(data => {
         return _.isEmpty(data);
      })
     .subscribe(data => {
          console.log('data.companies: ' + data.companies);
          this.companies = data.companies;
        },
        err => {
          console.log(err);
          return false;
        }).unsubscribe();

Note:

Adding a skip while makes you not subscribe till your data is available.

After completion of subscribing to the data you can unsubscribe() as above.