问:
Error in writing function in PostgreSQL
I've used this snippet code to create a function to export tables in JSON format in PostgreSQL. But the problem occurs when I wanted to use dynamic path for storing my output JSON file as the input argument of the function. When I replace the 'path' variable with something like 'c:\myfile.json' it doesn't have any error. What's wrong with path variable? Thanks.

```<code>CREATE OR REPLACE FUNCTION ST_Export2JSON(tableName TEXT, fields TEXT, path TEXT)
RETURNS VOID AS
$$
Copy(SELECT row_to_json(fc)
FROM ( SELECT 'FeatureCollection' As type, array_to_json(array_agg(f)) As     features
FROM ( SELECT 'Feature' As type, ST_AsGeoJSON(hp.geom)::json As geometry, row_to_json((select l from(select fields) as l)) As properties
FROM tableName As hp ) As f )  As fc) to path;
$$
LANGUAGE sql IMMUTABLE STRICT
</code>```

And this is the error:

```<code>ERROR:  syntax error at or near "path"
LINE 7:  FROM tableName As hp ) As f )  As fc) to path;
                                              ^
</code>```

答:
You should use plpgsql dynamic command, example:</p>

```<code>create or replace function example(path text)
returns void language plpgsql as $$
begin
    -- instead of
    -- copy (select 1) to path;
    -- use:
    execute format('copy (select 1) to %L', path);
end $$;
</code>```

Title: Error in writing function in PostgreSQL

Body:
I've used this snippet code to create a function to export tables in JSON format in PostgreSQL. But the problem occurs when I wanted to use dynamic path for storing my output JSON file as the input argument of the function. When I replace the 'path' variable with something like 'c:\myfile.json' it doesn't have any error. What's wrong with path variable? Thanks.

CREATE OR REPLACE FUNCTION ST_Export2JSON(tableName TEXT, fields TEXT, path TEXT)
RETURNS VOID AS
$$
Copy(SELECT row_to_json(fc)
FROM ( SELECT 'FeatureCollection' As type, array_to_json(array_agg(f)) As     features
FROM ( SELECT 'Feature' As type, ST_AsGeoJSON(hp.geom)::json As geometry, row_to_json((select l from(select fields) as l)) As properties
FROM tableName As hp ) As f )  As fc) to path;
$$
LANGUAGE sql IMMUTABLE STRICT

And this is the error:

ERROR:  syntax error at or near "path"
LINE 7:  FROM tableName As hp ) As f )  As fc) to path;
                                              ^

Body:
You should use plpgsql dynamic command, example:

create or replace function example(path text)
returns void language plpgsql as $$
begin
    -- instead of
    -- copy (select 1) to path;
    -- use:
    execute format('copy (select 1) to %L', path);
end $$;


来源: stackexchange

问:
Does Intercom works with AngularJS and Ionic apps?
I was wondering if I could integrate my Intercom messaging to my hybrid app. I was searching around the web, but didn't find something to answer my question, therefor I'm writing this.

So, does anyone know if it's possible? If so, how did you guys do it?

Cheers!

答:
Yes you can integrate Intercom messaging in your ionic app using plugin cordova intercom plugin

```<code>cordova plugin add cordova-plugin-intercom
</code>```

In you config file add:

```<code><preference name="intercom-app-id" value="your-app-id" />
<preference name="intercom-ios-api-key" value="ios_sdk-....." />
<preference name="intercom-android-api-key" value="android_sdk-..." />
</code>```

In your index file

```<code><script>intercom.displayMessenger();</script>
</code>```

In your controller after login:

```<code>document.addEventListener("deviceready", function() {
      intercom.registerIdentifiedUser({userId: response.id});
      intercom.updateUser({ email: response.email, name: response.name });

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

ContentLicense: CC BY-SA 3.0

Body:
Yes you can integrate Intercom messaging in your ionic app using plugin cordova intercom plugin

cordova plugin add cordova-plugin-intercom

In you config file add:

<preference name="intercom-app-id" value="your-app-id" />
<preference name="intercom-ios-api-key" value="ios_sdk-....." />
<preference name="intercom-android-api-key" value="android_sdk-..." />

In your index file

<script>intercom.displayMessenger();</script>

In your controller after login:

document.addEventListener("deviceready", function() {
      intercom.registerIdentifiedUser({userId: response.id});
      intercom.updateUser({ email: response.email, name: response.name });

     }, false);


问:
How inject service in AutoMapper profile class
I need to use a service layer in the AutoMapper profile class in ASP.NET Core but when I inject service in the constructor it does not work. For example:

```<code>public class UserProfile : Profile
{
    private readonly IUserManager _userManager;

    public UserProfile(IUserManager userManager)
    {
        _userManager = userManager;

        CreateMap<User, UserViewModel>()
           .ForMember(dest => dest.FullName, opt => opt.MapFrom(src => $"{src.FirstName} {src.LastName}"));
    }
}
</code>```

And in Startup Class:

```<code> public class Startup
{
    public IConfigurationRoot Configuration { set; get; }

    public Startup(IHostingEnvironment env)
    {
       //some code
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
        services.AddMvc();
        services.AddScoped<IUsersPhotoService, UsersPhotoService>();
        services.AddAutoMapper(typeof(UserProfile));
    }
}
</code>```

How do to do it?

答:
To solve your problem you just need to wire IUserManager in DI, and make sure UserProfile dependency is resolved.

```<code>public void ConfigureServices(IServiceCollection services)
{
    // ...
    services.AddSingleton<IUserManager, UserManager>();
    services.AddSingleton(provider => new MapperConfiguration(cfg =>
    {
        cfg.AddProfile(new UserProfile(provider.GetService<IUserManager>()));
    }).CreateMapper());
}
</code>```

And having that said, I would probably try to keep single responsibility per class, and not have any services injected into mapping profiles. You can populate your objects just before the mapping instead. This way it might be easier to unit test as well.

Body:
I need to use a service layer in the AutoMapper profile class in ASP.NET Core but when I inject service in the constructor it does not work. For example:

public class UserProfile : Profile
{
    private readonly IUserManager _userManager;

    public UserProfile(IUserManager userManager)
    {
        _userManager = userManager;

        CreateMap<User, UserViewModel>()
           .ForMember(dest => dest.FullName, opt => opt.MapFrom(src => $"{src.FirstName} {src.LastName}"));
    }
}

And in Startup Class:

 public class Startup
{
    public IConfigurationRoot Configuration { set; get; }

    public Startup(IHostingEnvironment env)
    {
       //some code
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
        services.AddMvc();
        services.AddScoped<IUsersPhotoService, UsersPhotoService>();
        services.AddAutoMapper(typeof(UserProfile));
    }
}

How do to do it?

Body:
To solve your problem you just need to wire IUserManager in DI, and make sure UserProfile dependency is resolved.

public void ConfigureServices(IServiceCollection services)
{
    // ...
    services.AddSingleton<IUserManager, UserManager>();
    services.AddSingleton(provider => new MapperConfiguration(cfg =>
    {
        cfg.AddProfile(new UserProfile(provider.GetService<IUserManager>()));
    }).CreateMapper());
}

And having that said, I would probably try to keep single responsibility per class, and not have any services injected into mapping profiles. You can populate your objects just before the mapping instead. This way it might be easier to unit test as well.


问:
How to select from whereIn clause using Laravel Eloquent ORM or Query Builder?
I'd like to get value by the following MySQL using Eloquent ORM.

MySQL Query -

```<code>SELECT * FROM `users` WHERE `is_super_admin` = 1 OR `is_partner` = 1
OR `is_admin` = 1 OR `id` IN
(select `user_id` from `site_userrole_mapper` where `is_site_owner` = 1)
</code>```

Laravel Query (It's not working) -

```<code>Users::Where('is_super_admin', '=', 1)
        ->orWhere('is_partner', '=', 1)
        ->orWhere('is_admin', '=', 1)
        ->orWhereIn('id', [
            DB::table('site_userrole_mapper')
            ->select('user_id')
            ->where('is_site_owner', '=', 1)
            ->get()
            //Here get() returns an object and we're not able compare it with id
        ])
        ->get();
</code>```

I just want to convert above MySQL query in Eloquent ORM. Thanks for your help.

答:
you can try this</p>

```<code>Users::Where('is_super_admin', '=', 1)
    ->orWhere('is_partner', '=', 1)
    ->orWhere('is_admin', '=', 1)
    ->orWhereIn('id',
        DB::table('site_userrole_mapper')
        ->where('is_site_owner', '=', 1)
        ->pluck('user_id')
        //Here get return an object and we're not able compare it with id
    )
    ->get();
</code>```

Body:
I'd like to get value by the following MySQL using Eloquent ORM.

MySQL Query -

SELECT * FROM `users` WHERE `is_super_admin` = 1 OR `is_partner` = 1
OR `is_admin` = 1 OR `id` IN
(select `user_id` from `site_userrole_mapper` where `is_site_owner` = 1)

Laravel Query (It's not working) -

Users::Where('is_super_admin', '=', 1)
        ->orWhere('is_partner', '=', 1)
        ->orWhere('is_admin', '=', 1)
        ->orWhereIn('id', [
            DB::table('site_userrole_mapper')
            ->select('user_id')
            ->where('is_site_owner', '=', 1)
            ->get()
            //Here get() returns an object and we're not able compare it with id
        ])
        ->get();

I just want to convert above MySQL query in Eloquent ORM. Thanks for your help.

Body:
you can try this

Users::Where('is_super_admin', '=', 1)
    ->orWhere('is_partner', '=', 1)
    ->orWhere('is_admin', '=', 1)
    ->orWhereIn('id',
        DB::table('site_userrole_mapper')
        ->where('is_site_owner', '=', 1)
        ->pluck('user_id')
        //Here get return an object and we're not able compare it with id
    )
    ->get();


问:
Replacing DIV content based on variable sent from another HTML file
I'm trying to get this JavaScript working:

I have an HTML email which links to this page which contains a variable in the link (index.html?content=email1). The JavaScript should replace the DIV content depending on what the variable for 'content' is.

```<code><!-- ORIGINAL DIV -->
<div id="Email">

</div>

<!-- DIV replacement function -->

<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
</script>

<!-- Email 1 Content -->
<script ="text/javascript">
var content = '<div class="test">Email 1 content</div>';

ReplaceContentInContainer('Email1',content);
}
</script>

<!-- Email 2 Content -->
<script ="text/javascript">
var content = '<div class="test">Email 2 content</div>';

ReplaceContentInContainer('Email2',content);
}
</script>
</code>```

Any ideas what I've done wrong that is causing it not to work?

答:
First of all, parse the query string data to find the desired content to show. To achieve this, add this function to your page:

```<code><script type="text/javascript">
function ParseQueryString() {
    var result = new Array();
    var strQS = window.location.href;
    var index = strQS.indexOf("?");
    if (index > 0) {
        var temp = strQS.split("?");
        var arrData = temp[1].split("&");
        for (var i = 0; i < arrData.length; i++) {
            temp = arrData[i].split("=");
            var key = temp[0];
            var value = temp.length > 0 ? temp[1] : "";
            result[key] = value;
        }
    }
    return result;
}
</script>
</code>```

Second step, have all possible DIV elements in the page, initially hidden using display: none; CSS, like this:

```<code><div id="Email1" style="display: none;">Email 1 Content</div>
<div id="Email2" style="display: none;">Email 2 Content</div>
...
</code>```

Third and final step, in the page load (after all DIV elements are loaded including the placeholder) read the query string, and if content is given, put the contents of the desired DIV into the "main" div.. here is the required code:

```<code>window.onload = function WindowLoad() {
    var QS = ParseQueryString();
    var contentId = QS["content"];
    if (contentId) {
        var source = document.getElementById(contentId);
        if (source) {
            var target = document.getElementById("Email");
            target.innerHTML = source.innerHTML;
        }
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to get this JavaScript working:

I have an HTML email which links to this page which contains a variable in the link (index.html?content=email1). The JavaScript should replace the DIV content depending on what the variable for 'content' is.

Any ideas what I've done wrong that is causing it not to work?

Body:
First of all, parse the query string data to find the desired content to show. To achieve this, add this function to your page:

<script type="text/javascript">
function ParseQueryString() {
    var result = new Array();
    var strQS = window.location.href;
    var index = strQS.indexOf("?");
    if (index > 0) {
        var temp = strQS.split("?");
        var arrData = temp[1].split("&");
        for (var i = 0; i < arrData.length; i++) {
            temp = arrData[i].split("=");
            var key = temp[0];
            var value = temp.length > 0 ? temp[1] : "";
            result[key] = value;
        }
    }
    return result;
}
</script>

Second step, have all possible DIV elements in the page, initially hidden using display: none; CSS, like this:

<div id="Email1" style="display: none;">Email 1 Content</div>
<div id="Email2" style="display: none;">Email 2 Content</div>
...

Third and final step, in the page load (after all DIV elements are loaded including the placeholder) read the query string, and if content is given, put the contents of the desired DIV into the "main" div.. here is the required code:

window.onload = function WindowLoad() {
    var QS = ParseQueryString();
    var contentId = QS["content"];
    if (contentId) {
        var source = document.getElementById(contentId);
        if (source) {
            var target = document.getElementById("Email");
            target.innerHTML = source.innerHTML;
        }
    }
}


问:
How to retrieve last inserted keys without using statements or "LAST_INSERTED_ID"
I'm looking for a way how to retrieve last generated keys/ids from insert performed via "createNativeQuery" in similar way like "getGeneratedKeys" in PreparedStatement.

As I wrote in first paragraph, I know there is a possibility to use PreparedStatement which actually works and we are using it for some different cases.
Also I know that I can do direct select into database and call "LAST_INSERT_ID" or "@@Identity" which also works, but that's a way I want to avoid. For now I've been using inserting rows into DB and then I was calling simple "LAST_INSERT_ID()" and retrieve the id.

I want to avoid this because it works until I started to testing ProxySQL, which, I guess, do some stuff with connections/sessions and when I call LAST_INSERT I will just get zero value (but when I try the same with Prepared statements and getGeneratedKeys, it works)

There are dozens of similar stack topics like this, but I didn't find a single answer.

I've been playing around with getResultList and getLastResult Query methods, but nothing leads to a success way how to retrieve last generated ids.

答:
Using JPA the ID is generated at flush time only. So if you need the ID call flush() to get the ID:</p>

```<code>Entity en = new Entity();
en.setName("My Entity name");
em.persist(en);
em.flush();
System.out.println(en.getId());
</code>```

Body:
Using JPA the ID is generated at flush time only. So if you need the ID call flush() to get the ID:

Entity en = new Entity();
en.setName("My Entity name");
em.persist(en);
em.flush();
System.out.println(en.getId());


问:
Rails: Password can't be blank with has_secure_password
I am trying to follow this tutorial (Rails Tutorial by Michael Hartl) to create a valid user. Filling in the password fields still gives me the error "Password cannot be blank" and "Password has to be longer thank 6 letters". I tried creating a user through the rails console, and that worked fine. It is only when I try doing it through the website itself.

My user model looks like this:

```<code>class User < ApplicationRecord
  #before saving, make sure the email is in downcase
  before_save { self.email = email.downcase }

  validates :name,  presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence: true, length: { maximum: 255 },
                format: { with: VALID_EMAIL_REGEX },
                uniqueness: {case_sensitive: false}

  has_secure_password
  validates :password, presence: true, length: { minimum: 6 }
end
</code>```

My user_controller looks like this:

```<code>class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
#wrap_parameters :user, include: [:name, :email, :password, :password_confirmation]

def index
  @users = User.all
end

def show
  @user = User.find(params[:id])
  #debugger
end
def new
  @user = User.new
end

# GET /users/1/edit
def edit
end

#POST /users
#POST /users.json
def create
  @user = User.new(user_params) #params[:user])#user_params)

  respond_to do |format|
    if @user.save
      #flash[:success] = "Welcome to CourseBuddies!"

      format.html { redirect_to @user, notice: 'User was successfully created.' }
      format.json { render :show, status: :created, location: @user }
      redirect_to @user
    else
      #render 'new'
      format.html { render :new }
      format.json { render json: @user.errors, status: :unprocessable_entity }
    end
  end
end

# PATCH/PUT /users/1
# PATCH/PUT /users/1.json
def update
  respond_to do |format|
    if @user.update(user_params)
      format.html { redirect_to @user, notice: 'User was successfully updated.' }
      format.json { render :show, status: :ok, location: @user }
    else
      format.html { render :edit }
      format.json { render json: @user.errors, status: :unprocessable_entity }
    end
  end
end

# DELETE /users/1
# DELETE /users/1.json
def destroy
  @user.destroy
  respond_to do |format|
    format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
    format.json { head :no_content }
  end
end

private
  # Use callbacks to share common setup or constraints between actions.
  def set_user
    @user = User.find(params[:id])
  end

  # Never trust parameters from the scary internet, only allow the white list through.
  def user_params
    params.require(:user).permit(:name, :email, :pasword, :password_confirmation)
  end
end
</code>```

This is my Migration file create_user:

```<code>class CreateUsers < ActiveRecord::Migration[5.0]
 def change
   create_table :users do |t|
     t.string :name
     t.string :email
     t.string :password
     t.string :password_confirmation

     t.timestamps
   end
 end
</code>```

end

I've tried different solutions found online like using "wrap_parameters" and such it doesn't seem to do anything for me.

My Gemfile looks like this:

```<code># Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.0.1'
gem 'bootstrap-sass', '3.3.7'
# make pw digest "has_secure_password" use a stateofart hash function (bcrypt)
gem 'bcrypt', '3.1.11'
# Use postgresql as the database for Active Record
gem 'pg', '~> 0.18.4'
# Use Puma as the app server
gem 'puma', '~> 3.0'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes navigating your web application faster. Read more:     https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  gem 'sqlite3', '1.3.13' #railsTuto said to get this, but already use postgresql
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platform: :mri
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '~> 3.0.5'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

group :test do
  gem 'rails-controller-testing', '1.0.2'
  gem 'minitest-reporters',       '1.1.14'
  gem 'guard',                    '2.13.0'
  gem 'guard-minitest',           '2.4.4'
end

group :production do
  gem 'pg', '~>0.18.4'
  gem 'rails_12factor'
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
</code>```

EDIT: My FORM

```<code><%- #FIELDS FOR THE FORM %>
<div class="row">
  <div class="col-md-6 col-md-offset-3">
    <%= form_for(@user, url: signup_path) do |f| %>

    <%- #ERROR MESSAGES %>
    <%= render 'shared/error_messages' %>

    <%= f.label :name %>
    <%= f.text_field :name, class: 'form-control' %>

    <br>
    <%= f.label :email %>
    <%= f.email_field :email, class: 'form-control' %>

    <br>
    <%= f.label :password %>
    <%= f.password_field :password, class: 'form-control' %>

    <br>
    <%= f.label :password_confirmation, "Confirmation" %>
    <%= f.password_field :password_confirmation, class: 'form-control' %>

    <br><br>
    <%= f.submit "Create my account", class: "btn btn-primary" %>
  <% end %>
</div>
</code>```

I would appreciate any kind of help or clarification. Thanks!

答:
SOLUTION:

Okey, so after fixing my typo in my controller (pointed out by @Pavan), and also I removed the presence:true in my user model (@Divya Sharma), so it would look something like this:

```<code>validates :password, length: { minimum: 6 }, allow_nil: true
</code>```

I can now properly sign up my user and login!

I think putting "allow_nil:true" actually just let me sign up because somehow, my password_fields was still "nil". I guess that was because of my typo's fault. Anyway, thanks guys for being so fast!

Body:
I am trying to follow this tutorial (Rails Tutorial by Michael Hartl) to create a valid user. Filling in the password fields still gives me the error "Password cannot be blank" and "Password has to be longer thank 6 letters". I tried creating a user through the rails console, and that worked fine. It is only when I try doing it through the website itself.

My user model looks like this:

class User < ApplicationRecord
  #before saving, make sure the email is in downcase
  before_save { self.email = email.downcase }

  validates :name,  presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence: true, length: { maximum: 255 },
                format: { with: VALID_EMAIL_REGEX },
                uniqueness: {case_sensitive: false}

  has_secure_password
  validates :password, presence: true, length: { minimum: 6 }
end

My user_controller looks like this:

class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
#wrap_parameters :user, include: [:name, :email, :password, :password_confirmation]

def index
  @users = User.all
end

def show
  @user = User.find(params[:id])
  #debugger
end
def new
  @user = User.new
end

# GET /users/1/edit
def edit
end

#POST /users
#POST /users.json
def create
  @user = User.new(user_params) #params[:user])#user_params)

  respond_to do |format|
    if @user.save
      #flash[:success] = "Welcome to CourseBuddies!"

      format.html { redirect_to @user, notice: 'User was successfully created.' }
      format.json { render :show, status: :created, location: @user }
      redirect_to @user
    else
      #render 'new'
      format.html { render :new }
      format.json { render json: @user.errors, status: :unprocessable_entity }
    end
  end
end

# PATCH/PUT /users/1
# PATCH/PUT /users/1.json
def update
  respond_to do |format|
    if @user.update(user_params)
      format.html { redirect_to @user, notice: 'User was successfully updated.' }
      format.json { render :show, status: :ok, location: @user }
    else
      format.html { render :edit }
      format.json { render json: @user.errors, status: :unprocessable_entity }
    end
  end
end

# DELETE /users/1
# DELETE /users/1.json
def destroy
  @user.destroy
  respond_to do |format|
    format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
    format.json { head :no_content }
  end
end

private
  # Use callbacks to share common setup or constraints between actions.
  def set_user
    @user = User.find(params[:id])
  end

  # Never trust parameters from the scary internet, only allow the white list through.
  def user_params
    params.require(:user).permit(:name, :email, :pasword, :password_confirmation)
  end
end

This is my Migration file create_user:

class CreateUsers < ActiveRecord::Migration[5.0]
 def change
   create_table :users do |t|
     t.string :name
     t.string :email
     t.string :password
     t.string :password_confirmation

     t.timestamps
   end
 end

end

I've tried different solutions found online like using "wrap_parameters" and such it doesn't seem to do anything for me.

My Gemfile looks like this:

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.0.1'
gem 'bootstrap-sass', '3.3.7'
# make pw digest "has_secure_password" use a stateofart hash function (bcrypt)
gem 'bcrypt', '3.1.11'
# Use postgresql as the database for Active Record
gem 'pg', '~> 0.18.4'
# Use Puma as the app server
gem 'puma', '~> 3.0'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes navigating your web application faster. Read more:     https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  gem 'sqlite3', '1.3.13' #railsTuto said to get this, but already use postgresql
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platform: :mri
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '~> 3.0.5'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

group :test do
  gem 'rails-controller-testing', '1.0.2'
  gem 'minitest-reporters',       '1.1.14'
  gem 'guard',                    '2.13.0'
  gem 'guard-minitest',           '2.4.4'
end

group :production do
  gem 'pg', '~>0.18.4'
  gem 'rails_12factor'
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

EDIT: My FORM

<%- #FIELDS FOR THE FORM %>

    <%= form_for(@user, url: signup_path) do |f| %>

    <%- #ERROR MESSAGES %>
    <%= render 'shared/error_messages' %>

    <%= f.label :name %>
    <%= f.text_field :name, class: 'form-control' %>

    <%= f.label :email %>
    <%= f.email_field :email, class: 'form-control' %>

    <%= f.label :password %>
    <%= f.password_field :password, class: 'form-control' %>

    <%= f.label :password_confirmation, "Confirmation" %>
    <%= f.password_field :password_confirmation, class: 'form-control' %>

    <%= f.submit "Create my account", class: "btn btn-primary" %>
  <% end %>

I would appreciate any kind of help or clarification. Thanks!

Body:
SOLUTION:

Okey, so after fixing my typo in my controller (pointed out by @Pavan), and also I removed the presence:true in my user model (@Divya Sharma), so it would look something like this:

validates :password, length: { minimum: 6 }, allow_nil: true

I can now properly sign up my user and login!

I think putting "allow_nil:true" actually just let me sign up because somehow, my password_fields was still "nil". I guess that was because of my typo's fault. Anyway, thanks guys for being so fast!


问:
Angular2 Tutorial (Tour of Heroes): Cannot find module 'angular2-in-memory-web-api'
I have followed the Tutorial. After changing app/maint.ts in the Http chapter I get the error when starting the app via command line:

app/main.ts(5,51): error TS2307: Cannot find module 'angular2-in-memory-web-api'.

(Visual Studio Code gives me the same error within main.ts - red wavy underlining.)

Here is my systemjs.config.js:

```<code>/**
 * System configuration for Angular 2 samples
 * Adjust as necessary for your application needs.
 */
(function(global) {
  // map tells the System loader where to look for things
  var map = {
    'app':                        'app', // 'dist',
    '@angular':                   'node_modules/@angular',
    'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
    'rxjs':                       'node_modules/rxjs'
  };
  // packages tells the System loader how to load when no filename and/or no extension
  var packages = {
    'app':                        { main: 'main.js',  defaultExtension: 'js' },
    'rxjs':                       { defaultExtension: 'js' },
    'angular2-in-memory-web-api': { defaultExtension: 'js' },
  };
  var ngPackageNames = [
    'common',
    'compiler',
    'core',
    'http',
    'platform-browser',
    'platform-browser-dynamic',
    'router',
    'router-deprecated',
    'upgrade',
  ];
  // Add package entries for angular packages
  ngPackageNames.forEach(function(pkgName) {
    packages['@angular/'+pkgName] = { main: pkgName + '.umd.js', defaultExtension: 'js' };
  });
  var config = {
    map: map,
    packages: packages
  }
  System.config(config);
})(this);
</code>```

Here is my app/main.ts:

```<code>// Imports for loading & configuring the in-memory web api
import { provide }    from '@angular/core';
import { XHRBackend } from '@angular/http';

import { InMemoryBackendService, SEED_DATA } from 'angular2-in-memory-web-api';
import { InMemoryDataService }               from './in-memory-data.service';

// The usual bootstrapping imports
import { bootstrap }      from '@angular/platform-browser-dynamic';
import { HTTP_PROVIDERS } from '@angular/http';

import { AppComponent }   from './app.component';

bootstrap(AppComponent, [
    HTTP_PROVIDERS,
    provide(XHRBackend, { useClass: InMemoryBackendService }), // in-mem server
    provide(SEED_DATA,  { useClass: InMemoryDataService })     // in-mem server data
]);
</code>```

答:
For me just doing an install from angular-tour-of-heroes directory works for me

C:\nodejs\angular-tour-of-heroes>npm install angular-in-memory-web-api --save

Body:
I have followed the Tutorial. After changing app/maint.ts in the Http chapter I get the error when starting the app via command line:

app/main.ts(5,51): error TS2307: Cannot find module 'angular2-in-memory-web-api'.

(Visual Studio Code gives me the same error within main.ts - red wavy underlining.)

Here is my systemjs.config.js:

/**
 * System configuration for Angular 2 samples
 * Adjust as necessary for your application needs.
 */
(function(global) {
  // map tells the System loader where to look for things
  var map = {
    'app':                        'app', // 'dist',
    '@angular':                   'node_modules/@angular',
    'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
    'rxjs':                       'node_modules/rxjs'
  };
  // packages tells the System loader how to load when no filename and/or no extension
  var packages = {
    'app':                        { main: 'main.js',  defaultExtension: 'js' },
    'rxjs':                       { defaultExtension: 'js' },
    'angular2-in-memory-web-api': { defaultExtension: 'js' },
  };
  var ngPackageNames = [
    'common',
    'compiler',
    'core',
    'http',
    'platform-browser',
    'platform-browser-dynamic',
    'router',
    'router-deprecated',
    'upgrade',
  ];
  // Add package entries for angular packages
  ngPackageNames.forEach(function(pkgName) {
    packages['@angular/'+pkgName] = { main: pkgName + '.umd.js', defaultExtension: 'js' };
  });
  var config = {
    map: map,
    packages: packages
  }
  System.config(config);
})(this);

Here is my app/main.ts:

// Imports for loading & configuring the in-memory web api
import { provide }    from '@angular/core';
import { XHRBackend } from '@angular/http';

import { InMemoryBackendService, SEED_DATA } from 'angular2-in-memory-web-api';
import { InMemoryDataService }               from './in-memory-data.service';

// The usual bootstrapping imports
import { bootstrap }      from '@angular/platform-browser-dynamic';
import { HTTP_PROVIDERS } from '@angular/http';

import { AppComponent }   from './app.component';

bootstrap(AppComponent, [
    HTTP_PROVIDERS,
    provide(XHRBackend, { useClass: InMemoryBackendService }), // in-mem server
    provide(SEED_DATA,  { useClass: InMemoryDataService })     // in-mem server data
]);


问:
Google map initialization
i'm using google maps in my app
i can initialize google maps but i have noticed that the initalize map function is executed twice

Code

```<code>    <script src="https://maps.googleapis.com/maps/api/js?key=XXXXXXXXX&libraries=drawing&callback=InitializeMap&language=ar"></script>

    <script>
        $(document).ready(function () {

            var Lan = getParameterByName('Lat');// get lat from Querystring
            var Long = getParameterByName('Lng');
            InitializeMap(Lan, Long);

        }); function InitializeMap(Lat, Long) {
            alert('Start');
}
</code>```

the alert shows twice
is that normal
what i'm doing wrong

答:
This is executed twice because you have initialized twice once in url "callback" and the other one in script. I have removed the Initialized Map function in callback, now it will trigger only once</p>

```<code><script src="https://maps.googleapis.com/maps/api/js?key=XXXXXXXXX&libraries=drawing&language=ar"></script>

    <script>
        $(document).ready(function () {

            var Lan = getParameterByName('Lat');// get lat from Querystring
            var Long = getParameterByName('Lng');
            InitializeMap(Lan, Long);

        }); function InitializeMap(Lat, Long) {
            alert('Start');
}
</code>```

Title: Google map initialization

Body:
This is executed twice because you have initialized twice once in url "callback" and the other one in script. I have removed the Initialized Map function in callback, now it will trigger only once

<script src="https://maps.googleapis.com/maps/api/js?key=XXXXXXXXX&libraries=drawing&language=ar"></script>

    <script>
        $(document).ready(function () {

            var Lan = getParameterByName('Lat');// get lat from Querystring
            var Long = getParameterByName('Lng');
            InitializeMap(Lan, Long);

        }); function InitializeMap(Lat, Long) {
            alert('Start');
}


问:
Fatal:Call to a member function query() on null
I am new to programming in PHP and I'm making a PHP class that receives queries but when summoned gives me the error "PHP Fatal error: Call to a member function query () on null". when inserting the data.

```<code>class users {

    public $host = "localhost";
    public $username = "root";
    public $password = "root1234";
    public $db_name = "boot_quiz_oops";
    public $conn;

    public function _construct() {

        $this->conn = new mysqli($this->host, $this->username, $this->password, $this->db_name);
        if ($this->conn->connect_errno) {
            die("database connection failed" . ($this->conn->connect_errno));
        }
    }

    public function signup($data)
    {
         $this->conn->query($data);
         return true;
    }
</code>```

this is my second file

```<code><?php
include("class/users.php");
$register = new users;
extract($_POST);

$img_name = $_FILES['img']['name'];
$tmp_name = $_FILES['img']['tmp_name'];
move_uploaded_file($tmp_name, "img/".$img_name);
$query = "insert into signup values ('','$n','$e','$p','$img_name') ";

if($register->signup($query))
{
    $register->url("index.php?run=success");
}
?>
</code>```

this is my index.php file

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Quiz</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<br>
    <div class="container">
        <div class="row">
<br>
            <div class="col-sm-12">
                <div class="panel panel-primary">
                    <div class="panel-heading">Online Quiz Portal</div>
                    <div class="panel-body">Quiz in php</div>
                </div>
            </div>
        </div>
    </div>
    <div class="container">
        <div class="row">
            <div class="col-sm-6">
                <div class="panel panel-info">
                    <div class="panel-heading"><h4>Login Form</h4></div>
                    <div class="panel-body">
                      <?php
                        if(isset($_GET['run']) && $_GET['run']=="failed")
                        {
                            echo "Your email and password does not match";
                        }
                      ?>
                        <form role="form" action="signin_sub.php" method="post" >
                            <div class="form-group">
                                <label for="email">Email:</label>
                                <input type="email" class="form-control" name="e" id="email" placeholder="Enter email">
                            </div>
                            <div class="form-group">
                                <label for="pwd">Password:</label>
                                <input type="password" class="form-control" name="p" id="pwd" placeholder="Enter password">
                            </div>
                            <button type="submit" class="btn btn-default">Submit</button>
                        </form>
                    </div>
                </div>
            </div>
            <div class="col-sm-6">
                <div class="panel panel-info">
                    <div class="panel-heading"><h4>Signup Form</h4></div>
                    <div class="panel-body">
                        <?php
                          if (isset($_GET['run']) && $_GET['run']=="success"){
                              echo "Your resgistration successfully done";
                          }
                        ?>
                        <form role="form" action="signup_sub.php" method="post" enctype="multipart/form-data">
                            <div class="form-group">
                                <label for="name">Name:</label>
                                <input type="text" class="form-control" name="n" id="name" placeholder="Enter name">
                            </div>
                            <div class="form-group">
                                <label for="email">Email:</label>
                                <input type="email" class="form-control" name="e" id="email" placeholder="Enter email">
                            </div>
                            <div class="form-group">
                                <label for="pwd">Password:</label>
                                <input type="password" class="form-control" name="p" id="pwd" placeholder="Enter password">
                            </div>
                            <div class="form-group">
                                <label for="imgage">Upload your image:</label>
                                <input type="file" class="form-control" name="img" id="file">
                            </div>
                            <button type="submit" class="btn btn-default">Submit</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
</code>```

答:
Your contructor have wrong name:

You have _construct, but should have __construct - with double underscore.

user.php

Need to change

```<code>public function __construct() {

    $this->conn = new mysqli($this->host, $this->username, $this->password, $this->db_name);
    if ($this->conn->connect_errno) {
        die("database connection failed" . ($this->conn->connect_errno));
    }
}
</code>```

Body:
I am new to programming in PHP and I'm making a PHP class that receives queries but when summoned gives me the error "PHP Fatal error: Call to a member function query () on null". when inserting the data.

class users {

    public $host = "localhost";
    public $username = "root";
    public $password = "root1234";
    public $db_name = "boot_quiz_oops";
    public $conn;

    public function _construct() {

        $this->conn = new mysqli($this->host, $this->username, $this->password, $this->db_name);
        if ($this->conn->connect_errno) {
            die("database connection failed" . ($this->conn->connect_errno));
        }
    }

    public function signup($data)
    {
         $this->conn->query($data);
         return true;
    }

this is my second file

<?php
include("class/users.php");
$register = new users;
extract($_POST);

$img_name = $_FILES['img']['name'];
$tmp_name = $_FILES['img']['tmp_name'];
move_uploaded_file($tmp_name, "img/".$img_name);
$query = "insert into signup values ('','$n','$e','$p','$img_name') ";

if($register->signup($query))
{
    $register->url("index.php?run=success");
}
?>

this is my index.php file

<!DOCTYPE html>

  <title>Bootstrap Quiz</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Online Quiz Portal

Quiz in php

Login Form

                      <?php
                        if(isset($_GET['run']) && $_GET['run']=="failed")
                        {
                            echo "Your email and password does not match";
                        }
                      ?>
                        <form role="form" action="signin_sub.php" method="post" >

                                Email:
                                <input type="email" class="form-control" name="e" id="email" placeholder="Enter email">

                                Password:
                                <input type="password" class="form-control" name="p" id="pwd" placeholder="Enter password">

                            <button type="submit" class="btn btn-default">Submit</button>
                        </form>

Signup Form

                        <?php
                          if (isset($_GET['run']) && $_GET['run']=="success"){
                              echo "Your resgistration successfully done";
                          }
                        ?>
                        <form role="form" action="signup_sub.php" method="post" enctype="multipart/form-data">

                                Name:
                                <input type="text" class="form-control" name="n" id="name" placeholder="Enter name">

                                Email:
                                <input type="email" class="form-control" name="e" id="email" placeholder="Enter email">

                                Password:
                                <input type="password" class="form-control" name="p" id="pwd" placeholder="Enter password">

                                Upload your image:
                                <input type="file" class="form-control" name="img" id="file">

                            <button type="submit" class="btn btn-default">Submit</button>
                        </form>

Body:
Your contructor have wrong name:

You have _construct, but should have __construct - with double underscore.

user.php

Need to change

public function __construct() {

    $this->conn = new mysqli($this->host, $this->username, $this->password, $this->db_name);
    if ($this->conn->connect_errno) {
        die("database connection failed" . ($this->conn->connect_errno));
    }
}


问:
Connection String in Azure while using Spring Boot
I can see that we can define a secure connection string form portal, and than can access those variables in our application.I found many examples to do it in ASP.NET, like defining the keys in web.config. But i can not find any example focusing on accessing these connection strings defined via portal from Spring Boot app.
Any help in that direction would be useful</p>

答:
See this article from Stefan: How Application Strings and Connection Strings Work in Azure App Service

Azure app service exposes them in the form of environment variables at runtime to the web app. There is a naming convention in place which makes it easier to retrieve them.

For app settings the name of the corresponding environment variable is prepended with APPSETTING_. For connection strings, it depends on the type of DB that has been configured. See below

For SQL Azure it is SQLAZURECONNSTR_

For SQL Database hosted on Azure VM it is SQLCONNSTR_

For MySQL database it is MYSQLCONNSTR_

For any other type of databases it is CUSTOMCONNSTR_

In Java, you can use the System.getenv() function to retrieve the environment variables. Refer the document on how to use this: public static String getenv(String name)

You can pass the environment variable to this function to get it working. For example

```<code>String envStr = System.getenv("APPSETTING_TestSetting");
</code>```

Body:
See this article from Stefan: How Application Strings and Connection Strings Work in Azure App Service

Azure app service exposes them in the form of environment variables at runtime to the web app. There is a naming convention in place which makes it easier to retrieve them.

For app settings the name of the corresponding environment variable is prepended with APPSETTING_. For connection strings, it depends on the type of DB that has been configured. See below

For SQL Azure it is SQLAZURECONNSTR_

For SQL Database hosted on Azure VM it is SQLCONNSTR_

For MySQL database it is MYSQLCONNSTR_

For any other type of databases it is CUSTOMCONNSTR_

In Java, you can use the System.getenv() function to retrieve the environment variables. Refer the document on how to use this: public static String getenv(String name)

You can pass the environment variable to this function to get it working. For example

String envStr = System.getenv("APPSETTING_TestSetting");


问:
How to Append two different hash map on a particular node without replacing other in Firebase?
I want to append two different hash map pairs on a particular node one with key value both being String and other String and Array List. But problem is Later one is replacing first one in Fire base database. what should i do? I cant use push() all the time.Link of my code. Please help  </p>

答:
Just use 1 Map<String, Object> instead of 2 different ones.
then you put all the data in that single map, string, arraylist


问:
How to extract best parameters from a CrossValidatorModel
I want to find the parameters of ParamGridBuilder that make the best model in CrossValidator in Spark 1.4.x,

In Pipeline Example in Spark documentation, they add different parameters (numFeatures, regParam) by using ParamGridBuilder in the Pipeline. Then by the following line of code they make the best model:

```<code>val cvModel = crossval.fit(training.toDF)
</code>```

Now, I want to know what are the parameters (numFeatures, regParam) from ParamGridBuilder that produces the best model.

I already used the following commands without success:

```<code>cvModel.bestModel.extractParamMap().toString()
cvModel.params.toList.mkString("(", ",", ")")
cvModel.estimatorParamMaps.toString()
cvModel.explainParams()
cvModel.getEstimatorParamMaps.mkString("(", ",", ")")
cvModel.toString()
</code>```

Any help?

Thanks in advance,

答:
this java code should work:
cvModel.bestModel().parent().extractParamMap().you can translate it to scala code
parent()method will return an estimator, you can get the best params then.

Body:
I want to find the parameters of ParamGridBuilder that make the best model in CrossValidator in Spark 1.4.x,

In Pipeline Example in Spark documentation, they add different parameters (numFeatures, regParam) by using ParamGridBuilder in the Pipeline. Then by the following line of code they make the best model:

val cvModel = crossval.fit(training.toDF)

Now, I want to know what are the parameters (numFeatures, regParam) from ParamGridBuilder that produces the best model.

I already used the following commands without success:

cvModel.bestModel.extractParamMap().toString()
cvModel.params.toList.mkString("(", ",", ")")
cvModel.estimatorParamMaps.toString()
cvModel.explainParams()
cvModel.getEstimatorParamMaps.mkString("(", ",", ")")
cvModel.toString()

Any help?

Thanks in advance,


问:
Does C have a standard ABI?
From a discussion somewhere else:

C++ has no standard ABI (Application Binary Interface)

But neither does C, right?

On any given platform it pretty much does. It wouldn't be useful as the lingua franca for inter-language communication if it lacked one.

What's your take on this?

答:
C has no standard ABI in principle, but in practice, this rarely matters: You do what your OS-vendor does.

Take the calling conventions on x86 Windows, for example: The Windows API uses the so-called 'standard' calling convention (stdcall). Thus, any compiler which wants to interface with the OS needs to implement it. However, stdcall doesn't support all C90 language features (eg calling functions without prototypes, variadic functions). As Microsoft provided a C compiler, a second calling convention was necessary, called the 'C' calling convention (cdecl). Most C compilers on Windows use this as their default calling convention, and thus are interoperable.

In principle, the same could have happened with C++, but as the C++ ABI (including the calling convention) is necessarily far more elaborate, compiler vendors did not agree on a single ABI, but could still interoperate by falling back to extern "C".

ContentLicense: CC BY-SA 4.0

Title: Does C have a standard ABI?


问:
sending mail with nodemailer
whenever i run the code I'm getting the error " Error: Greeting never received at SMTPConnection._formatError...."

```<code>function automatedMailSender(req,res){

var mailOptions = {
    from: "abc <abc@test.com>", // sender address
    to: 'nit@test.com', // list of receivers
    subject: 'Hello ', // Subject line
    text: 'Hello world ?', // plain text body
    html: '<b>Hello world ?</b>' // html body
 };

var mailer=nodemailer.createTransport({
    host: 'mail.test.com',
    port: 465,
    secure: false, // secure:true for port 465, secure:false for port 587
    auth: {
        user: 'mymail@test.com',
        pass: '1234'
    }
});

mailer.sendMail(mailOptions, (error, response)=>{
    if(error){
        console.log('mail not sent \n',error);
    }
    else{
        console.log("Message sent: " ,response.message);
    }
 });
}
</code>```

I'm I doing something wrong in the code.

答:
```<code>tls:{
        rejectUnauthorized:false
    }
</code>```

fixed it by using the above code in mailer variable.
Thanks guys

Title: sending mail with nodemailer

Body:
whenever i run the code I'm getting the error " Error: Greeting never received at SMTPConnection._formatError...."

function automatedMailSender(req,res){

var mailOptions = {
    from: "abc <abc@test.com>", // sender address
    to: 'nit@test.com', // list of receivers
    subject: 'Hello ', // Subject line
    text: 'Hello world ?', // plain text body
    html: 'Hello world ?' // html body
 };

var mailer=nodemailer.createTransport({
    host: 'mail.test.com',
    port: 465,
    secure: false, // secure:true for port 465, secure:false for port 587
    auth: {
        user: 'mymail@test.com',
        pass: '1234'
    }
});

mailer.sendMail(mailOptions, (error, response)=>{
    if(error){
        console.log('mail not sent \n',error);
    }
    else{
        console.log("Message sent: " ,response.message);
    }
 });
}

I'm I doing something wrong in the code.

Body:
tls:{
        rejectUnauthorized:false
    }

fixed it by using the above code in mailer variable.
Thanks guys


问:
Local Storage or other data persistence in elm
I am just beginning to look at Elm with the idea of building a simple web application with it. My idea would require to persist some user data in the browser.

Is there a way to handle data persistence directly with Elm? For example in browser session or even local storage? Or should I use ports to do it with JavaScript?

答: The official answer is "use ports" (for 0.18 - 0.19.1) while awaiting re-publication of Elm's official local storage library: https://github.com/elm-lang/persistent-cache</p>


问:
moveTaskToBack(true) returns false always
I know this has been asked earlier here & here too.They are not answered properly (or not answered at all).But,i don't know why moveTaskToBack(true); always returns false for me .Can anyone tell me why and how could i solve the issue? Thanks in advance.

```<code>public void onBackPressed() {
    boolean r=  moveTaskToBack(true);
    //r is false !! using API LEVEL 8
}
</code>```

Note:The activity from which i am calling it is a child Activity included in a tabActivity and neither of this is a MAIN or LAUNCHER activity.I don't know if that makes a difference.

EDIT:
and as a result the application does'nt go to background.I want it to go to background just as if the hardware HOME is pressed

答:
I came into the similar problem(a child Activity included in a tabActivity), when you call moveTaskToBack(true) in the child activity, it doesn't work, whereas it works in the parent activity. You can call moveTaskToBack(true) in child activity like this:
ChildActivity.this.getParent().moveTaskToBack(true)

Body:
I know this has been asked earlier here & here too.They are not answered properly (or not answered at all).But,i don't know why moveTaskToBack(true); always returns false for me .Can anyone tell me why and how could i solve the issue? Thanks in advance.

public void onBackPressed() {
    boolean r=  moveTaskToBack(true);
    //r is false !! using API LEVEL 8
}

Note:The activity from which i am calling it is a child Activity included in a tabActivity and neither of this is a MAIN or LAUNCHER activity.I don't know if that makes a difference.

EDIT:
and as a result the application does'nt go to background.I want it to go to background just as if the hardware HOME is pressed


问:
VBA to use Checkbox Selection for Multiple cases
I have designed an userform with 7checkboxes. Each Checkbox has an call function, which is called as autofilter. This function autofilter, helps to filter the field 4 in my sheet and Displays the result.

Here, I have 3 cases.

Case1. when Checkbox1 is selected,  Display the result of autofilter1.

case2: when checkboxes1 and 2 are selected, Display the result of autofilter1 and 2.

Note: it is not necessary that user can select just checkboxes 1 and 2, it can be checkbox 2 and 3 or 1 and 3 as well or sometime all 3 selection.

Case3: when nothing is selected, clear the filter.

I am successful in generating the case1 Situation, How should I proceed, in order to achieve case2 and case3.

Below is the autofilter function, which is assigned to checkbox1.

```<code>Sub autofilter1()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Result")
wslr = ws.Cells(Rows.Count, 1).End(xlUp).Row
Set myfilt = ws.Range("A1:D" & wslr)
myfilt.autofilter Field:=4, Criteria1:= _
"USA"
End Sub
</code>```

autofilter function assigned to checkbox2.

```<code>Sub autofilter2()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Result")
wslr = ws.Cells(Rows.Count, 1).End(xlUp).Row
Set myfilt = ws.Range("A1:D" & wslr)
myfilt.autofilter Field:=4, Criteria1:= _
"Germany"
End Sub
</code>```

autofilter function assigned to Checkbox 3.

```<code>Sub autofilter3()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Result_APQP")
wslr = ws.Cells(Rows.Count, 1).End(xlUp).Row
Set myfilt = ws.Range("A1:D" & wslr)
myfilt.autofilter Field:=4, Criteria1:= _
"France"
End Sub
</code>```

In the Command Button, "Go", I have the following code,

```<code>Private Sub CommandButton4_Click()
If CheckBox1.Value = True Then
Call autofilter1
End If
If CheckBox2.Value = True Then
Call autofilter2
End If
If CheckBox3.Value = True Then
Call autofiletr3
End If
End Sub
</code>```

I have attached the Image also, for reference. In the Image, i have just taken the example for 3 Checkbox.

答:
This is code for a UserForm module.

I made a UserForm with 3 checkboxes.

Each event handler just fires the DoFilter() method, which checks the checkboxes and for the ones that are true, builds string array based on their Caption (as in your example pictures) and passes that Array to the AutoFilter. If the Array is empty, the autofilter gets disabled.

Edit:
In the Visual Basic Editor (ALT+F11), in the Project window right-click. In the menu select Insert -> UserForm. On this UserForm, add a number of CheckBoxes. For each checkbox, change the Caption property in the Properties window to a value that you want to display in the filtered range, e.g. CheckBox1.Caption would be "USA" as per the question. Next, Right-click on the userform module and select View Code. In the code window, paste everything below:

```<code>Private Sub DoFilter()

Dim ws As Worksheet
Dim strCriteria() As String
Dim arrIdx As Integer

Dim cBox As Control

arrIdx = 0
For Each cBox In Me.Controls
    If TypeName(cBox) = "CheckBox" Then
        If cBox.Value = True Then
            ReDim Preserve strCriteria(0 To arrIdx)
            strCriteria(arrIdx) = cBox.Caption
            arrIdx = arrIdx + 1
        End If
    End If
Next cBox

Set ws = ThisWorkbook.Sheets("Sheet2")
If arrIdx = 0 Then
    ws.UsedRange.AutoFilter
Else
    ws.Range("A:D").AutoFilter Field:=4, Criteria1:=Array(strCriteria), Operator:=xlFilterValues
End If

End Sub

Private Sub CheckBox1_Change() 'Repeat for each CheckBox on your form.
    DoFilter
End Sub
Private Sub CheckBox2_Change() 'Repeat for each CheckBox on your form.
    DoFilter
End Sub
Private Sub CheckBox3_Change() 'Repeat for each CheckBox on your form.
    DoFilter
End Sub
</code>```

**Additional Edit:**N.b. in this case the filter will trigger as soon as you change the checkbox. If you want to apply the filter on the click of a commandbutton, you can also put the following code in the UserForm module, instead of the Private Sub CheckBox#_Change()

```<code>Private Sub CommandButton4_Click()
    DoFilter
End Sub
</code>```

You might want to use a Control Array in order not to have each CheckBox_Change event handler seperately listed.

Body:
I have designed an userform with 7checkboxes. Each Checkbox has an call function, which is called as autofilter. This function autofilter, helps to filter the field 4 in my sheet and Displays the result.

Here, I have 3 cases.

Case1. when Checkbox1 is selected,  Display the result of autofilter1.

case2: when checkboxes1 and 2 are selected, Display the result of autofilter1 and 2.

Note: it is not necessary that user can select just checkboxes 1 and 2, it can be checkbox 2 and 3 or 1 and 3 as well or sometime all 3 selection.

Case3: when nothing is selected, clear the filter.

I am successful in generating the case1 Situation, How should I proceed, in order to achieve case2 and case3.

Below is the autofilter function, which is assigned to checkbox1.

Sub autofilter1()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Result")
wslr = ws.Cells(Rows.Count, 1).End(xlUp).Row
Set myfilt = ws.Range("A1:D" & wslr)
myfilt.autofilter Field:=4, Criteria1:= _
"USA"
End Sub

autofilter function assigned to checkbox2.

Sub autofilter2()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Result")
wslr = ws.Cells(Rows.Count, 1).End(xlUp).Row
Set myfilt = ws.Range("A1:D" & wslr)
myfilt.autofilter Field:=4, Criteria1:= _
"Germany"
End Sub

autofilter function assigned to Checkbox 3.

Sub autofilter3()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Result_APQP")
wslr = ws.Cells(Rows.Count, 1).End(xlUp).Row
Set myfilt = ws.Range("A1:D" & wslr)
myfilt.autofilter Field:=4, Criteria1:= _
"France"
End Sub

In the Command Button, "Go", I have the following code,

Private Sub CommandButton4_Click()
If CheckBox1.Value = True Then
Call autofilter1
End If
If CheckBox2.Value = True Then
Call autofilter2
End If
If CheckBox3.Value = True Then
Call autofiletr3
End If
End Sub

I have attached the Image also, for reference. In the Image, i have just taken the example for 3 Checkbox.

Body:
This is code for a UserForm module.

I made a UserForm with 3 checkboxes.

Each event handler just fires the DoFilter() method, which checks the checkboxes and for the ones that are true, builds string array based on their Caption (as in your example pictures) and passes that Array to the AutoFilter. If the Array is empty, the autofilter gets disabled.

Edit:
In the Visual Basic Editor (ALT+F11), in the Project window right-click. In the menu select Insert -> UserForm. On this UserForm, add a number of CheckBoxes. For each checkbox, change the Caption property in the Properties window to a value that you want to display in the filtered range, e.g. CheckBox1.Caption would be "USA" as per the question. Next, Right-click on the userform module and select View Code. In the code window, paste everything below:

Private Sub DoFilter()

Dim ws As Worksheet
Dim strCriteria() As String
Dim arrIdx As Integer

Dim cBox As Control

arrIdx = 0
For Each cBox In Me.Controls
    If TypeName(cBox) = "CheckBox" Then
        If cBox.Value = True Then
            ReDim Preserve strCriteria(0 To arrIdx)
            strCriteria(arrIdx) = cBox.Caption
            arrIdx = arrIdx + 1
        End If
    End If
Next cBox

Set ws = ThisWorkbook.Sheets("Sheet2")
If arrIdx = 0 Then
    ws.UsedRange.AutoFilter
Else
    ws.Range("A:D").AutoFilter Field:=4, Criteria1:=Array(strCriteria), Operator:=xlFilterValues
End If

End Sub

Private Sub CheckBox1_Change() 'Repeat for each CheckBox on your form.
    DoFilter
End Sub
Private Sub CheckBox2_Change() 'Repeat for each CheckBox on your form.
    DoFilter
End Sub
Private Sub CheckBox3_Change() 'Repeat for each CheckBox on your form.
    DoFilter
End Sub

**Additional Edit:**N.b. in this case the filter will trigger as soon as you change the checkbox. If you want to apply the filter on the click of a commandbutton, you can also put the following code in the UserForm module, instead of the Private Sub CheckBox#_Change()

Private Sub CommandButton4_Click()
    DoFilter
End Sub

You might want to use a Control Array in order not to have each CheckBox_Change event handler seperately listed.


问:
Javascript error while expanding product categories on Prestashop 1.6 backoffice
I have a Prestashop 1.6.1.14 shop and at the backoffice when I'm adding a new product and I try to expand all the categories available to associate with the new product I get this error:

```<code>VM837:33 Uncaught TypeError: Cannot read property 'parent' of null
at organizeTree (eval at <anonymous> (jquery-1.11.0.min.js:2), <anonymous>:33:32)
at Object.eval [as success] (eval at <anonymous> (jquery-1.11.0.min.js:2), <anonymous>:195:6)
at j (jquery-1.11.0.min.js:2)
at Object.fireWith [as resolveWith] (jquery-1.11.0.min.js:2)
at x (jquery-1.11.0.min.js:4)
at XMLHttpRequest.b (jquery-1.11.0.min.js:4)
</code>```

Any ideas on how to solve it?

答:
Try to disables non Prestashop modules in

Advanced Preferences > Performances

and refresh your cache, see if issue comes from external plugins

Body:
I have a Prestashop 1.6.1.14 shop and at the backoffice when I'm adding a new product and I try to expand all the categories available to associate with the new product I get this error:

VM837:33 Uncaught TypeError: Cannot read property 'parent' of null
at organizeTree (eval at <anonymous> (jquery-1.11.0.min.js:2), <anonymous>:33:32)
at Object.eval [as success] (eval at <anonymous> (jquery-1.11.0.min.js:2), <anonymous>:195:6)
at j (jquery-1.11.0.min.js:2)
at Object.fireWith [as resolveWith] (jquery-1.11.0.min.js:2)
at x (jquery-1.11.0.min.js:4)
at XMLHttpRequest.b (jquery-1.11.0.min.js:4)

Any ideas on how to solve it?


问:
How to handle many checkboxes in MVVM (WPF)?
I have a list of extensions each with it's own checkbox that user needs to choose from:

In the end I need to have a List or an ObservableCollection of all the extensions chosen.

Doing this non-MVVM is quite straight forward. I create the event of Checked or Unchecked, and I add the content of the sender.

View:

```<code><CheckBox Checked="ToggleButton_OnChecked" Unchecked="ToggleButton_OnUnchecked">exe</CheckBox>
</code>```

Code Behind:

```<code>    private void ToggleButton_OnChecked(object sender, RoutedEventArgs e)
    {
        var ext = ((CheckBox) sender).Content.ToString();
        Model.FirstRun.ExcludeExt.Add(ext);
    }

    private void ToggleButton_OnUnchecked(object sender, RoutedEventArgs e)
    {
        var ext = ((CheckBox)sender).Content.ToString();
        Model.FirstRun.ExcludeExt.Remove(ext);
    }
</code>```

If I want to do this MVVM style, as far as I know - I have to create a property for each one of the checkboxes and bind them to the UI. This is a lot of work.

Is there any simpler way?

答:
You should think about a structure first and then it is not that much work and pretty straight forward to use.

For example: you have groups of extensions. I would create somethink like this (just pseudo code; e.g. no INotifyPropertyChanged implemented).

```<code>public class ExtensionGroup
{
    public string Name {get; set;}
    public ObservableCollection<ExtensionInfo> ExtensionInfos {get; set;}
}

public class ExtensionInfo
{
    public string Extension {get; set;}
    public bool IsChecked {get; set;}

    public ExtensionInfo(string extension)
    {
        Extension = extension;
    }
}
</code>```

And in your ViewModel you can create

```<code>public ObservableCollection<ExtensionGroup> ExtensionGroups {get; set;}
</code>```

Now you have to add the data like this

```<code>var extensionGroup = new ExtensionGroup{Name = "Executables"};
extensionGroup.ExtensionInfos.Add(new ExtensionInfo("exe");
extensionGroup.ExtensionInfos.Add(new ExtensionInfo("bat");
</code>```

and after that you have a list with all groups including the extensions.

In you view you can bind this data and you're done. For the view you could use a ListView with a DataTemplate or some other items control.

Your view will get a lot easier with less code because you just have to specify the layout one time.

/edit
This is a sample implementation of the xaml. I used a ItemsControl instead of a ListView.

```<code><ItemsControl ItemsSource="{Binding ExtensionGroups}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <Label Content="{Binding Name}"/>
                <ItemsControl ItemsSource="{Binding ExtensionInfos}">
                    <ItemsControl.ItemsPanel>
                        <ItemsPanelTemplate>
                            <WrapPanel />
                        </ItemsPanelTemplate>
                    </ItemsControl.ItemsPanel>
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <CheckBox IsChecked="{Binding IsChecked}"
                                      Content="{Binding Extension}"/>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>
</code>```

Looks like this (just added two groups with two extensions).

Body:
I have a list of extensions each with it's own checkbox that user needs to choose from:

In the end I need to have a List or an ObservableCollection of all the extensions chosen.

Doing this non-MVVM is quite straight forward. I create the event of Checked or Unchecked, and I add the content of the sender.

View:

<CheckBox Checked="ToggleButton_OnChecked" Unchecked="ToggleButton_OnUnchecked">exe</CheckBox>

Code Behind:

    private void ToggleButton_OnChecked(object sender, RoutedEventArgs e)
    {
        var ext = ((CheckBox) sender).Content.ToString();
        Model.FirstRun.ExcludeExt.Add(ext);
    }

    private void ToggleButton_OnUnchecked(object sender, RoutedEventArgs e)
    {
        var ext = ((CheckBox)sender).Content.ToString();
        Model.FirstRun.ExcludeExt.Remove(ext);
    }

If I want to do this MVVM style, as far as I know - I have to create a property for each one of the checkboxes and bind them to the UI. This is a lot of work.

Is there any simpler way?

Body:
You should think about a structure first and then it is not that much work and pretty straight forward to use.

For example: you have groups of extensions. I would create somethink like this (just pseudo code; e.g. no INotifyPropertyChanged implemented).

public class ExtensionGroup
{
    public string Name {get; set;}
    public ObservableCollection<ExtensionInfo> ExtensionInfos {get; set;}
}

public class ExtensionInfo
{
    public string Extension {get; set;}
    public bool IsChecked {get; set;}

    public ExtensionInfo(string extension)
    {
        Extension = extension;
    }
}

And in your ViewModel you can create

public ObservableCollection<ExtensionGroup> ExtensionGroups {get; set;}

Now you have to add the data like this

var extensionGroup = new ExtensionGroup{Name = "Executables"};
extensionGroup.ExtensionInfos.Add(new ExtensionInfo("exe");
extensionGroup.ExtensionInfos.Add(new ExtensionInfo("bat");

and after that you have a list with all groups including the extensions.

In you view you can bind this data and you're done. For the view you could use a ListView with a DataTemplate or some other items control.

Your view will get a lot easier with less code because you just have to specify the layout one time.

/edit
This is a sample implementation of the xaml. I used a ItemsControl instead of a ListView.

<ItemsControl ItemsSource="{Binding ExtensionGroups}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <Label Content="{Binding Name}"/>
                <ItemsControl ItemsSource="{Binding ExtensionInfos}">
                    <ItemsControl.ItemsPanel>
                        <ItemsPanelTemplate>
                            <WrapPanel />
                        </ItemsPanelTemplate>
                    </ItemsControl.ItemsPanel>
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <CheckBox IsChecked="{Binding IsChecked}"
                                      Content="{Binding Extension}"/>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Looks like this (just added two groups with two extensions).


问:
Angular 2 How to detect back button press using router and location.go()?
I have built an app that uses router 3.0.0-beta.1 to switch between app sections. I also use location.go() to emulate the switch between subsections of the same page. I used <base href="/"> and a few URL rewrite rules in order to redirect all routes to index.html in case of page refresh. This allows the router to receive the requested subsection as a URL param. Basically I have managed to avoid using the HashLocationStrategy.

routes.ts

```<code>export const routes: RouterConfig = [
    {
        path: '',
        redirectTo: '/catalog',
        pathMatch: 'full'
    },
    {
        path: 'catalog',
        component: CatalogComponent
    },
    {
        path: 'catalog/:topCategory',
        component: CatalogComponent
    },
    {
        path: 'summary',
        component: SummaryComponent
    }
];
</code>```

If I click on a subsection in the navigation bar 2 things happen:

logation.go() updates the URL with the necessary string in order to indicate the current subsection

A custom scrollTo() animation scrolls the page at the top of the requested subsection.

If I refresh the page I am using the previously defined route and extract the necessary parameter to restore scroll to the requested subsection.

```<code>this._activatedRoute.params
    .map(params => params['topCategory'])
    .subscribe(topCategory => {
        if (typeof topCategory !== 'undefined' &&
            topCategory !== null
        ) {
            self.UiState.startArrowWasDismised = true;
            self.UiState.selectedTopCategory = topCategory;
        }
    });
</code>```

All works fine except when I click the back button. If previous page was a different section, the app router behaves as expected. However if the previous page/url was a subsection, the url changes to the previous one, but nothing happens in the UI. How can I detect if the back button was pressed in order to invoke the scrollTo() function to do it's job again?

Most answers I saw relly on the event onhashchange, but this event does not get fired in my app since I have no hash in the URL afterall...

答:
To detect browser back button click
import platformlocation from '@angular/common and place the below code in your constructor :</p>

```<code> constructor(location: PlatformLocation) {
     location.onPopState(() => {
        alert(window.location);
     }); }
</code>```

Body:
I have built an app that uses router 3.0.0-beta.1 to switch between app sections. I also use location.go() to emulate the switch between subsections of the same page. I used <base href="/"> and a few URL rewrite rules in order to redirect all routes to index.html in case of page refresh. This allows the router to receive the requested subsection as a URL param. Basically I have managed to avoid using the HashLocationStrategy.

routes.ts

export const routes: RouterConfig = [
    {
        path: '',
        redirectTo: '/catalog',
        pathMatch: 'full'
    },
    {
        path: 'catalog',
        component: CatalogComponent
    },
    {
        path: 'catalog/:topCategory',
        component: CatalogComponent
    },
    {
        path: 'summary',
        component: SummaryComponent
    }
];

If I click on a subsection in the navigation bar 2 things happen:

logation.go() updates the URL with the necessary string in order to indicate the current subsection

A custom scrollTo() animation scrolls the page at the top of the requested subsection.

If I refresh the page I am using the previously defined route and extract the necessary parameter to restore scroll to the requested subsection.

this._activatedRoute.params
    .map(params => params['topCategory'])
    .subscribe(topCategory => {
        if (typeof topCategory !== 'undefined' &&
            topCategory !== null
        ) {
            self.UiState.startArrowWasDismised = true;
            self.UiState.selectedTopCategory = topCategory;
        }
    });

All works fine except when I click the back button. If previous page was a different section, the app router behaves as expected. However if the previous page/url was a subsection, the url changes to the previous one, but nothing happens in the UI. How can I detect if the back button was pressed in order to invoke the scrollTo() function to do it's job again?

Most answers I saw relly on the event onhashchange, but this event does not get fired in my app since I have no hash in the URL afterall...

Body:
To detect browser back button click
import platformlocation from '@angular/common and place the below code in your constructor :

 constructor(location: PlatformLocation) {
     location.onPopState(() => {
        alert(window.location);
     }); }


问:
Appbarlayout overlaps with NestedScrollView
I have a coordinator layout, which consists of appbarlayout and nestedscrollview. The problem is that when I open the activity, some part of nestedscrollview is by default hidden behind the expanded action bar (difference shown in the images).

XML File :

```<code><android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:id="@+id/my_appbar_container"
    android:layout_width="match_parent"
    android:layout_height="250dp"
    android:fitsSystemWindows="true"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/collapsing_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:contentScrim="@color/colorPrimary"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <ImageView
            android:id="@+id/ivToolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:adjustViewBounds="true"
            android:scaleType="fitXY"
            android:alpha="0.6"
            app:layout_collapseParallaxMultiplier="0.7" />

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:layout_collapseMode="pin"
            android:alpha="1.0"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

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

<android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        ......
        .......
</code>```

I am not able to figure out what's the issue here, and couldn't find anywhere online. Maybe it's a bug. Please check.

答:
Don't know why but this answer worked on my issue.
Btw I faced with this problem only when I change visibility of any view inside nestedScrollView</p>

Body:
I have a coordinator layout, which consists of appbarlayout and nestedscrollview. The problem is that when I open the activity, some part of nestedscrollview is by default hidden behind the expanded action bar (difference shown in the images).

XML File :

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:id="@+id/my_appbar_container"
    android:layout_width="match_parent"
    android:layout_height="250dp"
    android:fitsSystemWindows="true"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/collapsing_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:contentScrim="@color/colorPrimary"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <ImageView
            android:id="@+id/ivToolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:adjustViewBounds="true"
            android:scaleType="fitXY"
            android:alpha="0.6"
            app:layout_collapseParallaxMultiplier="0.7" />

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:layout_collapseMode="pin"
            android:alpha="1.0"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

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

<android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        ......
        .......

I am not able to figure out what's the issue here, and couldn't find anywhere online. Maybe it's a bug. Please check.


答:
Change your construct method to this:

```<code>public function __construct() {

    $this->conn = new mysqli($this->host, $this->username, $this->password, $this->db_name);
    if ($this->conn->connect_errno) {
        die("database connection failed" . ($this->conn->connect_errno));
    }
}
</code>```

The error is in _construct(), it must be with 2 sublines __, like this __construct()

Title: Fatal:Call to a member function query() on null

Body:
Change your construct method to this:

public function __construct() {

    $this->conn = new mysqli($this->host, $this->username, $this->password, $this->db_name);
    if ($this->conn->connect_errno) {
        die("database connection failed" . ($this->conn->connect_errno));
    }
}

The error is in _construct(), it must be with 2 sublines __, like this __construct()


问:
JUnit - Run test cases from a web application
I have a set of test cases that are written in JUnit. Since there is a dependency on the servlet container for these test cases, I want to run them from a servlet. For example, if I pass the fully qualified class name of the Test class to the servlet, it should be able to run that test case.
I have these test cases in the class path of web application.

答:
```<code>/**
 * The various JUNIT classes should be passed as the <code>class</code> request paramter in the URL.
 * @param request
 * @param response
 */
private void executeJUNITTestCases( HttpServletRequest request, HttpServletResponse response ){
    response.setContentType( "text/plain" );
    //Pass the class names of the Test cases in the URL parameter "class"
    String[] className = request.getParameterValues( "class" );
    try{
        if( className = null || className.length == 0){
            PrintWriter writer = response.getWriter();
            JSONObject obj = new JSONObject();
            obj.put( "error", "Class names should be provided as parameter values of key [class]" );
            writer.write( obj.toString() );
            return;
        }

        OutputStream out = response.getOutputStream();

        final PrintStream pout = new PrintStream( out );
        new JUnitCore().runMain( new JUnitSystem(){

            public PrintStream out(){
                return pout;
            }

            public void exit( int arg0 ){}
        }, className );
        out.close();
    }
    catch( IOException e ){
        e.printStackTrace();
    }
</code>```

Above code helps us to invoke the JUnit test cases within the web application context.

Body:
/**
 * The various JUNIT classes should be passed as the <code>class</code> request paramter in the URL.
 * @param request
 * @param response
 */
private void executeJUNITTestCases( HttpServletRequest request, HttpServletResponse response ){
    response.setContentType( "text/plain" );
    //Pass the class names of the Test cases in the URL parameter "class"
    String[] className = request.getParameterValues( "class" );
    try{
        if( className = null || className.length == 0){
            PrintWriter writer = response.getWriter();
            JSONObject obj = new JSONObject();
            obj.put( "error", "Class names should be provided as parameter values of key [class]" );
            writer.write( obj.toString() );
            return;
        }

        OutputStream out = response.getOutputStream();

        final PrintStream pout = new PrintStream( out );
        new JUnitCore().runMain( new JUnitSystem(){

            public PrintStream out(){
                return pout;
            }

            public void exit( int arg0 ){}
        }, className );
        out.close();
    }
    catch( IOException e ){
        e.printStackTrace();
    }

Above code helps us to invoke the JUnit test cases within the web application context.


问:
Remove session storage when user leaves the app
I want to execute the following code when the user closes my application.

```<code>ngOnDestroy(): void {
    sessionStorage.clear();
}
</code>```

In nutshell, i want to clear sessionStorage of my application once user naviagates away from my app but data shall be preserved when user refreshes the app.

The OnDestroy does not seem to fire when the application is closed.

I have tried below code as well

```<code>ngOnInit() {
   window.onbeforeunload = function () {
     sessionStorage.clear();
     return ''
   }
}
</code>```

I know this is not right place but this clear data on refresh as well :( and moreover this does not work in every browser.

Where can I place this code to get the behavior I'm looking for, or is there a better way to accomplish what I'm trying to accomplish?

答:
You can try this:

```<code>import { HostListener } from '@angular/core';
    @HostListener('window:unload', ['$event'])
    unloadHandler(event) {
        window.sessionStorage.clear();
    }
</code>```

Add it in your components (not necessarily inside ngOnInit). This will clear sessionStorage whenever you close the browser or tab with your application.

Body:
I want to execute the following code when the user closes my application.

ngOnDestroy(): void {
    sessionStorage.clear();
}

In nutshell, i want to clear sessionStorage of my application once user naviagates away from my app but data shall be preserved when user refreshes the app.

The OnDestroy does not seem to fire when the application is closed.

I have tried below code as well

ngOnInit() {
   window.onbeforeunload = function () {
     sessionStorage.clear();
     return ''
   }
}

I know this is not right place but this clear data on refresh as well :( and moreover this does not work in every browser.

Where can I place this code to get the behavior I'm looking for, or is there a better way to accomplish what I'm trying to accomplish?

Body:
You can try this:

import { HostListener } from '@angular/core';
    @HostListener('window:unload', ['$event'])
    unloadHandler(event) {
        window.sessionStorage.clear();
    }

Add it in your components (not necessarily inside ngOnInit). This will clear sessionStorage whenever you close the browser or tab with your application.


问:
SQL Query to suggest Chairs
i am working on trains Reservation with auto suggest chairs query

it's supposed to take trip Date ,from station ,to station and no of seats as bind variables and retrive chairs that are in sequence and not reserved.
for example : if chair 1,3 is reserved and chairs 2,4,5 not reserved and user enterd 2 seats , then query should suggest 4,5 and not 2,4

i'm trying to use lead or lag analyic functions

```<code>select * from
(
    select row_number() over (order by seat_no) rno, seat_no,lag(seat_no,1,0) OVER (ORDER BY seat_no) lag , lead(seat_no,1,0) OVER (ORDER BY seat_no) lead
    from TRAIN_LINE_DETAILS tld,train_lines tl
    where TRIP_DATE = to_date(:tipDate,'dd-mm-yyyy')
    and tld.line_code =  tl.line_code
    and station_from =:sfrom
    and station_to =:sto
    and  is_reserved = 0
)

where rno <= :n
--and lead-1 = seat_no or lag+1 = seat_no
</code>```

output :
output screenshot

答:
Without any sample data or descriptions of your tables it is difficult to test but something like this:

```<code>SELECT seat_no
FROM   (
  SELECT seat_no,
         is_reserved,
         COALESCE(
           LEAD( CASE is_reserved WHEN 0 THEN seat_no END )
             IGNORE NULLS OVER ( ORDER BY seat_no ),
           seat_no + 1
         ) AS next_reserved_seat
  FROM   TRAIN_LINE_DETAILS tld
         INNER JOIN train_lines tl
         ON ( tld.line_code =  tl.line_code )
  WHERE  TRIP_DATE    = to_date(:tipDate,'dd-mm-yyyy')
  AND    station_from =:sfrom
  AND    station_to   =:sto
)
WHERE  is_reserved = 0
AND    next_reserved_seat - seat_no >= :n;
</code>```

This assumes that all the seats are enumerated in your table and each has an associated is_reserved flag which is 0 when the seat is not reserved. The query will go through all the seats looking for those where the seat and the :n-1 subsequent seats are not reserved and will output the seat number at the start of the un-reserved range.

Title: SQL Query to suggest Chairs

Body:
i am working on trains Reservation with auto suggest chairs query

it's supposed to take trip Date ,from station ,to station and no of seats as bind variables and retrive chairs that are in sequence and not reserved.
for example : if chair 1,3 is reserved and chairs 2,4,5 not reserved and user enterd 2 seats , then query should suggest 4,5 and not 2,4

i'm trying to use lead or lag analyic functions

select * from
(
    select row_number() over (order by seat_no) rno, seat_no,lag(seat_no,1,0) OVER (ORDER BY seat_no) lag , lead(seat_no,1,0) OVER (ORDER BY seat_no) lead
    from TRAIN_LINE_DETAILS tld,train_lines tl
    where TRIP_DATE = to_date(:tipDate,'dd-mm-yyyy')
    and tld.line_code =  tl.line_code
    and station_from =:sfrom
    and station_to =:sto
    and  is_reserved = 0
)

where rno <= :n
--and lead-1 = seat_no or lag+1 = seat_no

output :
output screenshot

Body:
Without any sample data or descriptions of your tables it is difficult to test but something like this:

SELECT seat_no
FROM   (
  SELECT seat_no,
         is_reserved,
         COALESCE(
           LEAD( CASE is_reserved WHEN 0 THEN seat_no END )
             IGNORE NULLS OVER ( ORDER BY seat_no ),
           seat_no + 1
         ) AS next_reserved_seat
  FROM   TRAIN_LINE_DETAILS tld
         INNER JOIN train_lines tl
         ON ( tld.line_code =  tl.line_code )
  WHERE  TRIP_DATE    = to_date(:tipDate,'dd-mm-yyyy')
  AND    station_from =:sfrom
  AND    station_to   =:sto
)
WHERE  is_reserved = 0
AND    next_reserved_seat - seat_no >= :n;

This assumes that all the seats are enumerated in your table and each has an associated is_reserved flag which is 0 when the seat is not reserved. The query will go through all the seats looking for those where the seat and the :n-1 subsequent seats are not reserved and will output the seat number at the start of the un-reserved range.


问:
Swift - Replace extra line breaks in server generated CSV file
I have created a statistics controller for administrators to export back-end information from a database. The controller has several fields with UIPickers to filter data and a button to send a request to the server, where the API (written in C#) takes care of the export.

The data is currently being exported to a CSV and added back to my controller. The problem is that the attached file contains one extra line break after every line of data. The CSV looks perfect on the Windows machine, though.

If this a Windows / Unix problem where line breaks are handled differently, what can I do to fix this? I want all those extra lines to be gone before the user actually opens the file as a spreadsheet.

On my windows machine

```<code>Created by: ""
Created on: ""

Name,Date,Score
Jack Sparrow,2017-07-03-14:48:58,80
Jack Sparrow,2017-07-03-14:49:33,100
</code>```

On my Mac and iPhone

```<code>Created by: ""

Created on: ""

Name,Date,Score

Jack Sparrow,2017-07-03-14:48:58,80

Jack Sparrow,2017-07-03-14:49:33,100
</code>```

答: I think we found the problem. In Windows a line break is equal to \r\n, but I needed \n to make it work on Linux/Unix devices.

Body:
I have created a statistics controller for administrators to export back-end information from a database. The controller has several fields with UIPickers to filter data and a button to send a request to the server, where the API (written in C#) takes care of the export.

The data is currently being exported to a CSV and added back to my controller. The problem is that the attached file contains one extra line break after every line of data. The CSV looks perfect on the Windows machine, though.

If this a Windows / Unix problem where line breaks are handled differently, what can I do to fix this? I want all those extra lines to be gone before the user actually opens the file as a spreadsheet.

On my windows machine

Created by: ""
Created on: ""

Name,Date,Score
Jack Sparrow,2017-07-03-14:48:58,80
Jack Sparrow,2017-07-03-14:49:33,100

On my Mac and iPhone

Created by: ""

Created on: ""

Name,Date,Score

Jack Sparrow,2017-07-03-14:48:58,80

Jack Sparrow,2017-07-03-14:49:33,100


问:
[Symfony2]: Cascading element deletion of an entity How to have a life cycle attribute
I'm using symfony 2.7 as CMF .

I have 2 entity user and Mission . mission have a life cycle attribute (createdBy ,updatedBy).

when i try to delete the user i have this error:

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (XXXX.mission, CONSTRAINT FK_19653DBD16FE72E1 FOREIGN KEY (updated_by) REFERENCES fos_user_user (id))

this is my life cycle elément in the entity mission:

```<code>   /**
 * @ORM\ManyToOne(targetEntity="Application\Sonata\UserBundle\Entity\User")
 * @ORM\JoinColumn(name="created_by", referencedColumnName="id" , onDelete="CASCADE")
 */
private $createdBy;

/**
 * @ORM\ManyToOne(targetEntity="Application\Sonata\UserBundle\Entity\User")
 * @ORM\JoinColumn(name="updated_by", referencedColumnName="id" , onDelete="CASCADE")
 */
private $updatedBy;
</code>```

thx for help.

答:
In your user entity:
 @ORM\OneToMany(targetEntity="xx",mappedBy="mission_id",cascade={"persist"})

In your mission entity :

```<code>@ORM\ManyToOne(targetEntity="Application\Sonata\UserBundle\Entity\User")
@ORM\JoinColumn(name="created_by", referencedColumnName="id" ,
onDelete="CASCADE")
</code>```

Body:
I'm using symfony 2.7 as CMF .

I have 2 entity user and Mission . mission have a life cycle attribute (createdBy ,updatedBy).

when i try to delete the user i have this error:

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (XXXX.mission, CONSTRAINT FK_19653DBD16FE72E1 FOREIGN KEY (updated_by) REFERENCES fos_user_user (id))

this is my life cycle elément in the entity mission:

   /**
 * @ORM\ManyToOne(targetEntity="Application\Sonata\UserBundle\Entity\User")
 * @ORM\JoinColumn(name="created_by", referencedColumnName="id" , onDelete="CASCADE")
 */
private $createdBy;

/**
 * @ORM\ManyToOne(targetEntity="Application\Sonata\UserBundle\Entity\User")
 * @ORM\JoinColumn(name="updated_by", referencedColumnName="id" , onDelete="CASCADE")
 */
private $updatedBy;

thx for help.

Body:
In your user entity:
 @ORM\OneToMany(targetEntity="xx",mappedBy="mission_id",cascade={"persist"})

In your mission entity :

@ORM\ManyToOne(targetEntity="Application\Sonata\UserBundle\Entity\User")
@ORM\JoinColumn(name="created_by", referencedColumnName="id" ,
onDelete="CASCADE")