问:
If database record limit reached return to previous page with message
I am building out our membership levels and each one has limits on how many records one can save to the database.  Someone on a laracasts said I would want to check the limit against the membership level in an observer and if the limit has been reached redirect them to the previous page and show an error.

This seems to be working except it redirects with the message that the limit has been reach AND creates the records.  Ideally it should not create the record if the limit has been reached.  I don't know what I am doing wrong, I also tried to return false; instead of return back(); but that didnt work either.

(by the way if there is an easier way to do this I am all ears)

Here is my observer:

```<code><?php

namespace App\Observers;

use App\Company;
use Auth;
use Session;

class SubscriptionLimits {

    public function __construct(){
        $this->company =  Auth::user()->company_id;
    }

    public function creating()
    {
      try {
                $company = Company::find($this->company);

                $clients = \App\Client::where(['company_id' => $this->company])->count();
                $contacts = \App\Contact::where(['company_id' => $this->company])->count();
                $leads = \App\Lead::where(['company_id' => $this->company])->count();
                $opportunities = \App\Opportunity::where(['company_id' => $this->company])->count();
                $invoices = \App\Invoice::where(['company_id' => $this->company])->count();
                $estimates = \App\Estimate::where(['company_id' => $this->company])->count();
                $proposals = \App\Proposal::where(['company_id' => $this->company])->count();
                $projects = \App\Project::where(['company_id' => $this->company])->count();
                $tasks = \App\Task::where(['company_id' => $this->company])->count();
                $boards = \App\Board::where(['company_id' => $this->company])->count();
                $bulletins = \App\Bulletin::where(['company_id' => $this->company])->count();
                $cards = \App\Card::where(['company_id' => $this->company])->count();
                $lineitems = \App\LineItem::where(['company_id' => $this->company])->count();
                $notes = \App\Note::where(['company_id' => $this->company])->count();
                $timer = \App\Timer::where(['company_id' => $this->company])->count();
                $templates = \App\Template::where(['company_id' => $this->company])->count();
                $userExtra = \App\UserExtra::where(['company_id' => $this->company])->count();

                $count = $clients + $contacts + $leads + $opportunities + $invoices + $estimates + $proposals + $projects + $tasks + $boards + $bulletins + $cards + $lineitems + $notes + $timer + $templates + $userExtra;

                if($count >= 5 && !$company->subscriptions){ //Free tier throw error because limit is reached
                    //return false; //Works but throws error
                    Session::flash('error', 'You have reached your record limit, please <a href="/order">upgrade now</a> to continue');
                    return back();
                }

                if($company->subscribed('middle_tier_monthly_per_user') || $company->subscribed('middle_tier_annual_per_user')){
                    if($count > 10){ //If middle tier and limit is reached
                        //return false; //Works but throws error
                        Session::flash('error', 'You have reached your record limit, please <a href="/order">upgrade now</a> to continue');
                        return back();
                    }
                }
            } catch (Exception $e) {
                Session::flash('error', 'You have reached your record limit, please <a href="/order">upgrade now</a> to continue');
                return back();
            }
    }

}
</code>```

UPDATE
Here is a video of the issue, this should not let me create a record and should instead return the limit reached message and prompt me to upgrade.

答:
You don't redirect on observer. Observers are only meant to intercept the data before its written to the database.

You'll redirect on the controller where you're saving your data to the database.

In your controller:
`

```<code>function store(){
    if(!$model->save()) redirect()->back();
       return redirect()->to('#url');
}
</code>```

`

Body:
I am building out our membership levels and each one has limits on how many records one can save to the database.  Someone on a laracasts said I would want to check the limit against the membership level in an observer and if the limit has been reached redirect them to the previous page and show an error.

This seems to be working except it redirects with the message that the limit has been reach AND creates the records.  Ideally it should not create the record if the limit has been reached.  I don't know what I am doing wrong, I also tried to return false; instead of return back(); but that didnt work either.

(by the way if there is an easier way to do this I am all ears)

Here is my observer:

<?php

namespace App\Observers;

use App\Company;
use Auth;
use Session;

class SubscriptionLimits {

    public function __construct(){
        $this->company =  Auth::user()->company_id;
    }

    public function creating()
    {
      try {
                $company = Company::find($this->company);

                $clients = \App\Client::where(['company_id' => $this->company])->count();
                $contacts = \App\Contact::where(['company_id' => $this->company])->count();
                $leads = \App\Lead::where(['company_id' => $this->company])->count();
                $opportunities = \App\Opportunity::where(['company_id' => $this->company])->count();
                $invoices = \App\Invoice::where(['company_id' => $this->company])->count();
                $estimates = \App\Estimate::where(['company_id' => $this->company])->count();
                $proposals = \App\Proposal::where(['company_id' => $this->company])->count();
                $projects = \App\Project::where(['company_id' => $this->company])->count();
                $tasks = \App\Task::where(['company_id' => $this->company])->count();
                $boards = \App\Board::where(['company_id' => $this->company])->count();
                $bulletins = \App\Bulletin::where(['company_id' => $this->company])->count();
                $cards = \App\Card::where(['company_id' => $this->company])->count();
                $lineitems = \App\LineItem::where(['company_id' => $this->company])->count();
                $notes = \App\Note::where(['company_id' => $this->company])->count();
                $timer = \App\Timer::where(['company_id' => $this->company])->count();
                $templates = \App\Template::where(['company_id' => $this->company])->count();
                $userExtra = \App\UserExtra::where(['company_id' => $this->company])->count();

                $count = $clients + $contacts + $leads + $opportunities + $invoices + $estimates + $proposals + $projects + $tasks + $boards + $bulletins + $cards + $lineitems + $notes + $timer + $templates + $userExtra;

                if($count >= 5 && !$company->subscriptions){ //Free tier throw error because limit is reached
                    //return false; //Works but throws error
                    Session::flash('error', 'You have reached your record limit, please upgrade now to continue');
                    return back();
                }

                if($company->subscribed('middle_tier_monthly_per_user') || $company->subscribed('middle_tier_annual_per_user')){
                    if($count > 10){ //If middle tier and limit is reached
                        //return false; //Works but throws error
                        Session::flash('error', 'You have reached your record limit, please upgrade now to continue');
                        return back();
                    }
                }
            } catch (Exception $e) {
                Session::flash('error', 'You have reached your record limit, please upgrade now to continue');
                return back();
            }
    }

}

UPDATE
Here is a video of the issue, this should not let me create a record and should instead return the limit reached message and prompt me to upgrade.

Body:
You don't redirect on observer. Observers are only meant to intercept the data before its written to the database.

You'll redirect on the controller where you're saving your data to the database.

In your controller:
`

function store(){
    if(!$model->save()) redirect()->back();
       return redirect()->to('#url');
}

`


来源: stackexchange

问:
Eigen Broadcast Comparison
In Eigen we can compare two arrays component wise. We can also use broadcasting to add a (suitably sized) vector to a matrix. However, these two do not combine in the obvious way to allow row/column-wise comparison operations. For example

```<code>#include <iostream>
#include <Eigen/Core>

using namespace std;
using namespace Eigen;

using vect_t = Matrix<double, 1, 3>;
using matr_t = Matrix<double, 5, 3>;

int main()
{
    vect_t l(0.1,0.1,0.1);
    vect_t u(0.3,0.3,0.3);
    matr_t X;
    X << 0.0, 0.0, 0.0,
         0.1, 0.2, 0.1,
         0.2, 0.2, 0.2,
         1.0, 0.0, 0.2,
         0.2, 0.4, 0.4;

    auto Y = l.array() < u.array(); // okay, gives [1, 1, 1]
    auto Z = X.array().rowwise() + l.array();
    // okay, gives
    // 0.1, 0.1, 0.1,
    // 0.2, 0.3, 0.2,
    // 0.3, 0.3, 0.3,
    // 1.1, 0.1, 0.3,
    // 0.3, 0.5, 0.5;

    //auto W = X.array().rowwise() < l.array(); // does not compile
    // would expect (via broadcasting) something like
    // 1, 1, 1,
    // 0, 0, 0,
    // 0, 0, 0,
    // 0, 1, 0,
    // 0, 0, 0

    cout << X << endl << endl;
    cout << Y << endl << endl;
    cout << Z << endl << endl;
    //cout << W << endl << endl;

    return 0;
}
</code>```

How is it possible to achieve this sort of row-wise comparison?

Comment: It seems to me, that it should be possible for this to work nicely. Is just a case that it has not been implemented yet or am I missing something?

答:
Whenever rowwise() or colwise() does not work, you can use replicate. In your case:

```<code>auto W = X.array() < l.array().replicate(X.rows(), 1);
</code>```

or

```<code>auto W = X.array() < l.array().colwise().replicate(X.rows());
</code>```

ContentLicense: CC BY-SA 3.0

Title: Eigen Broadcast Comparison

Body:
In Eigen we can compare two arrays component wise. We can also use broadcasting to add a (suitably sized) vector to a matrix. However, these two do not combine in the obvious way to allow row/column-wise comparison operations. For example

#include <iostream>
#include <Eigen/Core>

using namespace std;
using namespace Eigen;

using vect_t = Matrix<double, 1, 3>;
using matr_t = Matrix<double, 5, 3>;

int main()
{
    vect_t l(0.1,0.1,0.1);
    vect_t u(0.3,0.3,0.3);
    matr_t X;
    X << 0.0, 0.0, 0.0,
         0.1, 0.2, 0.1,
         0.2, 0.2, 0.2,
         1.0, 0.0, 0.2,
         0.2, 0.4, 0.4;

    auto Y = l.array() < u.array(); // okay, gives [1, 1, 1]
    auto Z = X.array().rowwise() + l.array();
    // okay, gives
    // 0.1, 0.1, 0.1,
    // 0.2, 0.3, 0.2,
    // 0.3, 0.3, 0.3,
    // 1.1, 0.1, 0.3,
    // 0.3, 0.5, 0.5;

    //auto W = X.array().rowwise() < l.array(); // does not compile
    // would expect (via broadcasting) something like
    // 1, 1, 1,
    // 0, 0, 0,
    // 0, 0, 0,
    // 0, 1, 0,
    // 0, 0, 0

    cout << X << endl << endl;
    cout << Y << endl << endl;
    cout << Z << endl << endl;
    //cout << W << endl << endl;

    return 0;
}

How is it possible to achieve this sort of row-wise comparison?

Comment: It seems to me, that it should be possible for this to work nicely. Is just a case that it has not been implemented yet or am I missing something?

Body:
Whenever rowwise() or colwise() does not work, you can use replicate. In your case:

auto W = X.array() < l.array().replicate(X.rows(), 1);

or

auto W = X.array() < l.array().colwise().replicate(X.rows());


问:
Rails 5: do not allow create action if params are empty
I have this Controller, where I can create User Group and add Users, Roles to it:

```<code>class Strongbolt::UserGroupsController < ApplicationController
# some code...

def create
  user_roles #Helper method
  respond_to do |format|
  if @user_group = Strongbolt::UserGroup.create!(user_group_params)
    format.json { head :no_content }
    format.js { flash.now[:notice] = "User group #{@user_group.name} created!" }
  else
    format.json { render json: @user_group.errors.full_messages,
                          status: :unprocessable_entity }
    end
  end
end

# some code...

def user_group_params
  params.require(:strongbolt_user_group)
        .permit(:name, :description, {user_ids: []}, {role_ids: []})
end
</code>```

If user_ids and role_ids are empty, I need to do some error or stop Create action - I do not need User Group without at least one user and role. How do I do that, please?

Since this is related to Strongbolt gem where related Models are inside it, I cannot do validation on model side - I have to do it in Controller. At the moment this functionality is not there, so I have to add that for my project.

So far I've been trying to do something related tho this:

redirect_to 'new' unless params[:user_ids].present?

Update

Here is part of my Form:

```<code><!-- Users tab -->
<div class="tab-pane" id="users">
  <div class="i-checks">
    <%= f.collection_check_boxes(:user_ids, @users_for_group, :id, :name) do |b| %>
      <div class="col-sm-1">
        <%= b.check_box %>
      </div>
        <%= b.label %><br><br>
    <% end %>
  </div>
</div>
<!-- Roles tab -->
  <div class="tab-pane" id="roles">
    <div class="i-checks">
      <%= f.collection_check_boxes(:role_ids, @roles, :id, :name) do |bb| %>
        <div class="col-sm-1">
          <%= bb.check_box %>
        </div>
          <%= bb.label %><br><br>
      <% end %>
    </div>
  </div>
</code>```

Update 2

```<code>  def create
    user_roles #Helper method
    respond_to do |format|
      unless params[:user_ids].blank? || params[:role_ids].blank?
        @user_group = Strongbolt::UserGroup.create!(user_group_params)
        format.json { head :no_content }
        format.js { flash.now[:notice] = "User group #{@user_group.name} created!" }
      else
        format.json {
          render json: @user_group.errors.full_messages, status: :unprocessable_entity
        }
        format.js { flash.now[:error] = "User group was not created!" }
      end
    end
  end
</code>```

In terminal I see this:

```<code>Started POST "/en/strongbolt/user_groups" for 10.0.2.2 at 2017-06-06 17:51:59 +0000
Processing by Strongbolt::UserGroupsController#create as JS
  Parameters: {"utf8"=>"✓", "strongbolt_user_group"=>{"name"=>"Test @Jun6 v2", "description"=>"test", "user_ids"=>["", "5"], "role_ids"=>["", "2"]}, "commit"=>"Create User Group", "locale"=>"en"}
</code>```

The Solution

First of all it appears collection_check_boxes by default include hidden value " ", so I had to remove that with something like this:

```<code><%= f.collection_check_boxes(:role_ids, @roles, :id, :name, include_hidden: false) do |bb| %>
</code>```

If not to remove hidden field, Rails will not check empty params as basically params are there.

Then I was able to implement this:

```<code>before_action :validate_presence, only: [:create]

def check_presence
  params[:strongbolt_user_group][:user_ids].present? &&
  params[:strongbolt_user_group][:role_ids].present?
end

def validate_presence
  if !check_presence
    render json: { error: {
        message: "Bad Request, parameters missing.",
        status: 500 }
    }
  end
end
</code>```

I had to include Model name to check params presence, otherwise it did not work. Now I can implement JS part where I show some messages that something can't be blank, etc., but that is different story. Now my Controller will not accept empty params in this special case with Strongbolt gem.

答:
You can just add a validation. Read about them here: http://guides.rubyonrails.org/active_record_validations.html

validates :name_of_attribute, presence: true

You can also prevent submission via js. If you're using erb it would look something like this:

<%= f.text_field, :name_of_attribute, required: true %>

This will prevent submission if the field is empty.

If you want to do it completely in the controller, write a method that checks presence of those fields you want and add a flash message instead of saving if those fields are blank.

You could optionally disable submit with javascript if at least one of those fields isn't selected. (or both)

Update on how to check for blank values. Blank will return true when an array is empty, empty string, nil values, etc. https://apidock.com/rails/Object/blank%3F

```<code>unless params[:user_ids].blank? || params[:role_ids].blank?
   # call to your create method
else
   # show the user an error message
end
</code>```

Body:
I have this Controller, where I can create User Group and add Users, Roles to it:

class Strongbolt::UserGroupsController < ApplicationController
# some code...

def create
  user_roles #Helper method
  respond_to do |format|
  if @user_group = Strongbolt::UserGroup.create!(user_group_params)
    format.json { head :no_content }
    format.js { flash.now[:notice] = "User group #{@user_group.name} created!" }
  else
    format.json { render json: @user_group.errors.full_messages,
                          status: :unprocessable_entity }
    end
  end
end

# some code...

def user_group_params
  params.require(:strongbolt_user_group)
        .permit(:name, :description, {user_ids: []}, {role_ids: []})
end

If user_ids and role_ids are empty, I need to do some error or stop Create action - I do not need User Group without at least one user and role. How do I do that, please?

Since this is related to Strongbolt gem where related Models are inside it, I cannot do validation on model side - I have to do it in Controller. At the moment this functionality is not there, so I have to add that for my project.

So far I've been trying to do something related tho this:

redirect_to 'new' unless params[:user_ids].present?

Update

Here is part of my Form:

    <%= f.collection_check_boxes(:user_ids, @users_for_group, :id, :name) do |b| %>

        <%= b.check_box %>

        <%= b.label %>

    <% end %>

      <%= f.collection_check_boxes(:role_ids, @roles, :id, :name) do |bb| %>

          <%= bb.check_box %>

          <%= bb.label %>

      <% end %>

Update 2

  def create
    user_roles #Helper method
    respond_to do |format|
      unless params[:user_ids].blank? || params[:role_ids].blank?
        @user_group = Strongbolt::UserGroup.create!(user_group_params)
        format.json { head :no_content }
        format.js { flash.now[:notice] = "User group #{@user_group.name} created!" }
      else
        format.json {
          render json: @user_group.errors.full_messages, status: :unprocessable_entity
        }
        format.js { flash.now[:error] = "User group was not created!" }
      end
    end
  end

In terminal I see this:

Started POST "/en/strongbolt/user_groups" for 10.0.2.2 at 2017-06-06 17:51:59 +0000
Processing by Strongbolt::UserGroupsController#create as JS
  Parameters: {"utf8"=>"✓", "strongbolt_user_group"=>{"name"=>"Test @Jun6 v2", "description"=>"test", "user_ids"=>["", "5"], "role_ids"=>["", "2"]}, "commit"=>"Create User Group", "locale"=>"en"}

The Solution

First of all it appears collection_check_boxes by default include hidden value " ", so I had to remove that with something like this:

<%= f.collection_check_boxes(:role_ids, @roles, :id, :name, include_hidden: false) do |bb| %>

If not to remove hidden field, Rails will not check empty params as basically params are there.

Then I was able to implement this:

before_action :validate_presence, only: [:create]

def check_presence
  params[:strongbolt_user_group][:user_ids].present? &&
  params[:strongbolt_user_group][:role_ids].present?
end

def validate_presence
  if !check_presence
    render json: { error: {
        message: "Bad Request, parameters missing.",
        status: 500 }
    }
  end
end

I had to include Model name to check params presence, otherwise it did not work. Now I can implement JS part where I show some messages that something can't be blank, etc., but that is different story. Now my Controller will not accept empty params in this special case with Strongbolt gem.

Body:
You can just add a validation. Read about them here: http://guides.rubyonrails.org/active_record_validations.html

validates :name_of_attribute, presence: true

You can also prevent submission via js. If you're using erb it would look something like this:

<%= f.text_field, :name_of_attribute, required: true %>

This will prevent submission if the field is empty.

If you want to do it completely in the controller, write a method that checks presence of those fields you want and add a flash message instead of saving if those fields are blank.

You could optionally disable submit with javascript if at least one of those fields isn't selected. (or both)

Update on how to check for blank values. Blank will return true when an array is empty, empty string, nil values, etc. https://apidock.com/rails/Object/blank%3F

unless params[:user_ids].blank? || params[:role_ids].blank?
   # call to your create method
else
   # show the user an error message
end


问:
How to redirect 404 error to 404.php page?
I need help in php. I am making one portal website in Core Php. I had created 404 page and .htaccess file.

404.php:

```<code><html>
  <head>
    <title>404 Error - Page Not Found</title>
  </head>
  <body>404 Error - Page Not Found!</body>
</html>
</code>```

.htaccess:

```<code>Redirect 404 /404.php
</code>```

But this is not working. If I use this code:

```<code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /404.html [L]
</IfModule>
</code>```

It shows internal server error.

Here is my website: http://jobguide.australianenglishcenter.com/

答:
You have to set the rewrite engine on. Then customize a php page to handle the 404 error. Refer the below code</p>

```<code>RewriteEngine on
ErrorDocument 404 http://www.example.com/your-404-custom-file-name.php
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need help in php. I am making one portal website in Core Php. I had created 404 page and .htaccess file.

404.php:

    <title>404 Error - Page Not Found</title>

  404 Error - Page Not Found!

.htaccess:

Redirect 404 /404.php

But this is not working. If I use this code:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /404.html [L]
</IfModule>

It shows internal server error.

Here is my website: http://jobguide.australianenglishcenter.com/

Body:
You have to set the rewrite engine on. Then customize a php page to handle the 404 error. Refer the below code

RewriteEngine on
ErrorDocument 404 http://www.example.com/your-404-custom-file-name.php


问:
How to run a programme inside a virtual environment from a script
I have set up the google assistant sdk on my Raspberry Pi as shown here: https://developers.google.com/assistant/sdk/prototype/getting-started-pi-python/run-sample

Now in order to re-run the assistant I have worked out the two commands are

```<code>$ source env/bin/activate
</code>```

and

```<code>(env) $ google-assistant-demo
</code>```

however I want to automate this process into a script that I can call from rc.local (followed by an &) in order to make the assistant boot from start up.

However if I run a simple script

```<code>#!/bin/bash
source env/bin/activate
google-assistant-demo
</code>```

the assistant does not run inside the environment
my environment path is /home/pi/env/bin/activate
How can I have it so the script starts the environment and then runs the assistant inside the virtual environment?

EDIT: In the end I went with the following method:

using this as a base :
https://youtu.be/ohUszBxuQA4?t=774 – thanks to Eric Parisot

You will need to download the src file he uses and extract its contents into /home/pi/src/

However with a few changes.

I did not run gassist.sh as sudo, as it gave me the following error:

```<code>OpenAlsaHandle PcmOpen: No such file or directory
[7689:7702:ERROR:audio_input_processor.cc(756)] Input error
ON_MUTED_CHANGED:
{‘is_muted’: False}
ON_START_FINISHED
ON_ASSISTANT_ERROR:
{‘is_fatal’: True}
[7689:7704:ERROR:audio_input_processor.cc(756)] Input error
ON_ASSISTANT_ERROR:
{‘is_fatal’: True}
</code>```

Fix: DO NOT run as sudo

If gassist.sh gives an error about RPi.GPIO you need to do https://youtu.be/ohUszBxuQA4?t=580:

```<code>$ cd /home/pi/env/bin
$ source activate
(env) $ pip install RPi.GPIO
(env) $ deactivate
</code>```

And then I did sudo nano /etc/profile
and the appended this to the end:

```<code>#Harvs was here on 24/06/17
if pidof -x "gassist.sh" >/dev/null; then
    echo ""
    echo "/etc/profile says:"
    echo "An instance of Google Assistant is already running, will not start again"
    echo ""
else
    echo "Starting Google Assistant..."
    echo "If you are seeing this, perhaps you have SSH within seconds of reboot"
    /home/pi/src/gassist.sh &
fi
</code>```

And now it works perfectly, and inside the virtual enviroment :)

答:
found solution here :https://raspberrypi.stackexchange.com/a/45089

Create a startup shell script in your root directory (I named mine "launch"), make it executable too :

```<code>sudo nano launch.sh
</code>```

I wrote it that way :

```<code>#!/bin/bash
source /home/pi/env/bin/activate
/home/pi/env/bin/google-assistant-demo
</code>```

Save the file

Edit the LXDE-pi autostart file

```<code>sudo nano /home/pi/.config/lxsession/LXDE-pi/autostart
</code>```

Add this to the bottom of that file

```<code>./launch.sh
</code>```

reboot

Body:
I have set up the google assistant sdk on my Raspberry Pi as shown here: https://developers.google.com/assistant/sdk/prototype/getting-started-pi-python/run-sample

Now in order to re-run the assistant I have worked out the two commands are

$ source env/bin/activate

and

(env) $ google-assistant-demo

however I want to automate this process into a script that I can call from rc.local (followed by an &) in order to make the assistant boot from start up.

However if I run a simple script

#!/bin/bash
source env/bin/activate
google-assistant-demo

the assistant does not run inside the environment
my environment path is /home/pi/env/bin/activate
How can I have it so the script starts the environment and then runs the assistant inside the virtual environment?

EDIT: In the end I went with the following method:

using this as a base :
https://youtu.be/ohUszBxuQA4?t=774 – thanks to Eric Parisot

You will need to download the src file he uses and extract its contents into /home/pi/src/

However with a few changes.

I did not run gassist.sh as sudo, as it gave me the following error:

OpenAlsaHandle PcmOpen: No such file or directory
[7689:7702:ERROR:audio_input_processor.cc(756)] Input error
ON_MUTED_CHANGED:
{‘is_muted’: False}
ON_START_FINISHED
ON_ASSISTANT_ERROR:
{‘is_fatal’: True}
[7689:7704:ERROR:audio_input_processor.cc(756)] Input error
ON_ASSISTANT_ERROR:
{‘is_fatal’: True}

Fix: DO NOT run as sudo

If gassist.sh gives an error about RPi.GPIO you need to do https://youtu.be/ohUszBxuQA4?t=580:

$ cd /home/pi/env/bin
$ source activate
(env) $ pip install RPi.GPIO
(env) $ deactivate

And then I did sudo nano /etc/profile
and the appended this to the end:

#Harvs was here on 24/06/17
if pidof -x "gassist.sh" >/dev/null; then
    echo ""
    echo "/etc/profile says:"
    echo "An instance of Google Assistant is already running, will not start again"
    echo ""
else
    echo "Starting Google Assistant..."
    echo "If you are seeing this, perhaps you have SSH within seconds of reboot"
    /home/pi/src/gassist.sh &
fi

And now it works perfectly, and inside the virtual enviroment :)

Body:
found solution here :https://raspberrypi.stackexchange.com/a/45089

Create a startup shell script in your root directory (I named mine "launch"), make it executable too :

sudo nano launch.sh

I wrote it that way :

#!/bin/bash
source /home/pi/env/bin/activate
/home/pi/env/bin/google-assistant-demo

Save the file

Edit the LXDE-pi autostart file

sudo nano /home/pi/.config/lxsession/LXDE-pi/autostart

Add this to the bottom of that file

./launch.sh

reboot


问:
Getting a href from a button
I'm trying to extract the href from certain buttons from this url (the buttons are located bellow the h4 "Ofertas Disponíveis".

These buttons have an onclick function called "updateJobModal(button_index)" but I can't locate the function.
At the end of the tag, an "ev" button appears to be related to JQuery.

How can I obtain the attribute in this case?

答:
this should get you started
function in:  https://www.iefp.pt/Jobs-portlet/js/job.js?browserId=other&minifierType=js

Specifically:

```<code>function updateJobModal(a){currentAjax=jobListAjax;updateCurrentJobModal(search_job_offers[a])}
</code>```

Title: Getting a href from a button

Body:
this should get you started
function in:  https://www.iefp.pt/Jobs-portlet/js/job.js?browserId=other&minifierType=js

Specifically:

function updateJobModal(a){currentAjax=jobListAjax;updateCurrentJobModal(search_job_offers[a])}


问:
How to scan a string with white spaces in structure members in C?
```<code>struct Demo{
   char a[50];
   char b[50];
   int a;
};
</code>```

Can anyone give the code for this structure Demo where a and b will contains string with different words[white-spaces].

I tried

scanf("[^\n]s",name.a); //where name is the object

fgets(name.a,50,stdin);

Note : we can't use gets method as well

So, If any other method is there, please provide me.

答:
To read a line of user input into char a[50]; with its potential trailing '\n' trimmed:

```<code>if (fgets(name.a, sizeof name.a, stdin)) {
  name.a[strcspn(name.a, "\n")] = '\0'; // trim \n
}
</code>```

Work is needed to cope with consuming excessive long input lines and using the last element of name.a[] such as:

```<code>// Alternative
if (scanf("%49[^\n]", name.a) == 1) {
  // consume trailing input
  int ch;
  while ((ch = fgetc(stdin)) != '\n' && ch != EOF) {
    ;
  }
} else {  // Handle lines of only \n, end-of-file or input error
  name.a[0] = '\0';
}
</code>```

The scanf("%49[^\n]%*c", name.a) approach has trouble in 2 cases:

1) The input is only "\n", nothing is saved in name.a and '\n' remains in stdin.

2) With input longer than 49 characters (aside from the '\n'), the %*c consumes an extra character, yet the rest of the long input line remains in stdin.

Both of these issues can be solves with additional code too.

Body:
struct Demo{
   char a[50];
   char b[50];
   int a;
};

Can anyone give the code for this structure Demo where a and b will contains string with different words[white-spaces].

I tried

scanf("[^\n]s",name.a); //where name is the object

fgets(name.a,50,stdin);

Note : we can't use gets method as well

So, If any other method is there, please provide me.

Body:
To read a line of user input into char a[50]; with its potential trailing '\n' trimmed:

if (fgets(name.a, sizeof name.a, stdin)) {
  name.a[strcspn(name.a, "\n")] = '\0'; // trim \n
}

Work is needed to cope with consuming excessive long input lines and using the last element of name.a[] such as:

// Alternative
if (scanf("%49[^\n]", name.a) == 1) {
  // consume trailing input
  int ch;
  while ((ch = fgetc(stdin)) != '\n' && ch != EOF) {
    ;
  }
} else {  // Handle lines of only \n, end-of-file or input error
  name.a[0] = '\0';
}

The scanf("%49[^\n]%*c", name.a) approach has trouble in 2 cases:

1) The input is only "\n", nothing is saved in name.a and '\n' remains in stdin.

2) With input longer than 49 characters (aside from the '\n'), the %*c consumes an extra character, yet the rest of the long input line remains in stdin.

Both of these issues can be solves with additional code too.


问:
Creating a radio button list on the fly
I almost have this working but one thing I cant quite figure out:
What I'm trying to do is create a radio button list on the fly. However, when I do this it creates a radio box each time so all my answers can be selected. How can I create one input, that has 4 options so that I can only select one instead of them all?</p>

```<code>function questionAnswers() {
  let arr = Object.values(questionList[i].answers)
  for (var a in arr){
    let checkbox = document.createElement('input')
    let label = document.createElement('label')
    label.appendChild(document.createTextNode(arr[a]))
    checkbox.type = 'radio';
    answerSection.appendChild(checkbox);
    answerSection.appendChild(label)
  }
}
</code>```

答:
Assigning the same name to two or more radios groups them:

function questionAnswers() {
  let arr = ["shark","tiger","lion"];
  let answerSection=document.body;
  for (var a in arr){
    let checkbox = document.createElement('input')
    let label = document.createElement('label')
    label.appendChild(document.createTextNode(arr[a]))
    checkbox.type = 'radio';
    checkbox.name="animal";
    answerSection.appendChild(checkbox);
    answerSection.appendChild(label)
  }
}

window.onload=questionAnswers;```
</div>
</div>
</p>

<p>If you have multiple radios, you may assign random names, like:</p>

```var randname=""+Math.floor(Math.random()*10000);
```

Title: Creating a radio button list on the fly

Body:
I almost have this working but one thing I cant quite figure out:
What I'm trying to do is create a radio button list on the fly. However, when I do this it creates a radio box each time so all my answers can be selected. How can I create one input, that has 4 options so that I can only select one instead of them all?

function questionAnswers() {
  let arr = Object.values(questionList[i].answers)
  for (var a in arr){
    let checkbox = document.createElement('input')
    let label = document.createElement('label')
    label.appendChild(document.createTextNode(arr[a]))
    checkbox.type = 'radio';
    answerSection.appendChild(checkbox);
    answerSection.appendChild(label)
  }
}

Body:
Assigning the same name to two or more radios groups them:

function questionAnswers() {
  let arr = ["shark","tiger","lion"];
  let answerSection=document.body;
  for (var a in arr){
    let checkbox = document.createElement('input')
    let label = document.createElement('label')
    label.appendChild(document.createTextNode(arr[a]))
    checkbox.type = 'radio';
    checkbox.name="animal";
    answerSection.appendChild(checkbox);
    answerSection.appendChild(label)
  }
}

window.onload=questionAnswers;

If you have multiple radios, you may assign random names, like:

var randname=""+Math.floor(Math.random()*10000);


问:
Neo4j and parameterized queries
I'm looking into using Neo4j for a project, but I'm a bit confused when it comes to best practices. I would normally assume that the official C# driver provides a method of parameterizing queries, but I can't see anything in the official documentation.

There is what appears to be an unofficial library for C# located on Github with a recent release only a few days old which supports parameterized queries. However, I also remember seeing a comment stating that it mostly supports version 2.x (although I can't find the page stating this). This library only supports http+https as connection methods, there is no support for Bolt. What effect will this have on performance?

What is the preferred driver/library for Neo4j 3.x using C#?

答:
Neo4jClient (The community driver) does in it's current state not support Bolt, there is a beta pre-release version (which you can get using Nuget by adding https://www.myget.org/F/cskardon/api/v3/index.json as a source to your Nuget) - I'm reasonably confident with it, but it does need testing.

It Will support Bolt though.

The official driver does support paramaterized queries you just have to code it yourself and when you call session.Run you pass it in as the second argument.

Something like:

```<code>var obj = new Dictionary<string, object> { {"Name", "Chris"}, {"Email", "a@a.com"} }

var paramsObj = new Dictionary<string, object> { { "userParam", obj } };

session.Run("CREATE (n:User {userParam})", paramsObj);
</code>```

The official driver is supported by Neo4j, the community uses the official driver under the hood for bolt, wrapping up the OGM stuff, so the choice is yours from a Bolt point of view. If you need to use HTTP/HTTPS - you have to use Neo4jClient (which will work with 3.x DBs as well)

Title: Neo4j and parameterized queries

Body:
Neo4jClient (The community driver) does in it's current state not support Bolt, there is a beta pre-release version (which you can get using Nuget by adding https://www.myget.org/F/cskardon/api/v3/index.json as a source to your Nuget) - I'm reasonably confident with it, but it does need testing.

It Will support Bolt though.

The official driver does support paramaterized queries you just have to code it yourself and when you call session.Run you pass it in as the second argument.

Something like:

var obj = new Dictionary<string, object> { {"Name", "Chris"}, {"Email", "a@a.com"} }

var paramsObj = new Dictionary<string, object> { { "userParam", obj } };

session.Run("CREATE (n:User {userParam})", paramsObj);

The official driver is supported by Neo4j, the community uses the official driver under the hood for bolt, wrapping up the OGM stuff, so the choice is yours from a Bolt point of view. If you need to use HTTP/HTTPS - you have to use Neo4jClient (which will work with 3.x DBs as well)


问:
How to pass data from sub-view to main-view in Angular 2?
I have two buttons on the main view: Login and Logout. Initially only Login button is shown:

...

```<code><button type="button" routerLink="/login" routerLinkActive="active" class="btn btn-info">Login</button>
<button type="button" routerLink="/showlist" routerLinkActive="active" class="btn btn-info" (click)="logout()">Logout</button>

<router-outlet></router-outlet>
</code>```

Login button will display a sub-view, once user is authenticated there, I want to pass the result back to main view, if user is authenticated, I want to hide the 'Login' button and show the 'Logout' button.

How can I pass the data from a sub-view back to main view via 'router-outlet'?

答:
To show and hide the button you will use the *ngif structural directive like:

```<code><button *ngIf="!loggedIn" type="button" routerLink="/login" routerLinkActive="active" class="btn btn-info">Login</button>
<button *ngIf="loggedIn" type="button" routerLink="/showlist" routerLinkActive="active" class="btn btn-info" (click)="logout()">Logout</button>
</code>```

The loggedIn should be a boolean in your component associated with the main-view.
I suppose that with the term main-view and sub-view you mean that you have a parent-component and a child-component (for the authentication) form respectively. If this is the case refer to Component Interaction and select the communication that fits you best.

Body:
I have two buttons on the main view: Login and Logout. Initially only Login button is shown:

...

<button type="button" routerLink="/login" routerLinkActive="active" class="btn btn-info">Login</button>
<button type="button" routerLink="/showlist" routerLinkActive="active" class="btn btn-info" (click)="logout()">Logout</button>

<router-outlet></router-outlet>

Login button will display a sub-view, once user is authenticated there, I want to pass the result back to main view, if user is authenticated, I want to hide the 'Login' button and show the 'Logout' button.

How can I pass the data from a sub-view back to main view via 'router-outlet'?

Body:
To show and hide the button you will use the *ngif structural directive like:

<button *ngIf="!loggedIn" type="button" routerLink="/login" routerLinkActive="active" class="btn btn-info">Login</button>
<button *ngIf="loggedIn" type="button" routerLink="/showlist" routerLinkActive="active" class="btn btn-info" (click)="logout()">Logout</button>

The loggedIn should be a boolean in your component associated with the main-view.
I suppose that with the term main-view and sub-view you mean that you have a parent-component and a child-component (for the authentication) form respectively. If this is the case refer to Component Interaction and select the communication that fits you best.


问:
Epub or Mobi Sdk for xamarin
I am thinking of developing Ebook reader in xamarin forms. But I could not find any Epub/Mobi reader SDK anywhere.Is there any xmarin SDK available for Ebook reader ? If it is not available , How can I develop one in xamarin ?</p>

答:
I have made a port of EpubReader for PCL projects: EpubReader.Cross.
It has almost same api except you need to use streams instead paths to files.
You can download the library as a package from Nuget: Install-Package EpubReader.Cross

For opening a book without loading content:

```<code>var epubBook = EpubReader.OpenBook(stream);
</code>```

For reading a book:

```<code>var epubBook = EpubReader.ReadBook(stream);
</code>```

Title: Epub or Mobi Sdk for xamarin

Body:
I have made a port of EpubReader for PCL projects: EpubReader.Cross.
It has almost same api except you need to use streams instead paths to files.
You can download the library as a package from Nuget: Install-Package EpubReader.Cross

For opening a book without loading content:

var epubBook = EpubReader.OpenBook(stream);

For reading a book:

var epubBook = EpubReader.ReadBook(stream);


问:
Vue.js raise an error when view data in wrong case
I have the following template:

```<code><template>
<div>
    <h1>Users from SQL Server!</h1>

    <p>This component demonstrates fetching data from the server.</p>

    <table v-if="userlist.length" class="table">
        <thead>
            <tr>
                <th>Id</th>
                <th>First</th>
                <th>Last</th>
                <th>Date</th>
            </tr>
        </thead>
        <tbody>
        <!-- nb: These items must match the case they are passed in with (the Json passed back from .net Core serialises to lowerCamelCase) otherwise they will
            show nothing and no error is raised! -->
        <tr v-for="item in userlist">
            <td>{{ item.userid }}</td>
            <td>{{ item.firstname }}</td>
            <td>{{ item.lastname }}</td>
            <td>{{ item.createdonDate }}</td>
        </tr>
        </tbody>
    </table>

    <p v-else><em>Loading...</em></p>
</div>
</code>```

This displays a table with no data. This is because the data passed in from the server has a different case to that used in the template items. If I fix them for example:

```<code>item.userId
item.firstName
item.lastName
item.createdOnDate
</code>```

Then it works and data is displayed. The issue for me is that no error is returned. I am learning Vue using the .Net Core SPA template as a starter. But it took me a while to realise what I was doing wrong. If this was a model in the razor view it would have blown with a helpful error.

Is there a way to raise an error for this kind of thing?

I do have the Chrome Vue extension installed and realised the problem when I looked at the data there. But I was stumped for a while.

UPDATE 1:  Thanks @ndpu for your solution but I am having trouble fitting it into my project.  I have a boot.ts file like this:

```<code>import 'bootstrap';
import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use((VueRouter) as any);

Vue.config.devtools = true;

const routes = [
{ path: '/', component: require('./components/home/home.vue.html') },
{ path: '/counter', component:
require('./components/counter/counter.vue.html') },
{ path: '/fetchdata', component:
require('./components/fetchdata/fetchdata.vue.html') },
{ path: '/users', component: require('./components/users/users.vue.html') },
{ path: '/user', component: require('./components/user/user.vue.html') }
];

new Vue({
    el: '#app-root',
    router: new VueRouter({ mode: 'history', routes: routes }),
    render: h => h(require('./components/app/app.vue.html'))
});
</code>```

Where do I put the Object.prototype.safeGet? In there or in my component templates? Nowhere seems to work.

UPDATE 2:

I got it to work by putting the code from @ndpu into app.ts like this:

```<code>import Vue from "vue";
import { Component } from 'vue-property-decorator';

@Component({
    components: {
        MenuComponent: require('../navmenu/navmenu.vue.html')
    }
})
export default class AppComponent extends Vue {
}

Object.defineProperty(Object.prototype, 'safeGet', {
    get: function () {
        return this;
    }
});
</code>```

答:
Simplest way: define additional property to Object with getter that will only return himself.

```<code>/* eslint no-extend-native: ["error", { "exceptions": ["Object"] }] */

Object.defineProperty(Object.prototype, 'safeGet', {
    get: function () {
        return this;
    }
});
</code>```

So, by adding safeGet to any data attribute, you can be sure that you will get TypeError if attribute is undefined:

this:

```<code><td>{{ item.userid.safeGet }}</td>
</code>```

will produce exception (if actual property name is userId):

```<code>TypeError: Cannot read property 'safeGet' of undefined
</code>```

FIDDLE: http://jsfiddle.net/yMv7y/2785/

Also, you can define simple method in object prototype to check property existence:

UPDATE: i couldn't make it work in 'complex' application with modules, webpack etc - vue trying to make added to Object.prototope method reactive. Didnt know why it is work in simple case like in applied fiddle.

```<code>Object.prototype.safeGet = function() {
    var val, args = Array.prototype.slice.call(arguments);
    var currLvlObj = this;
    for (var i=0; i < args.length; i++) {
        val = currLvlObj = currLvlObj? currLvlObj[args[i]] : undefined;
        if (val === undefined)  {
            throw Error('property with name ' + args[i] + ' is undefined');
        }
    }
    return val;
}
</code>```

and use it like this:

```<code><td>{{ item.safeGet('userid') }}</td>
</code>```

this call should throw error (if actual property name is userId): Error: property with name userid is undefined

PS: nested objects properties can be accessed by passing all property names as arguments. For example, to access 'userId' in {'data': {'userId': 0}}:

```<code><td>{{ item.safeGet('data', 'userid') }}</td>
</code>```

FIDDLE: http://jsfiddle.net/yMv7y/2778/

Body:
I have the following template:

<template>

Users from SQL Server!

This component demonstrates fetching data from the server.

                Id
                First
                Last
                Date

            {{ item.userid }}
            {{ item.firstname }}
            {{ item.lastname }}
            {{ item.createdonDate }}

Loading...

This displays a table with no data. This is because the data passed in from the server has a different case to that used in the template items. If I fix them for example:

item.userId
item.firstName
item.lastName
item.createdOnDate

Then it works and data is displayed. The issue for me is that no error is returned. I am learning Vue using the .Net Core SPA template as a starter. But it took me a while to realise what I was doing wrong. If this was a model in the razor view it would have blown with a helpful error.

Is there a way to raise an error for this kind of thing?

I do have the Chrome Vue extension installed and realised the problem when I looked at the data there. But I was stumped for a while.

UPDATE 1:  Thanks @ndpu for your solution but I am having trouble fitting it into my project.  I have a boot.ts file like this:

import 'bootstrap';
import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use((VueRouter) as any);

Vue.config.devtools = true;

const routes = [
{ path: '/', component: require('./components/home/home.vue.html') },
{ path: '/counter', component:
require('./components/counter/counter.vue.html') },
{ path: '/fetchdata', component:
require('./components/fetchdata/fetchdata.vue.html') },
{ path: '/users', component: require('./components/users/users.vue.html') },
{ path: '/user', component: require('./components/user/user.vue.html') }
];

new Vue({
    el: '#app-root',
    router: new VueRouter({ mode: 'history', routes: routes }),
    render: h => h(require('./components/app/app.vue.html'))
});

Where do I put the Object.prototype.safeGet? In there or in my component templates? Nowhere seems to work.

UPDATE 2:

I got it to work by putting the code from @ndpu into app.ts like this:

import Vue from "vue";
import { Component } from 'vue-property-decorator';

@Component({
    components: {
        MenuComponent: require('../navmenu/navmenu.vue.html')
    }
})
export default class AppComponent extends Vue {
}

Object.defineProperty(Object.prototype, 'safeGet', {
    get: function () {
        return this;
    }
});

Body:
Simplest way: define additional property to Object with getter that will only return himself.

/* eslint no-extend-native: ["error", { "exceptions": ["Object"] }] */

Object.defineProperty(Object.prototype, 'safeGet', {
    get: function () {
        return this;
    }
});

So, by adding safeGet to any data attribute, you can be sure that you will get TypeError if attribute is undefined:

this:

<td>{{ item.userid.safeGet }}</td>

will produce exception (if actual property name is userId):

TypeError: Cannot read property 'safeGet' of undefined

FIDDLE: http://jsfiddle.net/yMv7y/2785/

Also, you can define simple method in object prototype to check property existence:

UPDATE: i couldn't make it work in 'complex' application with modules, webpack etc - vue trying to make added to Object.prototope method reactive. Didnt know why it is work in simple case like in applied fiddle.

Object.prototype.safeGet = function() {
    var val, args = Array.prototype.slice.call(arguments);
    var currLvlObj = this;
    for (var i=0; i < args.length; i++) {
        val = currLvlObj = currLvlObj? currLvlObj[args[i]] : undefined;
        if (val === undefined)  {
            throw Error('property with name ' + args[i] + ' is undefined');
        }
    }
    return val;
}

and use it like this:

<td>{{ item.safeGet('userid') }}</td>

this call should throw error (if actual property name is userId): Error: property with name userid is undefined

PS: nested objects properties can be accessed by passing all property names as arguments. For example, to access 'userId' in {'data': {'userId': 0}}:

<td>{{ item.safeGet('data', 'userid') }}</td>

FIDDLE: http://jsfiddle.net/yMv7y/2778/


问:
How to make DebugView work under .NET 4?
SysInternals' DebugView no longer works if used under .NET 4. Some research indicated that the new architecture of the framework did not allow for traces to be captured if a debugger was attached; in my case it's the Visual Studio debugger. Changing target framework from 4 to 3.5 makes it work again.

Anybody knows a way of getting DebugView to work under .NET 4 while having the Visual Studio debugger attached? I tried clearing the Listeners collection of the Trace class, but no luck.

答:
.NET trace messages are emitted using the OutputDebugString function in the Windows kernel. This function, as documented in MSDN,

sends a string to the debugger for display.

Obviously, a native debugger will receive this message. This is meant by the remark that this behavior is by design. The reason the messages were passed on to other listeners such as DebugView before .NET 4.0 is that Visual Studio did not debug .NET code as a "native" debugger; DebugView has never worked when a native debugger is attached.

A workaround could be to add a TraceListener that forwards all messages to another process that has no debugger attached. The communication could be realized using any IPC mechanism. The following is a sample using TCP sockets.

Server Application

This would be a simple stand-alone command line program that gets started and stopped automatically by the TraceListener class:

```<code>using System;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        if (args.Length != 1)
        {
            Console.WriteLine("Usage: DebugOutputListener.exe <port>");
            return;
        }
        TcpListener server = null;
        try
        {
            Int32 port = Convert.ToInt32(args[0]);
            IPAddress localAddr = IPAddress.Parse("127.0.0.1");

            server = new TcpListener(localAddr, port);
            server.Start();

            while (true)
            {
                Console.Write("Waiting for a connection... ");

                using (TcpClient client = server.AcceptTcpClient())
                {
                    using (NetworkStream stream = client.GetStream())
                    {

                        byte[] bufferLength = new byte[4];
                        stream.Read(bufferLength, 0, 4);
                        int length = BitConverter.ToInt32(bufferLength, 0);

                        if (length == -1)
                        {
                            // close message received
                            Trace.WriteLine("DebugOutputListener is closing.");
                            return;
                        }

                        byte[] bufferMessage = new byte[length];
                        stream.Read(bufferMessage, 0, length);

                        string msg = Encoding.UTF8.GetString(bufferMessage);
                        Trace.WriteLine(msg);
                    }
                }
            }
        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException: {0}", e);
        }
        finally
        {
            server.Stop();
        }
    }
}
</code>```

TraceListener

```<code>using System;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class DebugOutputTraceListener : TraceListener
{
    private IPEndPoint ipEndPoint;
    private bool needsDisposing;

    public DebugOutputTraceListener(string debugOutputListenerPath, int port)
    {
        this.ipEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 13000);

        // start the process that forwards the trace messages
        var psi = new ProcessStartInfo()
        {
            FileName = debugOutputListenerPath,
            Arguments = port.ToString(),
            CreateNoWindow = true,
            UseShellExecute = false
        };
        Process.Start(psi);
        needsDisposing = true;
    }

    ~DebugOutputTraceListener()
    {
        Dispose(false);
    }

    public override void Write(string message)
    {
        sendMessage(message);
    }

    public override void WriteLine(string message)
    {
        sendMessage(message + Environment.NewLine);
    }

    private void sendMessage(string message)
    {
        try
        {
            using (TcpClient client = new TcpClient())
            {
                client.Connect(ipEndPoint);
                byte[] bufferMessage = Encoding.UTF8.GetBytes(message);
                byte[] bufferLength =
                    BitConverter.GetBytes(bufferMessage.Length);

                using (NetworkStream stream = client.GetStream())
                {
                    stream.Write(bufferLength, 0, bufferLength.Length);
                    stream.Write(bufferMessage, 0, bufferMessage.Length);
                }
            }
        }
        catch (SocketException e)
        {
            Trace.WriteLine(e.ToString());
        }
    }

    /// <summary>
    /// Sends -1 to close the TCP listener server.
    /// </summary>
    private void sendCloseMessage()
    {
        try
        {
            using (TcpClient client = new TcpClient())
            {
                client.Connect(ipEndPoint);
                byte[] buffer = BitConverter.GetBytes(-1);

                using (NetworkStream stream = client.GetStream())
                {
                    stream.Write(buffer, 0, buffer.Length);
                }
            }
        }
        catch (SocketException e)
        {
            Trace.WriteLine(e.ToString());
        }
    }

    public override void Close()
    {
        sendCloseMessage();
        needsDisposing = false;
        base.Close();
    }

    protected override void Dispose(bool disposing)
    {
        if (needsDisposing)
        {
            sendCloseMessage();
            needsDisposing = false;
        }
        base.Dispose(disposing);
    }
}
</code>```

Usage

```<code>public class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        // using Debug; start a listener process on port 13000
        Debug.Listeners.Add(
            new DebugOutputTraceListener("DebugOutputListener.exe", 13000));
        Debug.WriteLine("A debug message.");

        // using Trace; start a listener process on port 13001
        Trace.Listeners.Add(
            new DebugOutputTraceListener("DebugOutputListener.exe", 13001));
        Trace.WriteLine("A trace message");
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
.NET trace messages are emitted using the OutputDebugString function in the Windows kernel. This function, as documented in MSDN,

sends a string to the debugger for display.

Obviously, a native debugger will receive this message. This is meant by the remark that this behavior is by design. The reason the messages were passed on to other listeners such as DebugView before .NET 4.0 is that Visual Studio did not debug .NET code as a "native" debugger; DebugView has never worked when a native debugger is attached.

A workaround could be to add a TraceListener that forwards all messages to another process that has no debugger attached. The communication could be realized using any IPC mechanism. The following is a sample using TCP sockets.

Server Application

This would be a simple stand-alone command line program that gets started and stopped automatically by the TraceListener class:

using System;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        if (args.Length != 1)
        {
            Console.WriteLine("Usage: DebugOutputListener.exe <port>");
            return;
        }
        TcpListener server = null;
        try
        {
            Int32 port = Convert.ToInt32(args[0]);
            IPAddress localAddr = IPAddress.Parse("127.0.0.1");

            server = new TcpListener(localAddr, port);
            server.Start();

            while (true)
            {
                Console.Write("Waiting for a connection... ");

                using (TcpClient client = server.AcceptTcpClient())
                {
                    using (NetworkStream stream = client.GetStream())
                    {

                        byte[] bufferLength = new byte[4];
                        stream.Read(bufferLength, 0, 4);
                        int length = BitConverter.ToInt32(bufferLength, 0);

                        if (length == -1)
                        {
                            // close message received
                            Trace.WriteLine("DebugOutputListener is closing.");
                            return;
                        }

                        byte[] bufferMessage = new byte[length];
                        stream.Read(bufferMessage, 0, length);

                        string msg = Encoding.UTF8.GetString(bufferMessage);
                        Trace.WriteLine(msg);
                    }
                }
            }
        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException: {0}", e);
        }
        finally
        {
            server.Stop();
        }
    }
}

TraceListener

using System;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class DebugOutputTraceListener : TraceListener
{
    private IPEndPoint ipEndPoint;
    private bool needsDisposing;

    public DebugOutputTraceListener(string debugOutputListenerPath, int port)
    {
        this.ipEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 13000);

        // start the process that forwards the trace messages
        var psi = new ProcessStartInfo()
        {
            FileName = debugOutputListenerPath,
            Arguments = port.ToString(),
            CreateNoWindow = true,
            UseShellExecute = false
        };
        Process.Start(psi);
        needsDisposing = true;
    }

    ~DebugOutputTraceListener()
    {
        Dispose(false);
    }

    public override void Write(string message)
    {
        sendMessage(message);
    }

    public override void WriteLine(string message)
    {
        sendMessage(message + Environment.NewLine);
    }

    private void sendMessage(string message)
    {
        try
        {
            using (TcpClient client = new TcpClient())
            {
                client.Connect(ipEndPoint);
                byte[] bufferMessage = Encoding.UTF8.GetBytes(message);
                byte[] bufferLength =
                    BitConverter.GetBytes(bufferMessage.Length);

                using (NetworkStream stream = client.GetStream())
                {
                    stream.Write(bufferLength, 0, bufferLength.Length);
                    stream.Write(bufferMessage, 0, bufferMessage.Length);
                }
            }
        }
        catch (SocketException e)
        {
            Trace.WriteLine(e.ToString());
        }
    }

    /// <summary>
    /// Sends -1 to close the TCP listener server.
    /// </summary>
    private void sendCloseMessage()
    {
        try
        {
            using (TcpClient client = new TcpClient())
            {
                client.Connect(ipEndPoint);
                byte[] buffer = BitConverter.GetBytes(-1);

                using (NetworkStream stream = client.GetStream())
                {
                    stream.Write(buffer, 0, buffer.Length);
                }
            }
        }
        catch (SocketException e)
        {
            Trace.WriteLine(e.ToString());
        }
    }

    public override void Close()
    {
        sendCloseMessage();
        needsDisposing = false;
        base.Close();
    }

    protected override void Dispose(bool disposing)
    {
        if (needsDisposing)
        {
            sendCloseMessage();
            needsDisposing = false;
        }
        base.Dispose(disposing);
    }
}

Usage

public class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        // using Debug; start a listener process on port 13000
        Debug.Listeners.Add(
            new DebugOutputTraceListener("DebugOutputListener.exe", 13000));
        Debug.WriteLine("A debug message.");

        // using Trace; start a listener process on port 13001
        Trace.Listeners.Add(
            new DebugOutputTraceListener("DebugOutputListener.exe", 13001));
        Trace.WriteLine("A trace message");
    }
}


答:
Give same name to all the radio buttons.

function questionAnswers() {
  let arr = Object.values(questionList[i].answers)
  for (var a in arr){
    let checkbox = document.createElement('input')
    let label = document.createElement('label')
    label.appendChild(document.createTextNode(arr[a]))
    checkbox.type = 'radio';
    checkbox.name = "myradio";
    answerSection.appendChild(checkbox);
    answerSection.appendChild(label)
  }
}```

Title: Creating a radio button list on the fly


问:
How to get image from RichEditBox
I have a RichEditBox in which I have already inserted an image through code. Now, I want to get the inserted image after some process.
Is there any way to get image from RichEditBox?
Any help would be greatly appreciated!!</p>

答:
I found two old question here that may help you.

Extracting images from RichTextBox

Extract Embedded Image Object in RTF

Title: How to get image from RichEditBox


问:
How do I specify URL resolution in python's requests library in a similar fashion to curl's --resolve flag?
I am writing some python client code and, due to some environmental constraints, I want to specify a URL and also control how it is resolved. I can accomplish this with curl by using the --resolve flag. Is there a way to do something similar with Python's requests library?

Ideally this would work in Python 2.7 but I can make a 3.x solution work as well.

答:
Looks like the easiest route is to use this package: https://github.com/requests/requests-kerberos

use the routable name and set the hostname_override value to be the name that Kerberos expects.


问:
Matplotlib - plot wont show up
I want to plot a function graph (using matplotlib) when a button is pressed, to do so I wrote the following code:

```<code>##--IMPORT
#Tkinter
from tkinter import Tk, ttk
from tkinter import Frame, LabelFrame, Button
from tkinter import FALSE
#Numpy
from numpy import linspace
#Sympy
from sympy import symbols,sympify,diff,N,log
#MathPlotLib
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure

_x = symbols("x")
_sympyFunction = None
_SP_mainSubPlot = None

def pr_draw(plotToDrawTo):

    _sympyFunction = sympify("log(x) + x")
    valuesRange = linspace(0.01, 3, 100)

    x = []
    y = []

    #Calculate y and x values
    for i in range(0, len(valuesRange)):
        tempValue = N(_sympyFunction.subs(_x,valuesRange[i]))

        x.append(float(valuesRange[i]))
        y.append(float(tempValue))

    #Draw function graph
    plotToDrawTo.plot(x,y)

##--MAIN
if __name__== "__main__":

    _root = Tk()
    _root.title("Grafico Approsimativo")
    _root.resizable(width = FALSE, height = FALSE)

    _mainFrame = Frame(_root, bg = "black")
    _mainFrame.pack(fill = "both", expand = True)

    #Frames
    #Main Left
    _F_LeftMainFrame = Frame(_mainFrame)
    _F_LeftMainFrame.grid(row = 0, column = 0, sticky = "nw")

    _F_RightMainFrame = Frame(_mainFrame, bg = "violet")
    _F_RightMainFrame.grid(row = 0, column = 2, sticky = "ne")

    #Left Content--------------------------
    _B_calculate = Button(_F_LeftMainFrame, text = "Draw", command = lambda: pr_draw(_SP_mainSubPlot))
    _B_calculate.grid(row = 0, column = 0, padx = 5, pady = 5, sticky = "w")

    #Right Content--------------------------
    _F_mainPlotWindow = Figure(figsize = None, dpi = 100)

    _SP_mainSubPlot = _F_mainPlotWindow.add_subplot(111)
    _SP_mainSubPlot.grid(True)

    #HERE

    #Set master frame for Figure Obj
    canvas = FigureCanvasTkAgg(_F_mainPlotWindow, master = _F_RightMainFrame)
    canvas.get_tk_widget().pack()
</code>```

The problem here is that when the button is pressed, nothing shows up in the plot window, the only way I could get this to work is by calling pr_draw(_SP_mainSubPlot) where I inserted the #HERE line: If the function is called there it will work, but not from the button., why?

答:
You would need to redraw the canvas after you have plotted to it.

Adding the line

```<code>plotToDrawTo.figure.canvas.draw_idle()
</code>```

at the end of your pr_draw function should do that.

Note that I also had to add _root.mainloop() at the end of the script to actually show the window.

Title: Matplotlib - plot wont show up

Body:
I want to plot a function graph (using matplotlib) when a button is pressed, to do so I wrote the following code:

##--IMPORT
#Tkinter
from tkinter import Tk, ttk
from tkinter import Frame, LabelFrame, Button
from tkinter import FALSE
#Numpy
from numpy import linspace
#Sympy
from sympy import symbols,sympify,diff,N,log
#MathPlotLib
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure

_x = symbols("x")
_sympyFunction = None
_SP_mainSubPlot = None

def pr_draw(plotToDrawTo):

    _sympyFunction = sympify("log(x) + x")
    valuesRange = linspace(0.01, 3, 100)

    x = []
    y = []

    #Calculate y and x values
    for i in range(0, len(valuesRange)):
        tempValue = N(_sympyFunction.subs(_x,valuesRange[i]))

        x.append(float(valuesRange[i]))
        y.append(float(tempValue))

    #Draw function graph
    plotToDrawTo.plot(x,y)

##--MAIN
if __name__== "__main__":

    _root = Tk()
    _root.title("Grafico Approsimativo")
    _root.resizable(width = FALSE, height = FALSE)

    _mainFrame = Frame(_root, bg = "black")
    _mainFrame.pack(fill = "both", expand = True)

    #Frames
    #Main Left
    _F_LeftMainFrame = Frame(_mainFrame)
    _F_LeftMainFrame.grid(row = 0, column = 0, sticky = "nw")

    _F_RightMainFrame = Frame(_mainFrame, bg = "violet")
    _F_RightMainFrame.grid(row = 0, column = 2, sticky = "ne")

    #Left Content--------------------------
    _B_calculate = Button(_F_LeftMainFrame, text = "Draw", command = lambda: pr_draw(_SP_mainSubPlot))
    _B_calculate.grid(row = 0, column = 0, padx = 5, pady = 5, sticky = "w")

    #Right Content--------------------------
    _F_mainPlotWindow = Figure(figsize = None, dpi = 100)

    _SP_mainSubPlot = _F_mainPlotWindow.add_subplot(111)
    _SP_mainSubPlot.grid(True)

    #HERE

    #Set master frame for Figure Obj
    canvas = FigureCanvasTkAgg(_F_mainPlotWindow, master = _F_RightMainFrame)
    canvas.get_tk_widget().pack()

The problem here is that when the button is pressed, nothing shows up in the plot window, the only way I could get this to work is by calling pr_draw(_SP_mainSubPlot) where I inserted the #HERE line: If the function is called there it will work, but not from the button., why?

Body:
You would need to redraw the canvas after you have plotted to it.

Adding the line

plotToDrawTo.figure.canvas.draw_idle()

at the end of your pr_draw function should do that.

Note that I also had to add _root.mainloop() at the end of the script to actually show the window.


问:
Firefox display=block problem
I have a the following HTML

```<code> <a id="rptQuestions_ctl01_hlQuestion" onclick="rptQuestions_ctl01_pnlAnswer.style.display = rptQuestions_ctl01_pnlAnswer.style.display == 'none'? 'block' : 'none';" href="javascript:">Header Link</a>

            <div id="rptQuestions_ctl01_pnlAnswer" style="display:none;">

            My Text to display

</div>
</code>```

This works as i would expect in IE8, where it displays the div when you click the header link, and then hides it when clicking the header link again. However, in Firefox, nothing happens when i click the header link.
I'm assuming this is to do with IE being forgiving of an error i have made, and Firefox sticking to the rules, but i can't see what i am doing wrong.
Any ideas?

--- EDIT

I've tried this with the following code and it works fine:

```<code>        <a id="rptQuestions_ctl01_hlQuestion" onclick="jasvascript:document.getElementById('rptQuestions_ctl01_pnlAnswer').style.display='block';" href="#">My header Link</a>

            <div id="rptQuestions_ctl01_pnlAnswer" style="display:none;">
My Text

</div>
</code>```

so it seems the problem is the ternary operator not working correctly.
Anyone see the problem?

答:
First and most important. USE: document.getElementById("the id to use.");

Second. Try using a javascript method to achieve this. and use a function in the onclick, or do an assignation directly on <script type="text/javascript"></script>
Something like this: document.getElementById("rptQuestions_ctl01_hlQuestion").onclick = function(){ document.getElementById('rptQuestions_ctl01_pnlAnswer').style.display = rptQuestions_ctl01_pnlAnswer.style.display == 'none' ? 'block' : 'none'; }

Title: Firefox display=block problem

Body:
I have a the following HTML

 Header Link

            My Text to display

This works as i would expect in IE8, where it displays the div when you click the header link, and then hides it when clicking the header link again. However, in Firefox, nothing happens when i click the header link.
I'm assuming this is to do with IE being forgiving of an error i have made, and Firefox sticking to the rules, but i can't see what i am doing wrong.
Any ideas?

--- EDIT

I've tried this with the following code and it works fine:

        My header Link

My Text

so it seems the problem is the ternary operator not working correctly.
Anyone see the problem?


问:
Difference in implementation between calling malloc() vs "operator new" function in C++
The thread here answers the question about the difference between the two: diff-between-malloc-operatornew

What I'm interested to know is: does one use the other? I suspect "operator new" function calls malloc in some form, but I may be way off. Anyone knows the implementation with say gcc?

答: It is the normally and customary practice for the default implementation of new to call malloc. However, there is no requirement that it do so. I have seen default new implementations that do not call malloc.</p>


问:
Promise not resolved correctly when routing
So basically I am using resolve in $routeProvider in order to get my current user's information before I instantiate the controller.
This is how I do it:

```<code>userMan.config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/userManagement', {
        templateUrl: 'userManagement/userManagement.html',
        controller: 'userManCtrl',
        resolve: {
            myUser:function($http){
                console.log("I am about to make the call");
                $http.get("/irods-cloud-backend/searchByMetadata/getCurrentUser").then( function( result ) {
                    console.log(result.data);
                    return result.data;
                },
                function( result ) {
                    alert("Unable to find any users! Please try again...");
                })
            }
        }
    });
}]);
</code>```

My controller also looks something like this:

```<code>userMan.controller('userManCtrl', ['$scope', '$log', '$http', '$location', 'myUser',
function($scope, $log, $http, $location, myUser){

    var currUser = myUser;
</code>```

Basically my error is that currUser is undefined. This prevents me to check the user's permissions and such.
I have also used:

```<code>    $scope.$on('$routeChangeSuccess',function(event, current){
        alert("loaded!!");
    });
</code>```

To see when this promise is resolved, but I see the alert message as soon as I load into the tab.
I then tried to use a dummy return object simply like

```<code>return { someAttr: 'val'};
</code>```

This functions just fine.. I know its not a promise but did that for sanity purposes..

Any clues for the error?

答:
After feedback from @JoelCDoyle and @baao, I used a different approach.
I simply created a service that handled the GET request and used that in my resolve.
More on this can be viewed here</p>

Body:
So basically I am using resolve in $routeProvider in order to get my current user's information before I instantiate the controller.
This is how I do it:

userMan.config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/userManagement', {
        templateUrl: 'userManagement/userManagement.html',
        controller: 'userManCtrl',
        resolve: {
            myUser:function($http){
                console.log("I am about to make the call");
                $http.get("/irods-cloud-backend/searchByMetadata/getCurrentUser").then( function( result ) {
                    console.log(result.data);
                    return result.data;
                },
                function( result ) {
                    alert("Unable to find any users! Please try again...");
                })
            }
        }
    });
}]);

My controller also looks something like this:

userMan.controller('userManCtrl', ['$scope', '$log', '$http', '$location', 'myUser',
function($scope, $log, $http, $location, myUser){

    var currUser = myUser;

Basically my error is that currUser is undefined. This prevents me to check the user's permissions and such.
I have also used:

    $scope.$on('$routeChangeSuccess',function(event, current){
        alert("loaded!!");
    });

To see when this promise is resolved, but I see the alert message as soon as I load into the tab.
I then tried to use a dummy return object simply like

return { someAttr: 'val'};

This functions just fine.. I know its not a promise but did that for sanity purposes..

Any clues for the error?


问:
How can i apply left outer join conditions on four tables?
i was trying to apply joins on 4 tables. but i could not find proper result for that.
i have 4 tables like 1.students,2.college,3.locations,4.departments. so i have same column sid in all tables which can be used to join conditions.
i want all matched rows from four tables as mentioned columns in select statement below and unmatched rows in left table which is left outer join work.

i have tried this syntax.

```<code>select
  students.sname,
  college.cname,
  locations.loc,
  department.dept
from students, college, locaions, departments
where student.sid=college.sid(+)
and college.sid=locations.sid(+)
and locations.sid=department.sid(+);
</code>```

is this right ?

答:
Given what you've shown it would appear that what you really want is

```<code>select s.sname,
       c.cname,
       l.loc,
       d.dept
from students s
LEFT OUTER JOIN college c
  ON c.SID = s.SID
LEFT OUTER JOIN locations l
  ON l.SID = s.SID
LEFT OUTER JOIN departments d
  ON d.SID = s.SID
</code>```

The issue in your original query is that because an OUTER JOIN is an optional join, you can end up with NULL values being returned in one of the join fields, which then prevents any of the downstream values being joined. I agree with @ThorstenKettner who observes in a comment that SID is apparently a "student ID", but it's not reasonable or appropriate to have a "student ID" field on tables named COLLEGE, LOCATIONS, or DEPARTMENTS. Perhaps you need to update your design to allow any number of students to be associated with one of these entities, perhaps using a "join" table.

Best of luck.

Body:
i was trying to apply joins on 4 tables. but i could not find proper result for that.
i have 4 tables like 1.students,2.college,3.locations,4.departments. so i have same column sid in all tables which can be used to join conditions.
i want all matched rows from four tables as mentioned columns in select statement below and unmatched rows in left table which is left outer join work.

i have tried this syntax.

select
  students.sname,
  college.cname,
  locations.loc,
  department.dept
from students, college, locaions, departments
where student.sid=college.sid(+)
and college.sid=locations.sid(+)
and locations.sid=department.sid(+);

is this right ?

Body:
Given what you've shown it would appear that what you really want is

select s.sname,
       c.cname,
       l.loc,
       d.dept
from students s
LEFT OUTER JOIN college c
  ON c.SID = s.SID
LEFT OUTER JOIN locations l
  ON l.SID = s.SID
LEFT OUTER JOIN departments d
  ON d.SID = s.SID

The issue in your original query is that because an OUTER JOIN is an optional join, you can end up with NULL values being returned in one of the join fields, which then prevents any of the downstream values being joined. I agree with @ThorstenKettner who observes in a comment that SID is apparently a "student ID", but it's not reasonable or appropriate to have a "student ID" field on tables named COLLEGE, LOCATIONS, or DEPARTMENTS. Perhaps you need to update your design to allow any number of students to be associated with one of these entities, perhaps using a "join" table.

Best of luck.


问:
How to define as Save As Function in Python
hello I have below code like this, I would like to do save as same name but add a Tag New to same file name so save it as new_TBM. Any help is appreciated.</p>

```<code>import sys
from tableaudocumentapi import Workbook

sourceWB = Workbook('C:\\Users\\rmakkena\\Music\\TBM.twb')

sourceWB.datasources[0].connections[0].server = "MY-NEW-SERVER"
sourceWB.datasources[0].connections[0].dbname = "NEW-DATABASE"
sourceWB.datasources[0].connections[0].username = "rithesh"

sourceWB.save_as()
</code>```

答:
You only need to do a bit of processing on your (basename part of the) filename. For that, we use [Python]: os.path — Common pathname manipulations. How it's done:

Split the file name into:

dirname (directory tree path: C:\Users\rmakkena\Music) and

basename (plain file name: TBM.twb)

Add the "new_" prefix to the basename

Rejoin the 2 parts together (C:\Users\rmakkena\Music\new_TBM.twb)

The (slightly modified) code (check [GitHub]: document-api-python/tableaudocumentapi/workbook.py: def save_as(self, new_filename):):

```<code>import sys
import os
from tableaudocumentapi import Workbook

file_name = "C:\\Users\\rmakkena\\Music\\TBM.twb"
new_tag = "new_"

sourceWB = Workbook(file_name)

sourceWB.datasources[0].connections[0].server = "MY-NEW-SERVER"
sourceWB.datasources[0].connections[0].dbname = "NEW-DATABASE"
sourceWB.datasources[0].connections[0].username = "rithesh"

sourceWB.save_as(os.path.join(os.path.dirname(file_name), new_tag + os.path.basename(file_name)))
</code>```

Body:
hello I have below code like this, I would like to do save as same name but add a Tag New to same file name so save it as new_TBM. Any help is appreciated.

import sys
from tableaudocumentapi import Workbook

sourceWB = Workbook('C:\\Users\\rmakkena\\Music\\TBM.twb')

sourceWB.datasources[0].connections[0].server = "MY-NEW-SERVER"
sourceWB.datasources[0].connections[0].dbname = "NEW-DATABASE"
sourceWB.datasources[0].connections[0].username = "rithesh"

sourceWB.save_as()

Body:
You only need to do a bit of processing on your (basename part of the) filename. For that, we use [Python]: os.path — Common pathname manipulations. How it's done:

Split the file name into:

dirname (directory tree path: C:\Users\rmakkena\Music) and

basename (plain file name: TBM.twb)

Add the "new_" prefix to the basename

Rejoin the 2 parts together (C:\Users\rmakkena\Music\new_TBM.twb)

The (slightly modified) code (check [GitHub]: document-api-python/tableaudocumentapi/workbook.py: def save_as(self, new_filename):):

import sys
import os
from tableaudocumentapi import Workbook

file_name = "C:\\Users\\rmakkena\\Music\\TBM.twb"
new_tag = "new_"

sourceWB = Workbook(file_name)

sourceWB.datasources[0].connections[0].server = "MY-NEW-SERVER"
sourceWB.datasources[0].connections[0].dbname = "NEW-DATABASE"
sourceWB.datasources[0].connections[0].username = "rithesh"

sourceWB.save_as(os.path.join(os.path.dirname(file_name), new_tag + os.path.basename(file_name)))


问:
How to create a four digit password Android layout
I want to create a layout for an Android app that has a numeric keypad and takes four digits to determine if it matches a preset passcode value.

I have seen a few applications use this, so I would have thought that it was a high level widget of some description.

The only thing I can find that's remotely close to what I want is this:

```<code><EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:ems="10"
    android:inputType="numberPassword" >

    <requestFocus />
</EditText>
</code>```

But this isn't really what I'm looking for.

Any input would be awesome and thanks in advance.

EDIT: Here's an image of the iOS dropbox app start screen that I'd like:

答:
I'm beginner in Android.
  when I stuck in coding I always use to refer stackoverflow. I have learnt lot of things from stackoverflow.
  This is the first time i  have dared to answer this question.
  Pardon me if I'm wrong and any suggestion regarding coding or the way of writing code in stackoverflow is highly appreciated.
  Thank You..

I have did something like this in Fragments..
Take 4 EditText in and set maxLength attribute to 1 in xml for all 4 EditTexts.     You can modify EditText as per your requirement.

Note: OnKey method may or may not be not be invoked for DEL(BackSpace) in Stock Android KeyBoard.

```<code>public class VerifyCodeFrag extends Fragment implements TextWatcher,View.OnKeyListener,View.OnFocusChangeListener
                        {
                            private EditText et_digit1, et_digit2, et_digit3, et_digit4;//In this et_digit1 is Most significant digit and et_digit4 is least significant digit
                            private int whoHasFocus;
                            char[] code = new char[4];//Store the digits in charArray.
                            @Override
                            public void onCreate(Bundle savedInstanceState)
                            {
                                super.onCreate(savedInstanceState);
                            }

                            @Override
                            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                                     Bundle savedInstanceState)
                            {
                                View view=inflater.inflate(R.layout.fragment_verify_code, container, false);
                                initializeView(view);
                                et_digit1.requestFocus();//Left digit gets focus after adding of fragment in Container
                                return view;
                            }
</code>```

This method is used to intilize views.

```<code>private void initializeView(View view)
  {
 et_digit1 = (EditText) view.findViewById(R.id.et_vfcode_digit1);
 et_digit2 = (EditText) view.findViewById(R.id.et_vfcode_digit2);
 et_digit3 = (EditText) view.findViewById(R.id.et_vfcode_digit3);
 et_digit4 = (EditText) view.findViewById(R.id.et_vfcode_digit4);
 setListners();
  }
</code>```

This method is to set the listeners for each EditTexts.

```<code>private void setListners()
  {
   et_digit1.addTextChangedListener(this);
   et_digit2.addTextChangedListener(this);
   et_digit3.addTextChangedListener(this);
   et_digit4.addTextChangedListener(this);

   et_digit1.setOnKeyListener(this);
   et_digit2.setOnKeyListener(this);
   et_digit3.setOnKeyListener(this);
   et_digit4.setOnKeyListener(this);

   et_digit1.setOnFocusChangeListener(this);
   et_digit2.setOnFocusChangeListener(this);
   et_digit3.setOnFocusChangeListener(this);
   et_digit4.setOnFocusChangeListener(this);
     }
</code>```

These are the override method of interface OnFocusChangeListner by which I'm checking which EditText currently has focus from where it is useful to fetch number from respective EditText Boxes in afterTextChnged method(override method of TextWatcher).

```<code> @Override
  public void onFocusChange(View v, boolean hasFocus)
  {
  switch(v.getId())
  {
  case R.id.et_vfcode_digit1:
  whoHasFocus=1;
  break;

  case R.id.et_vfcode_digit2:
  whoHasFocus=2;
  break;

  case R.id.et_vfcode_digit3:
  whoHasFocus=3;
  break;

  case R.id.et_vfcode_digit4:
  whoHasFocus=4;
  break;

   default:
   break;
   }
   }
</code>```

These are the override method of TextWatcher Interface.
Here in this afterTextChanged(override method)
I'm fetching number from EdiTexts storing them in  respective index of charArray.
And once the user enter the number in EditText the next EditText will get focus by requestfocus method(Example:et_digit2.requestFocus()).

```<code>@Override
public void beforeTextChanged(CharSequence s, int start, int count, int    after)
{
}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
}
@Override
public void afterTextChanged(Editable s)
{
switch (whoHasFocus)
{
case 1:
if(!et_digit1.getText().toString().isEmpty())
{
code[0]= et_digit1.getText().toString().charAt(0);
et_digit2.requestFocus();
}
break;

case 2:
if(!et_digit2.getText().toString().isEmpty())
{
code[1]= et_digit2.getText().toString().charAt(0);
et_digit3.requestFocus();
}
break;

case 3:
if(!et_digit3.getText().toString().isEmpty())
{
code[2]= et_digit3.getText().toString().charAt(0);
et_digit4.requestFocus();
}
break;

case 4:
if(!et_digit4.getText().toString().isEmpty())
{
code[3]= et_digit4.getText().toString().charAt(0);
}
break;

default:
break;
}
}
</code>```

This method will functionate  as delete(BackSpace) key.

In this override method I'm checking whether EditText is empty and DEL(backspace in keypad is pressed).
if true the previous EditText will get focus.

```<code>@Override
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if (event.getAction() == KeyEvent.ACTION_DOWN)
{
if (keyCode == KeyEvent.KEYCODE_DEL)
{
switch(v.getId())
{
 case R.id.et_vfcode_digit2:
 if (et_digit2.getText().toString().isEmpty())
 et_digit1.requestFocus();
 break;

 case R.id.et_vfcode_digit3:
 if (et_digit3.getText().toString().isEmpty())
 et_digit2.requestFocus();
 break;

case R.id.et_vfcode_digit4:
if (et_digit4.getText().toString().isEmpty())
et_digit3.requestFocus();
break;

default:
break;
}
}
}
return false;
}
}
</code>```

Sample image.

[1]: https://i.stack.imgur.com/DAc9y.jpg

Body:
I want to create a layout for an Android app that has a numeric keypad and takes four digits to determine if it matches a preset passcode value.

I have seen a few applications use this, so I would have thought that it was a high level widget of some description.

The only thing I can find that's remotely close to what I want is this:

<EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:ems="10"
    android:inputType="numberPassword" >

    <requestFocus />
</EditText>

But this isn't really what I'm looking for.

Any input would be awesome and thanks in advance.

EDIT: Here's an image of the iOS dropbox app start screen that I'd like:

Body:
I'm beginner in Android.
  when I stuck in coding I always use to refer stackoverflow. I have learnt lot of things from stackoverflow.
  This is the first time i  have dared to answer this question.
  Pardon me if I'm wrong and any suggestion regarding coding or the way of writing code in stackoverflow is highly appreciated.
  Thank You..

I have did something like this in Fragments..
Take 4 EditText in and set maxLength attribute to 1 in xml for all 4 EditTexts.     You can modify EditText as per your requirement.

Note: OnKey method may or may not be not be invoked for DEL(BackSpace) in Stock Android KeyBoard.

public class VerifyCodeFrag extends Fragment implements TextWatcher,View.OnKeyListener,View.OnFocusChangeListener
                        {
                            private EditText et_digit1, et_digit2, et_digit3, et_digit4;//In this et_digit1 is Most significant digit and et_digit4 is least significant digit
                            private int whoHasFocus;
                            char[] code = new char[4];//Store the digits in charArray.
                            @Override
                            public void onCreate(Bundle savedInstanceState)
                            {
                                super.onCreate(savedInstanceState);
                            }

                            @Override
                            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                                     Bundle savedInstanceState)
                            {
                                View view=inflater.inflate(R.layout.fragment_verify_code, container, false);
                                initializeView(view);
                                et_digit1.requestFocus();//Left digit gets focus after adding of fragment in Container
                                return view;
                            }

This method is used to intilize views.

private void initializeView(View view)
  {
 et_digit1 = (EditText) view.findViewById(R.id.et_vfcode_digit1);
 et_digit2 = (EditText) view.findViewById(R.id.et_vfcode_digit2);
 et_digit3 = (EditText) view.findViewById(R.id.et_vfcode_digit3);
 et_digit4 = (EditText) view.findViewById(R.id.et_vfcode_digit4);
 setListners();
  }

This method is to set the listeners for each EditTexts.

private void setListners()
  {
   et_digit1.addTextChangedListener(this);
   et_digit2.addTextChangedListener(this);
   et_digit3.addTextChangedListener(this);
   et_digit4.addTextChangedListener(this);

   et_digit1.setOnKeyListener(this);
   et_digit2.setOnKeyListener(this);
   et_digit3.setOnKeyListener(this);
   et_digit4.setOnKeyListener(this);

   et_digit1.setOnFocusChangeListener(this);
   et_digit2.setOnFocusChangeListener(this);
   et_digit3.setOnFocusChangeListener(this);
   et_digit4.setOnFocusChangeListener(this);
     }

These are the override method of interface OnFocusChangeListner by which I'm checking which EditText currently has focus from where it is useful to fetch number from respective EditText Boxes in afterTextChnged method(override method of TextWatcher).

 @Override
  public void onFocusChange(View v, boolean hasFocus)
  {
  switch(v.getId())
  {
  case R.id.et_vfcode_digit1:
  whoHasFocus=1;
  break;

  case R.id.et_vfcode_digit2:
  whoHasFocus=2;
  break;

  case R.id.et_vfcode_digit3:
  whoHasFocus=3;
  break;

  case R.id.et_vfcode_digit4:
  whoHasFocus=4;
  break;

   default:
   break;
   }
   }

These are the override method of TextWatcher Interface.
Here in this afterTextChanged(override method)
I'm fetching number from EdiTexts storing them in  respective index of charArray.
And once the user enter the number in EditText the next EditText will get focus by requestfocus method(Example:et_digit2.requestFocus()).

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int    after)
{
}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
}
@Override
public void afterTextChanged(Editable s)
{
switch (whoHasFocus)
{
case 1:
if(!et_digit1.getText().toString().isEmpty())
{
code[0]= et_digit1.getText().toString().charAt(0);
et_digit2.requestFocus();
}
break;

case 2:
if(!et_digit2.getText().toString().isEmpty())
{
code[1]= et_digit2.getText().toString().charAt(0);
et_digit3.requestFocus();
}
break;

case 3:
if(!et_digit3.getText().toString().isEmpty())
{
code[2]= et_digit3.getText().toString().charAt(0);
et_digit4.requestFocus();
}
break;

case 4:
if(!et_digit4.getText().toString().isEmpty())
{
code[3]= et_digit4.getText().toString().charAt(0);
}
break;

default:
break;
}
}

This method will functionate  as delete(BackSpace) key.

In this override method I'm checking whether EditText is empty and DEL(backspace in keypad is pressed).
if true the previous EditText will get focus.

@Override
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if (event.getAction() == KeyEvent.ACTION_DOWN)
{
if (keyCode == KeyEvent.KEYCODE_DEL)
{
switch(v.getId())
{
 case R.id.et_vfcode_digit2:
 if (et_digit2.getText().toString().isEmpty())
 et_digit1.requestFocus();
 break;

 case R.id.et_vfcode_digit3:
 if (et_digit3.getText().toString().isEmpty())
 et_digit2.requestFocus();
 break;

case R.id.et_vfcode_digit4:
if (et_digit4.getText().toString().isEmpty())
et_digit3.requestFocus();
break;

default:
break;
}
}
}
return false;
}
}

Sample image.

[1]: https://i.stack.imgur.com/DAc9y.jpg


问:
Xamarin.forms Data passing to another view
I have problem with passing parameter of ListView(Data Json Response) to Detailview. In listview i showed name of the title, and i want to show some details in DetailView. here the problem i can`t get index value of set of JSOn Value to pass Detail view.

Thanks in Advance.

答: When you use ListView and select an Item, you have SelectedItem property with the selected value. Pass SelectedItem to your DetailView. It's enough</p>


问:
How to override extjs modern DatePicker
In ExtJs 6.2.0 modern toolkit, the DatePicker is quite strange - it has three slots (day, month, year). But I really need to know the day of week for each date, like in normal datepickers.

How can I override existing DatePicker to highlight weekends or to write day of week somewhere near the day number?

答:
I just solved this issue by using a custom date picker that changes the day's text any time a slot is changed.</p>

```<code>Ext.define('App.field.DateDayPicker', {
    extend: 'Ext.field.DatePicker',
    alias: 'widget.datepickerdayfield',

    requires: [
        'App.picker.DateDay'
    ],

    picker: {
        xtype: 'datepickerday'
    }
});
</code>```

<p> </p>

```<code>Ext.define('App.picker.DateDay', {
    extend: 'Ext.picker.Date',
    alias: 'widget.datepickerday',

    onSlotPick: function () {
        this.callParent(arguments);

        var value = this.getValue();
        var store = this.daySlot.getStore();

        store.each(function (day) {
            var dayDate = day.get('value');
            var year = value.getFullYear();
            var month = value.getMonth();
            var date = new Date(year, month, dayDate);
            var text = Ext.Date.format(date, 'j D');

            day.set('text', text);
        });
    }
});
</code>```

Title: How to override extjs modern DatePicker

Body:
I just solved this issue by using a custom date picker that changes the day's text any time a slot is changed.

Ext.define('App.field.DateDayPicker', {
    extend: 'Ext.field.DatePicker',
    alias: 'widget.datepickerdayfield',

    requires: [
        'App.picker.DateDay'
    ],

    picker: {
        xtype: 'datepickerday'
    }
});

Ext.define('App.picker.DateDay', {
    extend: 'Ext.picker.Date',
    alias: 'widget.datepickerday',

    onSlotPick: function () {
        this.callParent(arguments);

        var value = this.getValue();
        var store = this.daySlot.getStore();

        store.each(function (day) {
            var dayDate = day.get('value');
            var year = value.getFullYear();
            var month = value.getMonth();
            var date = new Date(year, month, dayDate);
            var text = Ext.Date.format(date, 'j D');

            day.set('text', text);
        });
    }
});