问:
Rails: Logged in user can create a new user
For my website, I'm trying to find a way where if a user is logged in, then they can create a user for someone. For the website, I don't want just ANYONE signing up. Only a user can sign someone up for security reasons. I cannot figure out how to do that. I'm using devise for log in/sign up.

I'll post some of my code, but I'm not sure which ones I should post, still new to rails.

In here, I want the link to create a user/sign up. The sign up page should only be viewable if a user is logged in.

```<code><!DOCTYPE html>
<html>
...
  <body>
    <div class = "auth">
      <% if !user_signed_in? %>
        <button class = "signed_in"><%= link_to "Login", new_user_session_path %></button>
    <% end %>

    <% if user_signed_in? %>
        <div class = "buttons">
          <button class = "button"><%= link_to("Logout", destroy_user_session_path, :method => :delete) %> </button>

        </div>
    <% end %>
    </div>
    <p class="notice"><%= notice %></p>
    <p class="alert"><%= alert %></p>

    <%= yield %>
  </body>
 </html>
</code>```

I'll also post this. I think this is how the links work on the authentication.

```<code><%- if controller_name != 'sessions' %>
  <%= link_to "Log in", new_session_path(resource_name) %><br />
<% end -%>

<%- if devise_mapping.registerable? && controller_name != 'registrations' %>
  <%= link_to "Sign up", new_registration_path(resource_name) %><br />
<% end -%>

<%- if devise_mapping.recoverable? && controller_name != 'passwords' && controller_name != 'registrations' %>
  <%= link_to "Forgot your password?", new_password_path(resource_name) %><br />
<% end -%>

<%- if devise_mapping.confirmable? && controller_name != 'confirmations' %>
  <%= link_to "Didn't receive confirmation instructions?", new_confirmation_path(resource_name) %><br />
<% end -%>

<%- if devise_mapping.lockable? && resource_class.unlock_strategy_enabled?(:email) && controller_name != 'unlocks' %>
  <%= link_to "Didn't receive unlock instructions?", new_unlock_path(resource_name) %><br />
<% end -%>

<%- if devise_mapping.omniauthable? %>
  <%- resource_class.omniauth_providers.each do |provider| %>
    <%= link_to "Sign in with #{OmniAuth::Utils.camelize(provider)}", omniauth_authorize_path(resource_name, provider) %><br />
  <% end -%>
<% end -%>
</code>```

Here is where I guess how you sign up. I want this page only viewable if a user is logged in. The problem I see that I THNIK that a user can only get to the sign up page if he or she is logged out. I want the sign up page ONLY viewable if a user is logged in. Not sure how that will work.

```<code><article class = "sign" >

<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
  <%= devise_error_messages! %>

  <div class="field">
    <%= f.label :email %><br />
    <%= f.email_field :email, autofocus: true %>
  </div>

  <div class="field">
    <%= f.label :password %>
    <% if @minimum_password_length %>
    <em>(<%= @minimum_password_length %> characters minimum)</em>
    <% end %><br />
     <%= f.password_field :password, autocomplete: "off" %>
  </div>

  <div class="field">
     <%= f.label :password_confirmation %><br />
    <%= f.password_field :password_confirmation, autocomplete: "off" %>
  </div>

   <div class="actions">
    <%= f.submit "Sign up" %>
  </div>
<% end %>

<%= render "devise/shared/links" %>
</article>
</code>```

I also posted the migration code, looks important

```<code>class DeviseCreateUsers < ActiveRecord::Migration[5.1]
  def change
    create_table :users do |t|
      ## Database authenticatable
      t.string :email,              null: false, default: ""
      t.string :encrypted_password, null: false, default: ""

      ## Recoverable
      t.string   :reset_password_token
      t.datetime :reset_password_sent_at

      ## Rememberable
      t.datetime :remember_created_at

      ## Trackable
      t.integer  :sign_in_count, default: 0, null: false
      t.datetime :current_sign_in_at
      t.datetime :last_sign_in_at
      t.string   :current_sign_in_ip
      t.string   :last_sign_in_ip

      ## Confirmable
      # t.string   :confirmation_token
      # t.datetime :confirmed_at
      # t.datetime :confirmation_sent_at
      # t.string   :unconfirmed_email # Only if using reconfirmable

      ## Lockable
      # t.integer  :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
      # t.string   :unlock_token # Only if unlock strategy is :email or :both
      # t.datetime :locked_at

      t.timestamps null: false
    end

    add_index :users, :email,                unique: true
    add_index :users, :reset_password_token, unique: true
    # add_index :users, :confirmation_token,   unique: true
    # add_index :users, :unlock_token,         unique: true
  end
end
</code>```

Like I said, I am not exactly sure what code I should post for guidance. Let me know if I should post more to figure how to do this.

Also to note, I currently have no code in my user controller, maybe I will have to add stuff to make this work?

答:
The same way you do it to check if the user is signed in and print the buttons, you can add a new link_to helper which points to a new route created to make this work:

```<code># html.erb file (mostly application.html.erb)
<div class="auth">
  <% if !user_signed_in? %>
    <button class="signed_in">
      <%= link_to 'Login' new_user_session_path %>
    </button>
  <% else %>
    <div class="buttons">
      <button class="button">
        <%= link_to('Logout', destroy_user_session_path, method: :delete) %>
      </button>
      <button class="button">
        <%= link_to 'Create a new account', new_account_path %><br />
      </button>
    </div>
  <% end %>
</div>
</code>```

You need to create a new controller which inherits from the Devise RegistrationsController, which will override the Devise new method, and will use the skip_before_action (Rails 5, for Rails 4 use skip_before_filter) callback in order to make it work with the overrided method:

```<code># app/controllers/registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
  skip_before_action :require_no_authentication, only: [:new]

  def new
    super
  end
end
</code>```

Then in your routes you add the registrations_controller to make it work with Devise:

```<code># config/routes.rb
devise_for :users, controllers: { registrations: 'registrations' }
</code>```

And as a logged user define a GET route which match with the used in the link_to helper created in the first step:

```<code># config/routes.rb
as :user do
  get '/new_account', to: 'registrations#new'
end
</code>```

Here there's a repo to see how it works. Hope it helps.

Body:
For my website, I'm trying to find a way where if a user is logged in, then they can create a user for someone. For the website, I don't want just ANYONE signing up. Only a user can sign someone up for security reasons. I cannot figure out how to do that. I'm using devise for log in/sign up.

I'll post some of my code, but I'm not sure which ones I should post, still new to rails.

In here, I want the link to create a user/sign up. The sign up page should only be viewable if a user is logged in.

<!DOCTYPE html>

...

      <% if !user_signed_in? %>
        <button class = "signed_in"><%= link_to "Login", new_user_session_path %></button>
    <% end %>

    <% if user_signed_in? %>

          <button class = "button"><%= link_to("Logout", destroy_user_session_path, :method => :delete) %> </button>

    <% end %>

<%= notice %>

<%= alert %>

    <%= yield %>

I'll also post this. I think this is how the links work on the authentication.

<%- if controller_name != 'sessions' %>
  <%= link_to "Log in", new_session_path(resource_name) %>

<% end -%>

<%- if devise_mapping.registerable? && controller_name != 'registrations' %>
  <%= link_to "Sign up", new_registration_path(resource_name) %>

<% end -%>

<%- if devise_mapping.recoverable? && controller_name != 'passwords' && controller_name != 'registrations' %>
  <%= link_to "Forgot your password?", new_password_path(resource_name) %>

<% end -%>

<%- if devise_mapping.confirmable? && controller_name != 'confirmations' %>
  <%= link_to "Didn't receive confirmation instructions?", new_confirmation_path(resource_name) %>

<% end -%>

<%- if devise_mapping.lockable? && resource_class.unlock_strategy_enabled?(:email) && controller_name != 'unlocks' %>
  <%= link_to "Didn't receive unlock instructions?", new_unlock_path(resource_name) %>

<% end -%>

<%- if devise_mapping.omniauthable? %>
  <%- resource_class.omniauth_providers.each do |provider| %>
    <%= link_to "Sign in with #{OmniAuth::Utils.camelize(provider)}", omniauth_authorize_path(resource_name, provider) %>

  <% end -%>
<% end -%>

Here is where I guess how you sign up. I want this page only viewable if a user is logged in. The problem I see that I THNIK that a user can only get to the sign up page if he or she is logged out. I want the sign up page ONLY viewable if a user is logged in. Not sure how that will work.

<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
  <%= devise_error_messages! %>

    <%= f.label :email %>

    <%= f.email_field :email, autofocus: true %>

    <%= f.label :password %>
    <% if @minimum_password_length %>
    (<%= @minimum_password_length %> characters minimum)
    <% end %>

     <%= f.password_field :password, autocomplete: "off" %>

     <%= f.label :password_confirmation %>

    <%= f.password_field :password_confirmation, autocomplete: "off" %>

    <%= f.submit "Sign up" %>

<% end %>

<%= render "devise/shared/links" %>

I also posted the migration code, looks important

class DeviseCreateUsers < ActiveRecord::Migration[5.1]
  def change
    create_table :users do |t|
      ## Database authenticatable
      t.string :email,              null: false, default: ""
      t.string :encrypted_password, null: false, default: ""

      ## Recoverable
      t.string   :reset_password_token
      t.datetime :reset_password_sent_at

      ## Rememberable
      t.datetime :remember_created_at

      ## Trackable
      t.integer  :sign_in_count, default: 0, null: false
      t.datetime :current_sign_in_at
      t.datetime :last_sign_in_at
      t.string   :current_sign_in_ip
      t.string   :last_sign_in_ip

      ## Confirmable
      # t.string   :confirmation_token
      # t.datetime :confirmed_at
      # t.datetime :confirmation_sent_at
      # t.string   :unconfirmed_email # Only if using reconfirmable

      ## Lockable
      # t.integer  :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
      # t.string   :unlock_token # Only if unlock strategy is :email or :both
      # t.datetime :locked_at

      t.timestamps null: false
    end

    add_index :users, :email,                unique: true
    add_index :users, :reset_password_token, unique: true
    # add_index :users, :confirmation_token,   unique: true
    # add_index :users, :unlock_token,         unique: true
  end
end

Like I said, I am not exactly sure what code I should post for guidance. Let me know if I should post more to figure how to do this.

Also to note, I currently have no code in my user controller, maybe I will have to add stuff to make this work?

Body:
The same way you do it to check if the user is signed in and print the buttons, you can add a new link_to helper which points to a new route created to make this work:

# html.erb file (mostly application.html.erb)
<div class="auth">
  <% if !user_signed_in? %>
    <button class="signed_in">
      <%= link_to 'Login' new_user_session_path %>
    </button>
  <% else %>
    <div class="buttons">
      <button class="button">
        <%= link_to('Logout', destroy_user_session_path, method: :delete) %>
      </button>
      <button class="button">
        <%= link_to 'Create a new account', new_account_path %><br />
      </button>
    </div>
  <% end %>
</div>

You need to create a new controller which inherits from the Devise RegistrationsController, which will override the Devise new method, and will use the skip_before_action (Rails 5, for Rails 4 use skip_before_filter) callback in order to make it work with the overrided method:

# app/controllers/registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
  skip_before_action :require_no_authentication, only: [:new]

  def new
    super
  end
end

Then in your routes you add the registrations_controller to make it work with Devise:

# config/routes.rb
devise_for :users, controllers: { registrations: 'registrations' }

And as a logged user define a GET route which match with the used in the link_to helper created in the first step:

# config/routes.rb
as :user do
  get '/new_account', to: 'registrations#new'
end

Here there's a repo to see how it works. Hope it helps.


来源: stackexchange

问:
How to exclude folders from search except a few?
I work on a large project with many files. I want to exclude as many files as possible.

I want to exclude **/node_modules, but except a few that are created by my company. e.g. **/node_modules/@mycomp.

Is it possible today in vscode 1.8.1?

Thanks,

Unional

答:
Here is what I did to only show the node_modules/swagger-tools folder.

In the .vscode/settings.json file I wrote the following rules:

Filter all folders starting with the dot character or every letter except s.

Filter all folders starting with s and is followed by every letter except w.

Filter every folder starting with swagger- (at this point all the remaining folders started with swagger-) and is followed by every letter except t.

So the file ended up like this:

```<code>{
    "files.exclude": {
      "node_modules/[abcdefghijklmnopqrtuvwxyz.]*": true,
      "node_modules/s[abcdefghijklmnopqrstuvxyz]*": true,
      "node_modules/swagger-[abcdefghijklmnopqrsuvwxyz]*": true,
    }
}
</code>```

Arguably is not the nicest thing to do but certainly does the trick.

ContentLicense: CC BY-SA 3.0

Body:
Here is what I did to only show the node_modules/swagger-tools folder.

In the .vscode/settings.json file I wrote the following rules:

Filter all folders starting with the dot character or every letter except s.

Filter all folders starting with s and is followed by every letter except w.

Filter every folder starting with swagger- (at this point all the remaining folders started with swagger-) and is followed by every letter except t.

So the file ended up like this:

{
    "files.exclude": {
      "node_modules/[abcdefghijklmnopqrtuvwxyz.]*": true,
      "node_modules/s[abcdefghijklmnopqrstuvxyz]*": true,
      "node_modules/swagger-[abcdefghijklmnopqrsuvwxyz]*": true,
    }
}

Arguably is not the nicest thing to do but certainly does the trick.


问:
Adding a GPU Op in Tensorflow
I am trying to add a new op to TensorFlow loosely following this document. The difference being that I am trying to implement a GPU based op. The op I'm trying to add is the cuda op from here (cuda_op.py, cuda_op_kernel.cc, cuda_op_kernel.cu.cc). I am trying to compile these outside of tensorflow and the use tf.load_op_library to pull them in. I have made some changes so here are my files:

cuda_op_kernel.cc

```<code>#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/shape_inference.h"
#include "tensorflow/core/framework/op_kernel.h"

using namespace tensorflow;  // NOLINT(build/namespaces)

REGISTER_OP("AddOne")
    .Input("input: int32")
    .Output("output: int32")
    .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) {
      c->set_output(0, c->input(0));
      return Status::OK();
    });

void AddOneKernelLauncher(const int* in, const int N, int* out);

class AddOneOp : public OpKernel {
 public:
  explicit AddOneOp(OpKernelConstruction* context) : OpKernel(context) {}

  void Compute(OpKernelContext* context) override {
    // Grab the input tensor
    const Tensor& input_tensor = context->input(0);
    auto input = input_tensor.flat<int32>();

    // Create an output tensor
    Tensor* output_tensor = NULL;
    OP_REQUIRES_OK(context, context->allocate_output(0, input_tensor.shape(),
                                                     &output_tensor));
    auto output = output_tensor->template flat<int32>();

    // Set all but the first element of the output tensor to 0.
    const int N = input.size();
    // Call the cuda kernel launcher
    AddOneKernelLauncher(input.data(), N, output.data());

  }
};

REGISTER_KERNEL_BUILDER(Name("AddOne").Device(DEVICE_GPU), AddOneOp);
</code>```

cuda_op_kernel.cu

```<code>#define EIGEN_USE_GPU
#include <cuda.h>
#include <stdio.h>

__global__ void AddOneKernel(const int* in, const int N, int* out) {
  for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < N;
       i += blockDim.x * gridDim.x) {
    out[i] = in[i] + 1;
  }
}

void AddOneKernelLauncher(const int* in, const int N, int* out) {
  AddOneKernel<<<32, 256>>>(in, N, out);

  cudaError_t cudaerr = cudaDeviceSynchronize();
  if (cudaerr != cudaSuccess)
    printf("kernel launch failed with error \"%s\".\n", cudaGetErrorString(cudaerr));
}
</code>```

CMakeLists.txt

```<code>cmake_minimum_required(VERSION 3.5)

#found from running python -c 'import tensorflow as tf; print(tf.sysconfig.get_include())'
include_directories(/usr/local/lib/python3.5/dist-packages/tensorflow/include)

find_package(CUDA)

#set flags based on tutorial
set (CMAKE_CXX_FLAGS "--std=c++11 -fPIC -O2 -D_GLIBCXX_USE_CXX11_ABI=0")

#pass flags to c++ compiler
SET(CUDA_PROPAGATE_HOST_FLAGS ON)

#create library
cuda_add_library(
    cuda_op SHARED
    src/cuda_op_kernel.cu
    src/cuda_op_kernel.cc
    OPTIONS -gencode=arch=compute_20,code=sm_20)

#copy test file to build folder
configure_file(src/test.py test.py COPYONLY)
</code>```

test.py

```<code>import tensorflow as tf
mod = tf.load_op_library('./libcuda_op.so')
with tf.Session() as sess:
    start = [5,4,3,2,1]
    print(start)
    print(mod.add_one(start).eval())
</code>```

I am able to compile and run test.py successfully, but the output is always [0 0 0 0 0]. If I replace AddOneKernel<<<32, 256>>>(in, N, out); with for (int i = 0; i < N; i++) out[i] = in[i] + 1; and DEVICE_GPU with DEVICE_CPU, the op outputs the right values [6 5 4 3 2] (with exact same CMakeList.txt).

Any idea how to get the correct values to be returned?

答:
I don't fully remember where I found the cmake stuff for CUDA, but the options were messing the compilation up somehow. Replacing cuda_add_library in the CMakeLists.txt to be the following fixed the problem.

```<code>#no options needed
cuda_add_library(
    cuda_op SHARED
    src/cuda_op_kernel.cu
    src/cuda_op_kernel.cc)
</code>```

Title: Adding a GPU Op in Tensorflow

Body:
I am trying to add a new op to TensorFlow loosely following this document. The difference being that I am trying to implement a GPU based op. The op I'm trying to add is the cuda op from here (cuda_op.py, cuda_op_kernel.cc, cuda_op_kernel.cu.cc). I am trying to compile these outside of tensorflow and the use tf.load_op_library to pull them in. I have made some changes so here are my files:

cuda_op_kernel.cc

#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/shape_inference.h"
#include "tensorflow/core/framework/op_kernel.h"

using namespace tensorflow;  // NOLINT(build/namespaces)

REGISTER_OP("AddOne")
    .Input("input: int32")
    .Output("output: int32")
    .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) {
      c->set_output(0, c->input(0));
      return Status::OK();
    });

void AddOneKernelLauncher(const int* in, const int N, int* out);

class AddOneOp : public OpKernel {
 public:
  explicit AddOneOp(OpKernelConstruction* context) : OpKernel(context) {}

  void Compute(OpKernelContext* context) override {
    // Grab the input tensor
    const Tensor& input_tensor = context->input(0);
    auto input = input_tensor.flat<int32>();

    // Create an output tensor
    Tensor* output_tensor = NULL;
    OP_REQUIRES_OK(context, context->allocate_output(0, input_tensor.shape(),
                                                     &output_tensor));
    auto output = output_tensor->template flat<int32>();

    // Set all but the first element of the output tensor to 0.
    const int N = input.size();
    // Call the cuda kernel launcher
    AddOneKernelLauncher(input.data(), N, output.data());

  }
};

REGISTER_KERNEL_BUILDER(Name("AddOne").Device(DEVICE_GPU), AddOneOp);

cuda_op_kernel.cu

#define EIGEN_USE_GPU
#include <cuda.h>
#include <stdio.h>

__global__ void AddOneKernel(const int* in, const int N, int* out) {
  for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < N;
       i += blockDim.x * gridDim.x) {
    out[i] = in[i] + 1;
  }
}

void AddOneKernelLauncher(const int* in, const int N, int* out) {
  AddOneKernel<<<32, 256>>>(in, N, out);

  cudaError_t cudaerr = cudaDeviceSynchronize();
  if (cudaerr != cudaSuccess)
    printf("kernel launch failed with error \"%s\".\n", cudaGetErrorString(cudaerr));
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.5)

#found from running python -c 'import tensorflow as tf; print(tf.sysconfig.get_include())'
include_directories(/usr/local/lib/python3.5/dist-packages/tensorflow/include)

find_package(CUDA)

#set flags based on tutorial
set (CMAKE_CXX_FLAGS "--std=c++11 -fPIC -O2 -D_GLIBCXX_USE_CXX11_ABI=0")

#pass flags to c++ compiler
SET(CUDA_PROPAGATE_HOST_FLAGS ON)

#create library
cuda_add_library(
    cuda_op SHARED
    src/cuda_op_kernel.cu
    src/cuda_op_kernel.cc
    OPTIONS -gencode=arch=compute_20,code=sm_20)

#copy test file to build folder
configure_file(src/test.py test.py COPYONLY)

test.py

import tensorflow as tf
mod = tf.load_op_library('./libcuda_op.so')
with tf.Session() as sess:
    start = [5,4,3,2,1]
    print(start)
    print(mod.add_one(start).eval())

I am able to compile and run test.py successfully, but the output is always [0 0 0 0 0]. If I replace AddOneKernel<<<32, 256>>>(in, N, out); with for (int i = 0; i < N; i++) out[i] = in[i] + 1; and DEVICE_GPU with DEVICE_CPU, the op outputs the right values [6 5 4 3 2] (with exact same CMakeList.txt).

Any idea how to get the correct values to be returned?

Body:
I don't fully remember where I found the cmake stuff for CUDA, but the options were messing the compilation up somehow. Replacing cuda_add_library in the CMakeLists.txt to be the following fixed the problem.

#no options needed
cuda_add_library(
    cuda_op SHARED
    src/cuda_op_kernel.cu
    src/cuda_op_kernel.cc)


问:
Element style not allowed as child of element div in this context
I have been going through W3C errors and have cleared all but this one.

Element style not allowed as child of element div in this context.

Here is the code it refers to:

```<code><style><!--ul.lists { width: 29%; float: left;}--></style>
</code>```

Any help ridding me of this last error would be appreciated.

Body:
I have been going through W3C errors and have cleared all but this one.

Element style not allowed as child of element div in this context.

Here is the code it refers to:

Any help ridding me of this last error would be appreciated.

Body: In style tags and CSS files, you use /* ... */  for commenting things out, not the HTML way of commenting like <!-- ... -->


问:
Does opencl support boolean variables?
Does openCL support boolean variables? I am currently using JOCL (java) to write my openCL calling code and I don't see anything about booleans.</p>

答:
tl;dr: Yes, but you should avoid it in kernel function signatures.

Yes; but the size of a bool is not defined. Therefore, it does not have an associated API type (as what size the value should be is device dependent).

See section 6.1.1 Built-in Scalar Data Type of the OpenCL 1.1 specification for a list of supported scalar types.

From Section 6.8.k

Arguments to __kernel functions in a program cannot be declared with the built-in
scalar types bool, half, size_t, ptrdiff_t, intptr_t, and uintptr_t.  The
size in bytes of these types except half are implementation-defined and in addition can
also be different for the OpenCL device and the host processor  making it difficult to
allocate buffer objects to be  passed as arguments to a kernel declared as pointer to these
type

ContentLicense: CC BY-SA 2.5

Title: Does opencl support boolean variables?

ContentLicense: CC BY-SA 4.0


问:
JQuery how to difference between a select option with an option selected attribute and a select without a selected value
I'm populating multiple select with a webservice.
This web service is returning the selected value.

Well, at the moment to render them, I have 2 different select

```<code><select id='select1'>
<option value='1'>Option 1</option>
<option value='3'>Option 3</option>
</select>

<select id='select2'>
<option selected="selected" value='A'>Option A</option>
<option value='B'>Option B</option>
</select>
</code>```

Well, the first select hasn't any selected attribute and the second one has it.

When I execute:

```<code>$("select1").find("option:selected").val(); //Returns 1
$("select2").find("option:selected").val(); //Returns A
</code>```

How I can identify when the select has an option really selected?

答:
You can use the has() jQuery method to find the select that has an option with the selected attribute.

```<code>$("select").has("option[selected]")

$("#select1").has("option[selected]").val() // undefined
$("#select2").has("option[selected]").val() // "A"
</code>```

Body:
I'm populating multiple select with a webservice.
This web service is returning the selected value.

Well, at the moment to render them, I have 2 different select

<select id='select1'>
<option value='1'>Option 1</option>
<option value='3'>Option 3</option>
</select>

<select id='select2'>
<option selected="selected" value='A'>Option A</option>
<option value='B'>Option B</option>
</select>

Well, the first select hasn't any selected attribute and the second one has it.

When I execute:

$("select1").find("option:selected").val(); //Returns 1
$("select2").find("option:selected").val(); //Returns A

How I can identify when the select has an option really selected?

Body:
You can use the has() jQuery method to find the select that has an option with the selected attribute.

$("select").has("option[selected]")

$("#select1").has("option[selected]").val() // undefined
$("#select2").has("option[selected]").val() // "A"


问:
best way to compare different objects in powershell
Not sure if this is even possible, but I'm trying to compare properties of an ADgroup object and a PSCustomObject object. We're in the middle of a user audit which requires validating a list of active employees against our active AD user accounts along with their AD group memberships. Here's a basic breakdown of what I have so far:

(we're defining two separate search paths because we have groups in different OUs)

$mainGroups = get-adgroup -filter * -searchbase 'OU_here'

$subGroups = get-adgroup filter * -searchbase 'Different_OU_here'

List of usernames from HR system

$sourceUsers = get-content -path 'c:\temp\users.txt'

List of usernames from AD

$ADUserName = get-aduser -filter * -searchbase 'User_OU' -searchscope subtree | select -expandproperty SamAccountName

Empty array to store custom object/properties

$userObjEQ = @()

Compare HR to AD

$compareResults = compare-object -referenceobject $sourceUsers -differenceObject $ADUserName

Find group memberships of all matching users, create custom object, etc

```<code>foreach ($result in $compareResults) {
    if ($result.SideIndicator -eq '==') {
        $groupMem = get-adprincipalgroupmembership -identity $result.InputObject
    }
    $userObjEQ += [pscustomobject] @{
    'UserName' = $result.InputObject
    'Groups' = $groupMem.Name
    }
}
</code>```

From this point on, I want to compare every group from each matching user to the group name from the $mainGroups to see if there's a match. If there isn't then compare it to the $subGroups group names. If there's a match do nothing, if there's a mismatch, output the username along with any mismatched group names. Just not sure how best to compare these objects. Any hints will be appreciated.

答:
If your groups are arrays, then use the -contains operator -- if they're not, make them arrays: </p>

```<code>foreach ($u in $users) {
   foreach ($groupdn in $u.memberof) {
      if ($mainGroups -contains $ug -or $subGroups -contains $ug) {
         ## do something when the users' group exists in the checked sub-groups
      }
   }
}
</code>```

<p>...this assumes the $maingroups array is an array of group DNs...</p>

Body:
Not sure if this is even possible, but I'm trying to compare properties of an ADgroup object and a PSCustomObject object. We're in the middle of a user audit which requires validating a list of active employees against our active AD user accounts along with their AD group memberships. Here's a basic breakdown of what I have so far:

(we're defining two separate search paths because we have groups in different OUs)

$mainGroups = get-adgroup -filter * -searchbase 'OU_here'

$subGroups = get-adgroup filter * -searchbase 'Different_OU_here'

List of usernames from HR system

$sourceUsers = get-content -path 'c:\temp\users.txt'

List of usernames from AD

$ADUserName = get-aduser -filter * -searchbase 'User_OU' -searchscope subtree | select -expandproperty SamAccountName

Empty array to store custom object/properties

$userObjEQ = @()

Compare HR to AD

$compareResults = compare-object -referenceobject $sourceUsers -differenceObject $ADUserName

Find group memberships of all matching users, create custom object, etc

foreach ($result in $compareResults) {
    if ($result.SideIndicator -eq '==') {
        $groupMem = get-adprincipalgroupmembership -identity $result.InputObject
    }
    $userObjEQ += [pscustomobject] @{
    'UserName' = $result.InputObject
    'Groups' = $groupMem.Name
    }
}

From this point on, I want to compare every group from each matching user to the group name from the $mainGroups to see if there's a match. If there isn't then compare it to the $subGroups group names. If there's a match do nothing, if there's a mismatch, output the username along with any mismatched group names. Just not sure how best to compare these objects. Any hints will be appreciated.

Body:
If your groups are arrays, then use the -contains operator -- if they're not, make them arrays:

foreach ($u in $users) {
   foreach ($groupdn in $u.memberof) {
      if ($mainGroups -contains $ug -or $subGroups -contains $ug) {
         ## do something when the users' group exists in the checked sub-groups
      }
   }
}

...this assumes the $maingroups array is an array of group DNs...


问:
How to use a custom function within the rollapply
I have a custom function which runs a regression and returns the result in a desired way. the function is named "reg.fun". For example, I can run such a code:

```<code>results <- dt[ ,reg.fun(.SD, depvar="Y", indepvars=c("X1", "X2")),
              .SDcols=c("Y", "X1", "X2"), by = id]
</code>```

The code above produces an output like this: It is just reporting the regression results in my desired manner.) I am using it in data table to use the "by" group feature.

```<code>id  X1coef   X2coef  X1tstat  X2tstat ...other results...
A   0.0418   0.1194   2.65     3.56    ....
B   0.7903   -0.554   2.75     4.59    .....
</code>```

This works perfectly and gives me the results in the desired table. Now, I want to use the rollapply function to do the same excersice in a rolling window manner. What I write is this:

```<code>regress <- dt[ ,rollapply(.SD, width = 3,
               reg.fun(.SD, depvar="Y" indepvars=c("X1","X2")) ),
              .SDcols = c("Y", "X1", "X2"), by = id]
</code>```

here is the error that I get now:

Error in match.fun(FUN) :
    'reg.fun(.SD, depvar = "Y", indepvars = c("X1", "X2"))' is not a function, character or symbol

Ideally, I want to produce the same above table, but now with multiple rows for id A and id B, since I want to run regression on rolling windows. somthing like this:

```<code>window    id  X1coef   X2coef  X1tstat  X2tstat ...other results...
  1-3      A   xxx      xxx       xxx     xxx    ....
  2-5      A   xxx      xxx       xxx     xxx
  3-6      A   xxx      xxx       xxx     xxx
   ...
  1-3      B    xxx      xxx       xxx     xxx    .....
  2-5      B    xxx      xxx       xxx     xxx
  3-6      B    xxx      xxx       xxx     xxx
</code>```

I cannot find out why in this context reg.fun is not considered as a function for the rollapply.

I know that I might be wrong on so many levels since this is my first project in R. Can some one please let me know what is the problem, or if this is not the way, what is the correct direction to go?

答:
```<code>regress <- dt[ ,rollapply(.SD, width = 3, reg.fun, depvar="Y",
                indepvars=c("X1","X2")), .SDcols = c("Y", "X1", "X2"), by = id]
</code>```

Body:
I have a custom function which runs a regression and returns the result in a desired way. the function is named "reg.fun". For example, I can run such a code:

results <- dt[ ,reg.fun(.SD, depvar="Y", indepvars=c("X1", "X2")),
              .SDcols=c("Y", "X1", "X2"), by = id]

The code above produces an output like this: It is just reporting the regression results in my desired manner.) I am using it in data table to use the "by" group feature.

id  X1coef   X2coef  X1tstat  X2tstat ...other results...
A   0.0418   0.1194   2.65     3.56    ....
B   0.7903   -0.554   2.75     4.59    .....

This works perfectly and gives me the results in the desired table. Now, I want to use the rollapply function to do the same excersice in a rolling window manner. What I write is this:

regress <- dt[ ,rollapply(.SD, width = 3,
               reg.fun(.SD, depvar="Y" indepvars=c("X1","X2")) ),
              .SDcols = c("Y", "X1", "X2"), by = id]

here is the error that I get now:

Error in match.fun(FUN) :
    'reg.fun(.SD, depvar = "Y", indepvars = c("X1", "X2"))' is not a function, character or symbol

Ideally, I want to produce the same above table, but now with multiple rows for id A and id B, since I want to run regression on rolling windows. somthing like this:

window    id  X1coef   X2coef  X1tstat  X2tstat ...other results...
  1-3      A   xxx      xxx       xxx     xxx    ....
  2-5      A   xxx      xxx       xxx     xxx
  3-6      A   xxx      xxx       xxx     xxx
   ...
  1-3      B    xxx      xxx       xxx     xxx    .....
  2-5      B    xxx      xxx       xxx     xxx
  3-6      B    xxx      xxx       xxx     xxx

I cannot find out why in this context reg.fun is not considered as a function for the rollapply.

I know that I might be wrong on so many levels since this is my first project in R. Can some one please let me know what is the problem, or if this is not the way, what is the correct direction to go?


问:
Prevent component from being created when inserted as content within another component (angular 2)
When inserting a component as ng-content of another component, how can I prevent it from being initialized until an expression is true?

```<code><ng-content *ngIf="expression"></ng-content>
</code>```

I basically only want the component's ngOnInit method to run once it's actually visible.

答:
you need to wrap ng-content in'div' element to use *ngIf.</p>

```<code><div *ngIf="expression">
<ng-content ></ng-content>
</div>
</code>```

Body:
When inserting a component as ng-content of another component, how can I prevent it from being initialized until an expression is true?

<ng-content *ngIf="expression"></ng-content>

I basically only want the component's ngOnInit method to run once it's actually visible.

Body:
you need to wrap ng-content in'div' element to use *ngIf.

<div *ngIf="expression">
<ng-content ></ng-content>
</div>


问:
Why does Double.TryParse() return false for a string containing double.MaxValue or double.MinValue?
I have static method that takes a string for input and returns the original input string if the string represents a number.  If the string does not represent a number the the input string is processed and a transformed string is returned.  I'm writing test cases.  I'm trying to verify that an input string containing either double.MinValue or double.MaxValue is returned unchanged.  I've read through a number of forums, including StackOverflow, and have come up with the following logic:

```<code>string doubleMax = double.MaxValue.ToString();
double d;
CultureInfo cultureInfo = new CultureInfo("en-US", true);
if (Double.TryParse(doubleMax, NumberStyles.Any, cultureInfo.NumberFormat, out d))
{
    Console.WriteLine("parsed");
}
else
{
    Console.WriteLine("couldn't parse");
}
</code>```

Problem is the Double.TryParse() always returns false.  I've called TryParse() in a bunch of different ways, but the result is always the same, false.

This logic works if I use decimal.MinValue(), int.MinValue(), or float.MinValue().

Can someone tell me why my logic isn't working for double.MinValue?

答:
That's because of the way that floating point numbers are stored and displayed. The value is rounded when it's turned into a human readable string, and for double.MaxValue it happens to be rounded up so that it no longer fits in a double.

You can use the round-trip format "R" to turn a value into a string that always can be parsed back to the same value, as it adds extra precision until the correct value is returned. Also, use the same culture when formatting the number as parsing it, to avoid culture differences:

```<code>CultureInfo cultureInfo = new CultureInfo("en-US", true);
string doubleMax = Double.MaxValue.ToString("R", cultureInfo);
Console.WriteLine(doubleMax);
double d;
if (Double.TryParse(doubleMax, NumberStyles.Any, cultureInfo.NumberFormat, out d)) {
  if (d == Double.MaxValue) {
    Console.WriteLine("parsed");
  } else {
    Console.WriteLine("value changed");
  }
} else {
  Console.WriteLine("couldn't parse");
}
</code>```

Output:

```<code>1.7976931348623157E+308
parsed
</code>```

Edit:

I added output of the string, and verification that the parsed value actually still is MaxValue.

Body:
I have static method that takes a string for input and returns the original input string if the string represents a number.  If the string does not represent a number the the input string is processed and a transformed string is returned.  I'm writing test cases.  I'm trying to verify that an input string containing either double.MinValue or double.MaxValue is returned unchanged.  I've read through a number of forums, including StackOverflow, and have come up with the following logic:

string doubleMax = double.MaxValue.ToString();
double d;
CultureInfo cultureInfo = new CultureInfo("en-US", true);
if (Double.TryParse(doubleMax, NumberStyles.Any, cultureInfo.NumberFormat, out d))
{
    Console.WriteLine("parsed");
}
else
{
    Console.WriteLine("couldn't parse");
}

Problem is the Double.TryParse() always returns false.  I've called TryParse() in a bunch of different ways, but the result is always the same, false.

This logic works if I use decimal.MinValue(), int.MinValue(), or float.MinValue().

Can someone tell me why my logic isn't working for double.MinValue?

Body:
That's because of the way that floating point numbers are stored and displayed. The value is rounded when it's turned into a human readable string, and for double.MaxValue it happens to be rounded up so that it no longer fits in a double.

You can use the round-trip format "R" to turn a value into a string that always can be parsed back to the same value, as it adds extra precision until the correct value is returned. Also, use the same culture when formatting the number as parsing it, to avoid culture differences:

CultureInfo cultureInfo = new CultureInfo("en-US", true);
string doubleMax = Double.MaxValue.ToString("R", cultureInfo);
Console.WriteLine(doubleMax);
double d;
if (Double.TryParse(doubleMax, NumberStyles.Any, cultureInfo.NumberFormat, out d)) {
  if (d == Double.MaxValue) {
    Console.WriteLine("parsed");
  } else {
    Console.WriteLine("value changed");
  }
} else {
  Console.WriteLine("couldn't parse");
}

Output:

1.7976931348623157E+308
parsed

Edit:

I added output of the string, and verification that the parsed value actually still is MaxValue.


问:
Can you assign a value to a returned object?
I am trying to implement Euclid's algorithm in Python3.
If max(a, b) returns the object with the largest value in (a, b),
why can't you operate on that object like so:

max(a, b) %= min(a, b)

答:
You can only assign to variables, but there's no way for a function to return a variable. (It can only return a value.)

For example:

```<code>a = 4
b = 5
max(a, b)  # What does this return?
</code>```

max(a, b) returns the value 5, not the variable b. (So the code you're trying to write is essentially 5 = ... which makes little sense.)

Body:
You can only assign to variables, but there's no way for a function to return a variable. (It can only return a value.)

For example:

a = 4
b = 5
max(a, b)  # What does this return?

max(a, b) returns the value 5, not the variable b. (So the code you're trying to write is essentially 5 = ... which makes little sense.)


问:
unknown column 'guru.kode_guru' in 'on clause'
SELECT jadwal_ajar.hari, jadwal_ajar.waktu, jenjang.nama_jenjang, jurusan.nama_jurusan, kelas.nama_kelas, mapel.nama_mapel, guru.nama_guru
FROM jadwal_ajar,guru  , jenjang , jurusan , kelas , mapel
LEFT JOIN jadwal_ajar as a5 ON guru.kode_guru = a5.kode_guru
LEFT JOIN jadwal_ajar as a1 ON kelas.kode_kelas = a1.kode_kelas
LEFT JOIN jadwal_ajar as a2 ON mapel.kode_mapel = a2.kode_mapel
LEFT JOIN jadwal_ajar as a3 ON j.kode_jenjang = a3.kode_jenjang
LEFT JOIN jadwal_ajar as a4 ON jurusan.kode_jurusan = a4.kode_jurusan

答:
The error you got is because of a missing field in the table guru, you should check it out.

And, from what I can see, I think that you are trying to join tables in the from, here is the way to achieve that:

```<code>SELECT jadwal_ajar.hari, jadwal_ajar.waktu,
       jenjang.nama_jenjang, jurusan.nama_jurusan, kelas.nama_kelas,
       mapel.nama_mapel, guru.nama_guru
FROM jadwal_ajar
LEFT JOIN guru ON guru.kode_guru = jadwal_ajar.kode_guru
LEFT JOIN kelas ON kelas.kode_kelas = jadwal_ajar.kode_kelas
LEFT JOIN mapel ON mapel.kode_mapel = jadwal_ajar.kode_mapel
LEFT JOIN jenjang ON jenjang.kode_jenjang = jadwal_ajar.kode_jenjang
LEFT JOIN jurusan ON jurusan.kode_jurusan = jadwal_ajar.kode_jurusan
</code>```

Body:
The error you got is because of a missing field in the table guru, you should check it out.

And, from what I can see, I think that you are trying to join tables in the from, here is the way to achieve that:

SELECT jadwal_ajar.hari, jadwal_ajar.waktu,
       jenjang.nama_jenjang, jurusan.nama_jurusan, kelas.nama_kelas,
       mapel.nama_mapel, guru.nama_guru
FROM jadwal_ajar
LEFT JOIN guru ON guru.kode_guru = jadwal_ajar.kode_guru
LEFT JOIN kelas ON kelas.kode_kelas = jadwal_ajar.kode_kelas
LEFT JOIN mapel ON mapel.kode_mapel = jadwal_ajar.kode_mapel
LEFT JOIN jenjang ON jenjang.kode_jenjang = jadwal_ajar.kode_jenjang
LEFT JOIN jurusan ON jurusan.kode_jurusan = jadwal_ajar.kode_jurusan


问:
jQuery - chrome lightbox
I've been creating an lightbox myself and everything is ok but only in chrome browser it something bad. I click on thumbnail later i want to change image with next button. Works well, later i click on prev button and i don't know what is happening. On mozilla works great without this problem.

Here's the wideo of my problem:
https://www.youtube.com/watch?v=38NOYGAT0R0&feature=youtu.be

And here's the code of prev fuction:

```<code>function prevImage() {

    var img2 = $(".lightbox__img").attr("src");
    src = img2.replace(/[^\d.]/g, '');
    numberOfImage = parseInt(src, 10);
    if (numberOfImage !== 1) {
        $(".lightbox__img").attr("src", "gallery/(" + (numberOfImage - 1) + ").jpg");
    } else {
        $(".lightbox__img").attr("src", "gallery/(" + 15 + ").jpg");
    }

}
</code>```

答:
try user-select: none. Here is a quick example: http://www.jsfiddle.net/pn3bry1e

   user non-selectable

   user selectable

Title: jQuery - chrome lightbox

Body:
I've been creating an lightbox myself and everything is ok but only in chrome browser it something bad. I click on thumbnail later i want to change image with next button. Works well, later i click on prev button and i don't know what is happening. On mozilla works great without this problem.

Here's the wideo of my problem:
https://www.youtube.com/watch?v=38NOYGAT0R0&feature=youtu.be

And here's the code of prev fuction:

function prevImage() {

    var img2 = $(".lightbox__img").attr("src");
    src = img2.replace(/[^\d.]/g, '');
    numberOfImage = parseInt(src, 10);
    if (numberOfImage !== 1) {
        $(".lightbox__img").attr("src", "gallery/(" + (numberOfImage - 1) + ").jpg");
    } else {
        $(".lightbox__img").attr("src", "gallery/(" + 15 + ").jpg");
    }

}

Body:
try user-select: none. Here is a quick example: http://www.jsfiddle.net/pn3bry1e

<div style='user-select: none'>
   user non-selectable
</div>
<div>
   user selectable
</div>


问:
Javascript how to run some code after a forEach completes executing
So I want to turn my "loading" gif on and off with ng-show. I would specifically like to turn it off after my script is done loading the array through a forEach.

How do I run code when the forEach completes its entire cycle". Something similar to a .then(), but for for loops

```<code>function selectAll(bool) {
  vm.selectAllSpinner = true;
  vm.practicesLeftCol = [];
  if(bool === true){
    vm.practices.forEach(function(practice){
      practice.selected = true;
      vm.practicesLeftCol.push(practice)
    })
    I want this after the foreach ->vm.selectAllSpinner = false;

  } else if (bool === false){
    vm.practices.forEach(function(practice){
      practice.selected = false;
      vm.practicesLeftCol = [];
    })
    I want this after the foreach ->vm.selectAllSpinner = false;

  }
</code>```

答:
Unfortunately forEach does not have a callback - but you could do something like this:</p>

```<code>  if(bool === true){
        vm.practices.forEach(function(practice){
          practice.selected = true;
          vm.practicesLeftCol.push(practice);
           items++;
           if(items === your_array.length) {
             vm.selectAllSpinner = false;
           }
        })

      }
</code>```

Body:
So I want to turn my "loading" gif on and off with ng-show. I would specifically like to turn it off after my script is done loading the array through a forEach.

How do I run code when the forEach completes its entire cycle". Something similar to a .then(), but for for loops

function selectAll(bool) {
  vm.selectAllSpinner = true;
  vm.practicesLeftCol = [];
  if(bool === true){
    vm.practices.forEach(function(practice){
      practice.selected = true;
      vm.practicesLeftCol.push(practice)
    })
    I want this after the foreach ->vm.selectAllSpinner = false;

  } else if (bool === false){
    vm.practices.forEach(function(practice){
      practice.selected = false;
      vm.practicesLeftCol = [];
    })
    I want this after the foreach ->vm.selectAllSpinner = false;

  }

Body:
Unfortunately forEach does not have a callback - but you could do something like this:

  if(bool === true){
        vm.practices.forEach(function(practice){
          practice.selected = true;
          vm.practicesLeftCol.push(practice);
           items++;
           if(items === your_array.length) {
             vm.selectAllSpinner = false;
           }
        })

      }


问:
XQuery Show Collection Name
What is the XQuery to search the entire database and show the collection name which has a given element-name?</p>

答:
Run it this way- I think it does what you expect. Returns the collections that include the "adr_key" element. Your query didn't work because your data is in the default namespace, not the html namespace that you have in your example. That semicolon can't be good either...anyway, here you go-</p>

```<code>cts:collections((), (),
cts:element-query(QName("", "adr_key"), cts:true-query())
)
</code>```

Title: XQuery Show Collection Name

Body:
Run it this way- I think it does what you expect. Returns the collections that include the "adr_key" element. Your query didn't work because your data is in the default namespace, not the html namespace that you have in your example. That semicolon can't be good either...anyway, here you go-

cts:collections((), (),
cts:element-query(QName("", "adr_key"), cts:true-query())
)


问:
Merge statement on a single record table
I need to write a single statement to insert or update a record in a single record table

the merge statement allows me to write this:

```<code>create table t1 (n int)

-- insert into t1 (n) Values (1);  -- uncomment to test the matched branch

MERGE t1 AS P
USING (SELECT 3 AS n) AS S
ON 1 = 1
WHEN MATCHED THEN
    UPDATE SET n = S.n
WHEN NOT MATCHED THEN
    INSERT (n)
    VALUES (S.n);

select * from t1
</code>```

this work, but I think that the 1=1 condition purpose is not very easy to understand.
Is there a different syntax to insert a record when the table is empty or update the record when it does already exist?

答:
The other option would be to do it the old fashioned way.</p>

```<code>if exists (select null from t1)
    update t1 set n = 3
else
    insert into t1 (n) values (3)
</code>```

Body:
I need to write a single statement to insert or update a record in a single record table

the merge statement allows me to write this:

create table t1 (n int)

-- insert into t1 (n) Values (1);  -- uncomment to test the matched branch

MERGE t1 AS P
USING (SELECT 3 AS n) AS S
ON 1 = 1
WHEN MATCHED THEN
    UPDATE SET n = S.n
WHEN NOT MATCHED THEN
    INSERT (n)
    VALUES (S.n);

select * from t1

this work, but I think that the 1=1 condition purpose is not very easy to understand.
Is there a different syntax to insert a record when the table is empty or update the record when it does already exist?

Body:
The other option would be to do it the old fashioned way.

if exists (select null from t1)
    update t1 set n = 3
else
    insert into t1 (n) values (3)


问:
Custom UITextField clear button
Is it possible to customize the image of the clear button in a UITextField? I have a dark textfield background and the "x" is not visible enough.

答:
Swift 3

```<code>let customClearButton = UIButton.appearance(whenContainedInInstancesOf: [UITextField.self])
customClearButton.setBackgroundImage(UIImage(named: "custom_cb"), for: .normal)
</code>```

Title: Custom UITextField clear button

Body:
Swift 3

let customClearButton = UIButton.appearance(whenContainedInInstancesOf: [UITextField.self])
customClearButton.setBackgroundImage(UIImage(named: "custom_cb"), for: .normal)


问:
How do I use input if the user entered a char into an int?
I have a code in which I read ints into a vector.

```<code>vector <int> v;

for (int i; cin >> i;){
    v.push_back(i);
}
</code>```

and to end the loop, the user must enter '/'. How would I do that?
in other words, if the user enters a char into an int, how do I use the input?

答: You just about need to read the individual chars (or strings) from the stream. Then determine whether it's actually a number or not. If it is, convert it (e.g., using std::stoi). If not, check whether it's the "quit" symbol, and if so go on to whatever else you need to do. If it's something else, you'd typically report the error, and if it's meant to be used interactively, probably give the user another chance to enter the right thing.

Body:
I have a code in which I read ints into a vector.

vector <int> v;

for (int i; cin >> i;){
    v.push_back(i);
}

and to end the loop, the user must enter '/'. How would I do that?
in other words, if the user enters a char into an int, how do I use the input?


问:
Java CSV Formatting Issues
I am reading a HashMap and creating a CSV file.
The below code accepts a HashMap and produce a CSV file. However the formatting is a problem. For a HashMap,

```<code>HashMap<String, Integer> hmap = new HashMap<String, Integer>();
hmap.put("Feature1", 1);
hmap.put("Feature2", 2);
</code>```

It produces

```<code>Feature2,Feature2,
2,1,Feature1,Feature1,
2,1,
</code>```

Expected Output (without comma at the end of each line):

```<code>Feature2,Feature1
2,1
</code>```

Which is  a wrong formatting

This is the code I use. How to fix it ?

```<code>public String appendCSV(Map featureset) throws IOException{
    StringBuilder csvReport = new StringBuilder();

    Map<String, Integer> map =featureset;
    Set<String> keys = map.keySet();

    String[] lsitofkeys = {};

    for(String elements:keys){
        for(int i =0 ; i< keys.size(); i++){
             csvReport.append(elements+",");
        }
        csvReport.append("\n");
        for(String key: keys){
            csvReport.append(map.get(key).toString()+",");
        }
    }

  return csvReport.toString();
}
</code>```

答:
You should have a separate StringBuilder for the keys and another one for the values. Then as you go through your keys you add them to your key StringBuilder and then take the map given and grab the value associated with that key and add it to your value StringBuilder.

Lastly you just keep track of how many keys you have seen so far. If the number of keys seen is not equal to the size of the map then you append a comma. But if you are on the last element according to the numOfKeys counter, then you append nothing to the end of the StringBuilders.

```<code>    StringBuilder csvKeyReport = new StringBuilder();
    StringBuilder csvValueReport = new StringBuilder();

    Map<String, Integer> map = hmap;
    Set<String> keys = map.keySet();

    int numOfKeys = 0;

    for(String key : keys)
    {
        numOfKeys++;
        String comma = numOfKeys == map.size() ? "" : ",";
        csvKeyReport.append(key + comma);
        csvValueReport.append(map.get(key) + comma);
    }

    csvKeyReport.append("\n");
    csvKeyReport.append(csvValueReport.toString() + "\n");

    System.out.print(csvKeyReport.toString());
</code>```

Output

```<code>Feature2,Feature1
2,1
</code>```

Title: Java CSV Formatting Issues

Body:
I am reading a HashMap and creating a CSV file.
The below code accepts a HashMap and produce a CSV file. However the formatting is a problem. For a HashMap,

HashMap<String, Integer> hmap = new HashMap<String, Integer>();
hmap.put("Feature1", 1);
hmap.put("Feature2", 2);

It produces

Feature2,Feature2,
2,1,Feature1,Feature1,
2,1,

Expected Output (without comma at the end of each line):

Feature2,Feature1
2,1

Which is  a wrong formatting

This is the code I use. How to fix it ?

public String appendCSV(Map featureset) throws IOException{
    StringBuilder csvReport = new StringBuilder();

    Map<String, Integer> map =featureset;
    Set<String> keys = map.keySet();

    String[] lsitofkeys = {};

    for(String elements:keys){
        for(int i =0 ; i< keys.size(); i++){
             csvReport.append(elements+",");
        }
        csvReport.append("\n");
        for(String key: keys){
            csvReport.append(map.get(key).toString()+",");
        }
    }

  return csvReport.toString();
}

Body:
You should have a separate StringBuilder for the keys and another one for the values. Then as you go through your keys you add them to your key StringBuilder and then take the map given and grab the value associated with that key and add it to your value StringBuilder.

Lastly you just keep track of how many keys you have seen so far. If the number of keys seen is not equal to the size of the map then you append a comma. But if you are on the last element according to the numOfKeys counter, then you append nothing to the end of the StringBuilders.

    StringBuilder csvKeyReport = new StringBuilder();
    StringBuilder csvValueReport = new StringBuilder();

    Map<String, Integer> map = hmap;
    Set<String> keys = map.keySet();

    int numOfKeys = 0;

    for(String key : keys)
    {
        numOfKeys++;
        String comma = numOfKeys == map.size() ? "" : ",";
        csvKeyReport.append(key + comma);
        csvValueReport.append(map.get(key) + comma);
    }

    csvKeyReport.append("\n");
    csvKeyReport.append(csvValueReport.toString() + "\n");

    System.out.print(csvKeyReport.toString());

Output

Feature2,Feature1
2,1


问:
java.lang.UnsatisfiedLinkError: org.bytedeco.javacpp.avutil while using "gpuImage" with "javacv" in android
I want to use both javacv and gpuimagein my android application. Everything works fine if i only include javacv in my app. When i include gpuimage in my app, it crashes and shows this message.

```<code>java.lang.UnsatisfiedLinkError: org.bytedeco.javacpp.avutil
    at java.lang.Class.classForName(Native Method)
    at java.lang.Class.forName(Class.java:308)
    at org.bytedeco.javacpp.Loader.load(Loader.java:413)
    at org.bytedeco.javacpp.Loader.load(Loader.java:381)
    at org.bytedeco.javacpp.avcodec$AVPacket.<clinit>(avcodec.java:1650)
    at org.bytedeco.javacv.FFmpegFrameRecorder.<init>(FFmpegFrameRecorder.java:149)
    at org.bytedeco.javacv.FFmpegFrameRecorder.<init>(FFmpegFrameRecorder.java:126)
    at com.example.app.ShareActivity.initRecorder(ShareActivity.java:351)
    at com.example.app.ShareActivity.access$1000(ShareActivity.java:49)
    at com.example.app.ShareActivity$8.run(ShareActivity.java:398)
    at java.lang.Thread.run(Thread.java:818)
</code>```

This my build.gradle

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

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.example.app"
        minSdkVersion 15
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"

    }

    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support:support-v4:23.4.0'
    compile 'jp.co.cyberagent.android.gpuimage:gpuimage-library:1.4.1'
    compile 'com.android.support:design:23.4.0'
    compile 'org.bytedeco:javacv:1.1'
    compile 'com.google.android.gms:play-services-ads:8.4.0'
    compile 'com.googlecode.mp4parser:isoparser:1.1.18'
}
</code>```

i extracted ffmpeg-android-arm.jar and kept all *.so files inside app\src\jniLibs\armeabi. App works properly without gpuimage.

答:
Remove

```<code>compile 'org.bytedeco:javacv:1.1'
</code>```

from your Gradle and add the lines below

```<code>compile(group: 'org.bytedeco', name: 'javacv-platform', version: '1.3'){
    exclude group: 'org.bytedeco.javacpp-presets'
}
compile group: 'org.bytedeco.javacpp-presets', name: 'ffmpeg', version: '3.2.1-1.3'
compile group: 'org.bytedeco.javacpp-presets', name: 'ffmpeg', version: '3.2.1-1.3', classifier: 'android-arm'
</code>```

Body:
I want to use both javacv and gpuimagein my android application. Everything works fine if i only include javacv in my app. When i include gpuimage in my app, it crashes and shows this message.

java.lang.UnsatisfiedLinkError: org.bytedeco.javacpp.avutil
    at java.lang.Class.classForName(Native Method)
    at java.lang.Class.forName(Class.java:308)
    at org.bytedeco.javacpp.Loader.load(Loader.java:413)
    at org.bytedeco.javacpp.Loader.load(Loader.java:381)
    at org.bytedeco.javacpp.avcodec$AVPacket.<clinit>(avcodec.java:1650)
    at org.bytedeco.javacv.FFmpegFrameRecorder.<init>(FFmpegFrameRecorder.java:149)
    at org.bytedeco.javacv.FFmpegFrameRecorder.<init>(FFmpegFrameRecorder.java:126)
    at com.example.app.ShareActivity.initRecorder(ShareActivity.java:351)
    at com.example.app.ShareActivity.access$1000(ShareActivity.java:49)
    at com.example.app.ShareActivity$8.run(ShareActivity.java:398)
    at java.lang.Thread.run(Thread.java:818)

This my build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.example.app"
        minSdkVersion 15
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"

    }

    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support:support-v4:23.4.0'
    compile 'jp.co.cyberagent.android.gpuimage:gpuimage-library:1.4.1'
    compile 'com.android.support:design:23.4.0'
    compile 'org.bytedeco:javacv:1.1'
    compile 'com.google.android.gms:play-services-ads:8.4.0'
    compile 'com.googlecode.mp4parser:isoparser:1.1.18'
}

i extracted ffmpeg-android-arm.jar and kept all *.so files inside app\src\jniLibs\armeabi. App works properly without gpuimage.

Body:
Remove

compile 'org.bytedeco:javacv:1.1'

from your Gradle and add the lines below

compile(group: 'org.bytedeco', name: 'javacv-platform', version: '1.3'){
    exclude group: 'org.bytedeco.javacpp-presets'
}
compile group: 'org.bytedeco.javacpp-presets', name: 'ffmpeg', version: '3.2.1-1.3'
compile group: 'org.bytedeco.javacpp-presets', name: 'ffmpeg', version: '3.2.1-1.3', classifier: 'android-arm'


问:
Data matching in R
I have two dataframes with the same length (1000) and width (200). In both dataframes, each row is a person. In one dataframe, each column is a binary item score (i.e. 0 or 1). In the other dataframe, each column is the item label. Here is it:

Dataframe 1:

```<code>item1 item2 item3
0     1     1
1     0     0
1     1     1
</code>```

Dataframe 2:

```<code>item1   item2   item3
C2HSD   WW11S3  EI22S
WW11S3  2JDDS   TT6SQ1
EI22S   TT6SQ1  331ID
</code>```

What I want is a combined and matched dataframe like this:

```<code>C2HSD  WW11S3 EI22S 2JDDS TT6SQ1 331ID
0      1      1     NA    NA     NA
NA     1      NA    0     0      NA
NA     NA     1     NA    1      1
</code>```

Thank you!

答:
An attempt in base R uses mapply and match as follows. The code below uses match to return a vector with NAs where a column of dat2 does not have any of the variables and the respective value of dat1 where there is a match in dat2. For the desired output structure, the dat1 data.frame has to be transposed (data.frame(t(dat1))).

```<code># get the vector of unique names in dat2
vars <- unique(unlist(dat2))
mapply(function(x, y, vars) x[match(vars, y)],
       data.frame(t(dat1)), dat2, MoreArgs=list(vars=vars))
     X1 X2 X3
[1,]  0 NA NA
[2,]  1  1 NA
[3,]  1 NA  1
[4,] NA  0 NA
[5,] NA  0  1
[6,] NA NA  1
</code>```

to return a data.frame with the named variables, wrap this in t, data.frame, and setNames.

```<code>setNames(data.frame(t(mapply(function(x, y, vars) x[match(vars, y)],
                             data.frame(t(dat1)), dat2, MoreArgs=list(vars=vars)))), vars)

   C2HSD WW11S3 EI22S 2JDDS TT6SQ1 331ID
X1     0      1     1    NA     NA    NA
X2    NA      1    NA     0      0    NA
X3    NA     NA     1    NA      1     1
</code>```

The data below has dat2 as character vectors rather than factors. This is the preferable storage type for this sort of operation.

data

```<code>dat1 <-
structure(list(item1 = c(0L, 1L, 1L), item2 = c(1L, 0L, 1L),
    item3 = c(1L, 0L, 1L)), .Names = c("item1", "item2", "item3"
), class = "data.frame", row.names = c(NA, -3L))
dat2 <-
structure(list(item1 = c("C2HSD", "WW11S3", "EI22S"), item2 = c("WW11S3",
"2JDDS", "TT6SQ1"), item3 = c("EI22S", "TT6SQ1", "331ID")), .Names = c("item1",
"item2", "item3"), class = "data.frame", row.names = c(NA, -3L
))
</code>```

Title: Data matching in R

Body:
I have two dataframes with the same length (1000) and width (200). In both dataframes, each row is a person. In one dataframe, each column is a binary item score (i.e. 0 or 1). In the other dataframe, each column is the item label. Here is it:

Dataframe 1:

item1 item2 item3
0     1     1
1     0     0
1     1     1

Dataframe 2:

item1   item2   item3
C2HSD   WW11S3  EI22S
WW11S3  2JDDS   TT6SQ1
EI22S   TT6SQ1  331ID

What I want is a combined and matched dataframe like this:

C2HSD  WW11S3 EI22S 2JDDS TT6SQ1 331ID
0      1      1     NA    NA     NA
NA     1      NA    0     0      NA
NA     NA     1     NA    1      1

Thank you!

Body:
An attempt in base R uses mapply and match as follows. The code below uses match to return a vector with NAs where a column of dat2 does not have any of the variables and the respective value of dat1 where there is a match in dat2. For the desired output structure, the dat1 data.frame has to be transposed (data.frame(t(dat1))).

# get the vector of unique names in dat2
vars <- unique(unlist(dat2))
mapply(function(x, y, vars) x[match(vars, y)],
       data.frame(t(dat1)), dat2, MoreArgs=list(vars=vars))
     X1 X2 X3
[1,]  0 NA NA
[2,]  1  1 NA
[3,]  1 NA  1
[4,] NA  0 NA
[5,] NA  0  1
[6,] NA NA  1

to return a data.frame with the named variables, wrap this in t, data.frame, and setNames.

setNames(data.frame(t(mapply(function(x, y, vars) x[match(vars, y)],
                             data.frame(t(dat1)), dat2, MoreArgs=list(vars=vars)))), vars)

   C2HSD WW11S3 EI22S 2JDDS TT6SQ1 331ID
X1     0      1     1    NA     NA    NA
X2    NA      1    NA     0      0    NA
X3    NA     NA     1    NA      1     1

The data below has dat2 as character vectors rather than factors. This is the preferable storage type for this sort of operation.

data

dat1 <-
structure(list(item1 = c(0L, 1L, 1L), item2 = c(1L, 0L, 1L),
    item3 = c(1L, 0L, 1L)), .Names = c("item1", "item2", "item3"
), class = "data.frame", row.names = c(NA, -3L))
dat2 <-
structure(list(item1 = c("C2HSD", "WW11S3", "EI22S"), item2 = c("WW11S3",
"2JDDS", "TT6SQ1"), item3 = c("EI22S", "TT6SQ1", "331ID")), .Names = c("item1",
"item2", "item3"), class = "data.frame", row.names = c(NA, -3L
))


问:
How to avoid hard-coding URLS in the static files on Django?
Is there any techniques to avoid hard coding URLs, especially the URLs for Ajax calls in an external static resource file like JavaScript files in Django.</p>

答:
I don't know if there is any standard way to avoid hardcoding the URLs in the JavaScript files, but I could suggest a method. You could define an object in a separate file, something like "constants.js" in a format,

```<code>var api = {
    api_name1 : "url_ for your api1",
    api_name2 : "url_ for your api2",
    };
</code>```

And remember to invoke the file before any other js files using the script tags. Then, the JavaScript will put this object "api" to the top of the declarations, due to the variable hoisting in JavaScript. Also, you could access each URL by calling api.api_name1. In case, if there is a change in the URLs, you only need to change in this file "constants.js".

This is a method I'm following inorder to avoid hardcoding the URLs myself. You could follow this or if you find another one which is better or efficient than this, please let me know.

Body:
I don't know if there is any standard way to avoid hardcoding the URLs in the JavaScript files, but I could suggest a method. You could define an object in a separate file, something like "constants.js" in a format,

var api = {
    api_name1 : "url_ for your api1",
    api_name2 : "url_ for your api2",
    };

And remember to invoke the file before any other js files using the script tags. Then, the JavaScript will put this object "api" to the top of the declarations, due to the variable hoisting in JavaScript. Also, you could access each URL by calling api.api_name1. In case, if there is a change in the URLs, you only need to change in this file "constants.js".

This is a method I'm following inorder to avoid hardcoding the URLs myself. You could follow this or if you find another one which is better or efficient than this, please let me know.


问:
How do I write a custom init for a UIView subclass in Swift?
Say I want to init a UIView subclass with a String and an Int.

How would I do this in Swift if I'm just subclassing UIView? If I just make a custom init() function but the parameters are a String and an Int, it tells me that "super.init() isn't called before returning from initializer".

And if I call super.init() I'm told I must use a designated initializer. What should I be using there? The frame version? The coder version? Both? Why?

答:
I create a common init for the designated and required. For convenience inits I delegate to init(frame:) with frame of zero.

Having zero frame is not a problem because typically the view is inside a ViewController's view; your custom view will get a good, safe chance to layout its subviews when its superview calls layoutSubviews() or updateConstraints(). These two functions are called by the system recursively throughout the view hierarchy. You can use either updateContstraints() or layoutSubviews(). updateContstraints() is called first, then layoutSubviews(). In updateConstraints() make sure to call super last. In layoutSubviews(), call super first.

Here's what I do:

```<code>@IBDesignable
class MyView: UIView {

      convenience init(args: Whatever) {
          self.init(frame: CGRect.zero)
          //assign custom vars
      }

      override init(frame: CGRect) {
           super.init(frame: frame)
           commonInit()
      }

      required init?(coder aDecoder: NSCoder) {
           super.init(coder: aDecoder)
           commonInit()
      }

      override func prepareForInterfaceBuilder() {
           super.prepareForInterfaceBuilder()
           commonInit()
      }

      private func commonInit() {
           //custom initialization
      }

      override func updateConstraints() {
           //set subview constraints here
           super.updateConstraints()
      }

      override func layoutSubviews() {
           super.layoutSubviews()
           //manually set subview frames here
      }

}
</code>```

Body:
I create a common init for the designated and required. For convenience inits I delegate to init(frame:) with frame of zero.

Having zero frame is not a problem because typically the view is inside a ViewController's view; your custom view will get a good, safe chance to layout its subviews when its superview calls layoutSubviews() or updateConstraints(). These two functions are called by the system recursively throughout the view hierarchy. You can use either updateContstraints() or layoutSubviews(). updateContstraints() is called first, then layoutSubviews(). In updateConstraints() make sure to call super last. In layoutSubviews(), call super first.

Here's what I do:

@IBDesignable
class MyView: UIView {

      convenience init(args: Whatever) {
          self.init(frame: CGRect.zero)
          //assign custom vars
      }

      override init(frame: CGRect) {
           super.init(frame: frame)
           commonInit()
      }

      required init?(coder aDecoder: NSCoder) {
           super.init(coder: aDecoder)
           commonInit()
      }

      override func prepareForInterfaceBuilder() {
           super.prepareForInterfaceBuilder()
           commonInit()
      }

      private func commonInit() {
           //custom initialization
      }

      override func updateConstraints() {
           //set subview constraints here
           super.updateConstraints()
      }

      override func layoutSubviews() {
           super.layoutSubviews()
           //manually set subview frames here
      }

}


问:
Should I include file extensions when setting registry items?
In two instances I define registry items which I specify the name of the template and css files.  Should I include the file extension when setting the registry items, or exclude them as I am currently doing with my application?  What do you advise?

```<code> $registryItems['template']    = 'default'; //Name of .tpl file
 $registryItems['stylesheet']  = 'default'; //Name of .css file
</code>```

Thanks in advance!

答: A CSS file doesn't necessarily have to have the .css extension. The same is true for templates. They could as well end with .txt. Therefore if you do not include the extension you have to implement them as conventions in your code with the effect that all files of a type must have the same extension. Strictness vs. flexibility.</p>

Body:
In two instances I define registry items which I specify the name of the template and css files.  Should I include the file extension when setting the registry items, or exclude them as I am currently doing with my application?  What do you advise?

 $registryItems['template']    = 'default'; //Name of .tpl file
 $registryItems['stylesheet']  = 'default'; //Name of .css file

Thanks in advance!


问:
Larval left join with Eloquent causing id field to be overwritten
I am building search listings application using Laravel; the app needs to search for Businesses by distance (which I've already built) and include the latest subscription to a business (if any) so I can order by it and then distance.

The two models here are Business and Subscriptions. A Business can have many Subscriptions (although there will only ever be one thats active).

Controller

```<code>$businesses = Business::distance($place['lat'], $place['lng'], $request->distance)
                        ->ofShopType($request->shop_type)
                        ->uptoBudget($request->price)
                        ->leftJoin('subscriptions', function($join) {
                            $join->on('businesses.id', '=', 'subscriptions.business_id')
                                 ->orderBy('subscriptions.created_at', 'desc');
                        });
return $businesses = $businesses->get();
</code>```

Business Model

```<code>public function scopeDistance($query,$from_latitude,$from_longitude,$distance)
{
    $raw = \DB::raw('ROUND ( ( 3959 * acos( cos( radians('.$from_latitude.') ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians('.$from_longitude.') ) + sin( radians('.$from_latitude.') ) * sin( radians( latitude ) ) ) ), 1 ) AS distance');
    return $query->select('*')->addSelect($raw)
             ->orderBy( 'distance', 'ASC' )
             ->groupBy('businesses.id')
             ->having('distance', '<=', $distance);
}
</code>```

So the difficulties I am getting are that the business.id field is being overwritten by the subscription.id.
I've done some searching and have read that including ->select('businesses.*') before the leftJoin should resolve this, however by doing this I get the following error:

```<code>SQLSTATE[42S22]: Column not found: 1054 Unknown column
      'business.distance' in 'having clause'
      (SQL: select `businesses`.*
          from `businesses`
          left join `subscriptions`
                   on `businesses`.`id` = `subscriptions`.`business_id`
          where `shop_type_id` = 1
            and `min_cost` <= 100
          group by `distance`, `businesses`.`id`
          having `distance` <= 50
          order by `distance` asc)
</code>```

The second issue is that the left join seems to get the first record, I would like to get the most recent record (by created_at). You can see that I already have an orderBy line in my controller but this has no affect as I can see its still returning an older record even though a newer record is available.

答:
You could add a lastSubscription() relation to your Business model:

```<code>public function lastSubscription()
{
    return $this->hasOne(Subscription::class)->orderBy('created_at', 'desc');
}
</code>```

Then in your controller you'd be able to do:

```<code>return Business::distance($place['lat'], $place['lng'], $request->distance)
                        ->ofShopType($request->shop_type)
                        ->uptoBudget($request->price)
                        ->with('lastSubscription')
                        ->get();
</code>```

Body:
I am building search listings application using Laravel; the app needs to search for Businesses by distance (which I've already built) and include the latest subscription to a business (if any) so I can order by it and then distance.

The two models here are Business and Subscriptions. A Business can have many Subscriptions (although there will only ever be one thats active).

Controller

$businesses = Business::distance($place['lat'], $place['lng'], $request->distance)
                        ->ofShopType($request->shop_type)
                        ->uptoBudget($request->price)
                        ->leftJoin('subscriptions', function($join) {
                            $join->on('businesses.id', '=', 'subscriptions.business_id')
                                 ->orderBy('subscriptions.created_at', 'desc');
                        });
return $businesses = $businesses->get();

Business Model

public function scopeDistance($query,$from_latitude,$from_longitude,$distance)
{
    $raw = \DB::raw('ROUND ( ( 3959 * acos( cos( radians('.$from_latitude.') ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians('.$from_longitude.') ) + sin( radians('.$from_latitude.') ) * sin( radians( latitude ) ) ) ), 1 ) AS distance');
    return $query->select('*')->addSelect($raw)
             ->orderBy( 'distance', 'ASC' )
             ->groupBy('businesses.id')
             ->having('distance', '<=', $distance);
}

So the difficulties I am getting are that the business.id field is being overwritten by the subscription.id.
I've done some searching and have read that including ->select('businesses.*') before the leftJoin should resolve this, however by doing this I get the following error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column
      'business.distance' in 'having clause'
      (SQL: select `businesses`.*
          from `businesses`
          left join `subscriptions`
                   on `businesses`.`id` = `subscriptions`.`business_id`
          where `shop_type_id` = 1
            and `min_cost` <= 100
          group by `distance`, `businesses`.`id`
          having `distance` <= 50
          order by `distance` asc)

The second issue is that the left join seems to get the first record, I would like to get the most recent record (by created_at). You can see that I already have an orderBy line in my controller but this has no affect as I can see its still returning an older record even though a newer record is available.

Body:
You could add a lastSubscription() relation to your Business model:

public function lastSubscription()
{
    return $this->hasOne(Subscription::class)->orderBy('created_at', 'desc');
}

Then in your controller you'd be able to do:

return Business::distance($place['lat'], $place['lng'], $request->distance)
                        ->ofShopType($request->shop_type)
                        ->uptoBudget($request->price)
                        ->with('lastSubscription')
                        ->get();


答:
I believe the short answer to your question is no. The function max(a,b) is returning the largest value to you, not a variable reference to the largest value.

I believe what you are looking for is:

```<code>if max(a,b) == a:
    a %= min(a,b)
else
    b %= min(a,b)
</code>```

which will check if the largest value is indeed the variable a before the assignment.

Title: Can you assign a value to a returned object?

Body:
I am trying to implement Euclid's algorithm in Python3.
If max(a, b) returns the object with the largest value in (a, b),
why can't you operate on that object like so:

max(a, b) %= min(a, b)

Body:
I believe the short answer to your question is no. The function max(a,b) is returning the largest value to you, not a variable reference to the largest value.

I believe what you are looking for is:

if max(a,b) == a:
    a %= min(a,b)
else
    b %= min(a,b)

which will check if the largest value is indeed the variable a before the assignment.


问:
How to load a Tensorflow graph created in a non-distributed environment to a distributed environment?
I shall create a Tensorflow graph for a single node run. But later if I want to train the same model graph on a distributed environment (divide variables between multiple parameter servers and replicate the graph between n workers), how do I do it ?

I found something called tf.Graph.as_graph_def() to export the GraphDef proto and later import the graph as tf.import_graph_def(). But this did not work.

Code:

```<code>import tensorflow as tf

graph = tf.Graph()

with graph.as_default():
    x_place_holder = tf.placeholder(dtype=tf.float32, shape=[], name="xin")
    y_place_holder = tf.placeholder(dtype=tf.float32, shape=[], name="yin")

    m = tf.Variable(10.0, name="varm")
    l = tf.Variable(20.0, name="varl")

    Y = tf.multiply(m, x_place_holder, name="mulop")
    X = tf.add(l, x_place_holder, name="addop")
    cost = tf.abs(Y - X, name="cost")

    optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.5, name="optimizer").minimize(cost)

tf.reset_default_graph()

if FLAGS.job_name == "ps":
    server.join()

elif FLAGS.job_name == "worker":
    print(FLAGS.task_index, "task index")

    with tf.device(tf.train.replica_device_setter(
            worker_device="/job:worker/task:%d" % FLAGS.task_index,
            cluster=cluster)):
        tf.import_graph_def(graph.as_graph_def(),return_elements=["xin","yin","varm","varl","mulop","addop","cost","optimizer"])
</code>```

Stacktrace:

```<code>    Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1039, in _do_call
    return fn(*args)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1017, in _run_fn
    self._extend_graph()
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1066, in _extend_graph
    self._session, graph_def.SerializeToString(), status)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/contextlib.py", line 66, in __exit__
    next(self.gen)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/tensorflow/python/framework/errors_impl.py", line 466, in raise_exception_on_not_ok_status
    pywrap_tensorflow.TF_GetCode(status))
tensorflow.python.framework.errors_impl.InvalidArgumentError: Cannot colocate nodes 'import/varl/read' and 'import/varl: Cannot merge devices with incompatible jobs: '/job:ps/task:1' and '/job:worker/task:1'
     [[Node: import/varl/read = Identity[T=DT_FLOAT, _class=["loc:@import/varl"], _device="/job:worker/task:1"](import/varl)]]
</code>```

Or is there any other way that Tensorflow allows to do that ?

答: This is not  supported as of june 2017. To train a model in a distributed environment you can reuse the graph-generating python code if it's wrapped in a replica_device_setter, but not the generated graph itself.</p>

Body:
I shall create a Tensorflow graph for a single node run. But later if I want to train the same model graph on a distributed environment (divide variables between multiple parameter servers and replicate the graph between n workers), how do I do it ?

I found something called tf.Graph.as_graph_def() to export the GraphDef proto and later import the graph as tf.import_graph_def(). But this did not work.

Code:

import tensorflow as tf

graph = tf.Graph()

with graph.as_default():
    x_place_holder = tf.placeholder(dtype=tf.float32, shape=[], name="xin")
    y_place_holder = tf.placeholder(dtype=tf.float32, shape=[], name="yin")

    m = tf.Variable(10.0, name="varm")
    l = tf.Variable(20.0, name="varl")

    Y = tf.multiply(m, x_place_holder, name="mulop")
    X = tf.add(l, x_place_holder, name="addop")
    cost = tf.abs(Y - X, name="cost")

    optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.5, name="optimizer").minimize(cost)

tf.reset_default_graph()

if FLAGS.job_name == "ps":
    server.join()

elif FLAGS.job_name == "worker":
    print(FLAGS.task_index, "task index")

    with tf.device(tf.train.replica_device_setter(
            worker_device="/job:worker/task:%d" % FLAGS.task_index,
            cluster=cluster)):
        tf.import_graph_def(graph.as_graph_def(),return_elements=["xin","yin","varm","varl","mulop","addop","cost","optimizer"])

Stacktrace:

    Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1039, in _do_call
    return fn(*args)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1017, in _run_fn
    self._extend_graph()
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1066, in _extend_graph
    self._session, graph_def.SerializeToString(), status)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/contextlib.py", line 66, in __exit__
    next(self.gen)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/tensorflow/python/framework/errors_impl.py", line 466, in raise_exception_on_not_ok_status
    pywrap_tensorflow.TF_GetCode(status))
tensorflow.python.framework.errors_impl.InvalidArgumentError: Cannot colocate nodes 'import/varl/read' and 'import/varl: Cannot merge devices with incompatible jobs: '/job:ps/task:1' and '/job:worker/task:1'
     [[Node: import/varl/read = Identity[T=DT_FLOAT, _class=["loc:@import/varl"], _device="/job:worker/task:1"](import/varl)]]

Or is there any other way that Tensorflow allows to do that ?


问:
How to center absolutely positioned children of a flex container in Safari?
I have a container that contains both an image, and some text. I want the text to be vertically and horizontally centered in the middle of the image.

It seems that the easiest, forward-thinking method is to use Flexbox and absolute positioning of the text:

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.text {
  position: absolute;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='container'>
  <div class='text'>
    This should be centered
  </div>
  <img src="https://placehold.it/250x250" />
</div></code>```

The text is centered in both axes. This seems to work in all modern browsers..... except Safari.

Safari appear to not center the text at all. It's just sitting at the top/left of the container like a normal absolutely positioned element would be in a non-flexbox layout.

Safari (wrong):

All other browsers (correct):

I thought Flexbox was really ready for primetime, but this seems like a deal-breaker considering how many people using Safari on iOS. Centering content horizontally and vertically is something Flexbox should be great at.

My only real alternative here is to not use Flexbox and then use:

```<code>.text {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%);
}
</code>```

But I would much rather be using Flexbox for progressive reasons.

Is there anything I'm missing here? As much as I hate to ask for it, is there some of Safari-only work-around here? Is there any solution to this besides just "not using flexbox" because if that is the answer in mid-2017 that is going to be disappointing.

JSFiddle for reference: https://jsfiddle.net/z7kh5Laz/4/

答:
When it comes to Flexbox and absolute positioning, there is a few do's and don't's, and in this case, Safari won't center an absolute positioned element the other browsers does.

You can combine Flexbox and transform: translate, as the latter does not impact the former, and when times comes, where they all behave the same with Flexbox alone, you can just drop the transform/left/top part.

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.text {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='container'>
  <div class='text'>
    This should be centered
  </div>
  <img src="https://placehold.it/250x250"/>
</div></code>```

Body:
I have a container that contains both an image, and some text. I want the text to be vertically and horizontally centered in the middle of the image.

It seems that the easiest, forward-thinking method is to use Flexbox and absolute positioning of the text:

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.text {
  position: absolute;
}

    This should be centered

The text is centered in both axes. This seems to work in all modern browsers..... except Safari.

Safari appear to not center the text at all. It's just sitting at the top/left of the container like a normal absolutely positioned element would be in a non-flexbox layout.

Safari (wrong):

All other browsers (correct):

I thought Flexbox was really ready for primetime, but this seems like a deal-breaker considering how many people using Safari on iOS. Centering content horizontally and vertically is something Flexbox should be great at.

My only real alternative here is to not use Flexbox and then use:

.text {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%);
}

But I would much rather be using Flexbox for progressive reasons.

Is there anything I'm missing here? As much as I hate to ask for it, is there some of Safari-only work-around here? Is there any solution to this besides just "not using flexbox" because if that is the answer in mid-2017 that is going to be disappointing.

JSFiddle for reference: https://jsfiddle.net/z7kh5Laz/4/

Body:
When it comes to Flexbox and absolute positioning, there is a few do's and don't's, and in this case, Safari won't center an absolute positioned element the other browsers does.

You can combine Flexbox and transform: translate, as the latter does not impact the former, and when times comes, where they all behave the same with Flexbox alone, you can just drop the transform/left/top part.

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.text {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%);
}

<div class='container'>
  <div class='text'>
    This should be centered
  </div>
  <img src="https://placehold.it/250x250"/>
</div>


问:
Do you recommend using semicolons after every statement in JavaScript?
In many situations, JavaScript parsers will insert semicolons for you if you leave them out. My question is, do you leave them out?

If you're unfamiliar with the rules, there's a description of semicolon insertion on the Mozilla site. Here's the key point:

If the first through the nth tokens of a JavaScript program form are grammatically valid but the first through the n+1st tokens are not and there is a line break between the nth tokens and the n+1st tokens, then the parser tries to parse the program again after inserting a virtual semicolon token between the nth and the n+1st tokens.

That description may be incomplete, because it doesn't explain @Dreas's example. Anybody have a link to the complete rules, or see why the example gets a semicolon? (I tried it in JScript.NET.)

This stackoverflow question is related, but only talks about a specific scenario.

答: I think this is similar to what the last podcast discussed. The "Be liberal in what you accept" means that extra work had to be put into the Javascript parser to fix cases where semicolons were left out.  Now we have a boatload of pages out there floating around with bad syntax, that might break one day in the future when some browser decides to be a little more stringent on what it accepts. This type of rule should also apply to HTML and CSS.  You can write broken HTML and CSS, but don't be surprise when you get weird and hard to debug behaviors when some browser doesn't properly interpret your incorrect code.  </p>

OwnerDisplayName: anon

LastEditorDisplayName: anon


问:
Round corners on a borderless NSWindow
I'm creating an application and I don't want a title bar:

If the title remains the same all the time, does it make sense to show it? For example, if an app doesn’t show the names of documents, or any other assets that it opens, and there is plenty of space at the top around other controls to grab onto if you want to move the window around, does the title serve much purpose?

The problem is: how do I do this? I tried using [mainWindow setStyleMask:NSBorderlessWindowMask]; but I can't make it have round corners. I really don't know how to make round corners. Next to that, I can't make it have a resize control. If I use [mainWindow setStyleMask:NSBorderlessWindowMask | NSResizableWindowMask]; it's not borderless anymore. Can anyone help me? Thanks.

答: If you want to do something completely different (like drawing your own window) check out Matt Gemmell's code.  Look at MAAttachedWindow code for ways of removing the title bar, drawing bezier corners, and making it look superb.</p>

Title: Round corners on a borderless NSWindow


问:
Zip a folder using SSIS
I am trying to zip a Folder in SSIS, there are 12 files in the source folder and I need to zipthat folder. I can get the files to zip fine my problem is the folders.

I have to use winzip to create the zipped packages.

Can anyone point me to a good tutorial. I haven't been able to implement any of the samples that I have found.

Thanks

答:
Try using 7zip it is free. Take a look at 7zip command line user guide  it contains all commands you need

And use a script task or an execute process task to achieve this. Also there are other useful links:

https://www.dotnetperls.com/7-zip-examples

UPDATE 1

you can follow this link for winzip:

http://www.vbforums.com/showthread.php?202918-Well-WinZip-Command-Line-Folders-to-Zip-keep-folder-structure-

In the link above they suggested using this command:

```<code> wzzip "c:\Test.zip" "c:\myfolder" -exPR
</code>```

Title: Zip a folder using SSIS

Body:
Try using 7zip it is free. Take a look at 7zip command line user guide  it contains all commands you need

And use a script task or an execute process task to achieve this. Also there are other useful links:

https://www.dotnetperls.com/7-zip-examples

UPDATE 1

you can follow this link for winzip:

http://www.vbforums.com/showthread.php?202918-Well-WinZip-Command-Line-Folders-to-Zip-keep-folder-structure-

In the link above they suggested using this command:

 wzzip "c:\Test.zip" "c:\myfolder" -exPR


问:
Why is my regular Expression that ignore the order of the characters does not work?
I want to make a string pattern that is:

at least 7 characters long

have at least 1 digits, max 5

have at least 3 capital alphabetic characters , max 5

have at least 1 lower alphabetic characters , max 5

have at least 1 special  characters , max 5

How to express this in a regular expression?
I can do something like

```<code>^((?=.*[A-Z]{3,5})(?=.*[a-z]{1,5})(?=.*[0-9]{1,5})(?=.*[.~!@#$%^_&-]{1,5}))(?=.{7,20}).*$
</code>```

I don't want to require this kind of order. In fact, any mixed order should be accepted, only require the number of characters.

This Match:

```<code>PASSW120P45ccb^&@%#
</code>```

But this one does not

```<code>PA12S1SW2045ccb^&@%#
</code>```

How can i fix this?

```<code>P&@Ass120W45ccb^%#
P&@Ass20W45cb^%#
</code>```

Please have a look at https://regex101.com/r/vF2yO7/51

答:
You need to operate with the contrary character classes, put these into non-capturing groups and repeat these:

```<code>^
(?=(?:\D*\d){1,5})
(?=(?:[^A-Z]*[A-Z]){3,5})
(?=(?:[^a-z]*[a-z]){1,5})
(?=(?:[^.\~!@#$%^_&-]*[.\~!@#$%^_&-]){1,5})
.{7,20}
$
</code>```

See a demo on regex101.com.

The structure here is always the same, e.g. with the numbers: require anything not a number zero or more times, followed by a number and repeat the whole pattern 1-5 times. In general:

```<code>(?=(?:not_what_you_want*what_you_want){min_times, max_times})
</code>```

In the expression above, all pos. lookaheads follow this scheme, [^...] negates the characters to be matched in the class and \D* is essentially the same as [^\d]*.

Body:
I want to make a string pattern that is:

at least 7 characters long

have at least 1 digits, max 5

have at least 3 capital alphabetic characters , max 5

have at least 1 lower alphabetic characters , max 5

have at least 1 special  characters , max 5

How to express this in a regular expression?
I can do something like

^((?=.*[A-Z]{3,5})(?=.*[a-z]{1,5})(?=.*[0-9]{1,5})(?=.*[.~!@#$%^_&-]{1,5}))(?=.{7,20}).*$

I don't want to require this kind of order. In fact, any mixed order should be accepted, only require the number of characters.

This Match:

PASSW120P45ccb^&@%#

But this one does not

PA12S1SW2045ccb^&@%#

How can i fix this?

P&@Ass120W45ccb^%#
P&@Ass20W45cb^%#

Please have a look at https://regex101.com/r/vF2yO7/51

Body:
You need to operate with the contrary character classes, put these into non-capturing groups and repeat these:

^
(?=(?:\D*\d){1,5})
(?=(?:[^A-Z]*[A-Z]){3,5})
(?=(?:[^a-z]*[a-z]){1,5})
(?=(?:[^.\~!@#$%^_&-]*[.\~!@#$%^_&-]){1,5})
.{7,20}
$

See a demo on regex101.com.

The structure here is always the same, e.g. with the numbers: require anything not a number zero or more times, followed by a number and repeat the whole pattern 1-5 times. In general:

(?=(?:not_what_you_want*what_you_want){min_times, max_times})

In the expression above, all pos. lookaheads follow this scheme, [^...] negates the characters to be matched in the class and \D* is essentially the same as [^\d]*.


问:
NodeJS & Socket.io: Chrome not loading with WebSockets
Chrome is loading with long polling, and the loading indicator doesn't stop.

Why is Chrome not using WebSockets, and how can I prevent the loading indicator from spinning when it does use long polling?

I'm using the latest socket.io and nodejs v2.5

--

The first time I connect, it uses Websocket, but disconnects right away and reconnects with xhr-polling.

答:
I'm using Chrome 8 and WebSockets appear to work fine.

If you're using socket.io, it should fall back to FlashSockets or even xhr-multipart before long polling (or forever iframe). Check your transport options when initialising socket.io on both the server and the client.