问:
Run rails application with apache and passenger on ubuntu
I have got some source code or rails project and I need to to run in on local machine. Actually on Ubuntu virtual machine.

I am not sure what all I need to install and configure in order to run it locally. Is there a standard way to find it all throughout source code?

I have figure out that application is using SQL Lite in development environment and MySQL in production environment.

from config/database.rb

```<code># MySQL.  Versions 4.1 and 5.0 are recommended.
#
# Install the MySQL driver:
#   gem install mysql2
#
# And be sure to use new-style password hashing:
#   http://dev.mysql.com/doc/refman/5.0/en/old-client.html
development:
  adapter: sqlite3
  database: db/development.sqlite3
  pool: 5
  timeout: 5000

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  adapter: sqlite3
  database: db/test.sqlite3
  pool: 5
  timeout: 5000

staging:
  adapter: mysql2
  database: appname_staging
  username: rails
  password: somepassword
  host: localhost

production:
  adapter: mysql2
  database: appname_production
  username: rails
  password: somepassword
  host: localhost
</code>```

Also I have set proper version of ruby and rails and install it with rvm. I know that the versions are correct because of .ruby-gemset .ruby-version files. Also I did bundle install and all gems from Gemfile installed successfully.

ruby -v => ruby 1.9.3p551
rails -v => 3.2.13

apache2 -v => Server version: Apache/2.4.7 (Ubuntu)
              Server built:   Oct 14 2015 14:18:49

mysql -V => mysql  Ver 14.14 Distrib 5.5.46,
            for debian-linux-gnu (i686) using readline 6.3

lsb_release -a => No LSB modules are available.
                  Distributor ID:   Ubuntu
                  Description:  Ubuntu 14.04.3 LTS
                  Release:  14.04
                  Codename: trusty

This is pretty much where my expertise stops. I am not sure  which web server application should use. Is it predefined in source code somewhere?

I spot that there is apache, passenger and moonshine are used.

from app/manifests/application_manifest.rb

```<code># The default_stack recipe install Rails, Apache, Passenger, the database from
  # database.yml, Postfix, Cron, logrotate and NTP. See lib/moonshine/manifest/rails.rb
  # for details. To customize, remove this recipe and specify the components you want.
  recipe :default_stack
  recipe :ssh
</code>```

I also not sure what is exactly purpose of each of these individually.

How apache as web server can recognize and interpret ruby code?

I would be happy if I could host any rails app on apache. I have created some very simple app and tries these steps https://www.linode.com/docs/websites/ror/ruby-on-rails-with-apache-on-ubuntu-10-04-lucid but it always opens default apache web page.

I am not usre where to start. I just have a bunch of questions adn a lot of confustion. I do not understand how the ROR on apache actually works.

Is the passenger the thing upon apache that interprets ruby code?

I show that nginx is alternative for passenger but it is also alternative for apache, it confuses me even more.

Thanks for any help.

答:
The web is an extremely concurrent environment. Production web server such as Apache can work on several requests — even tens or hundreds of requests — at the same time. A single-process, Ruby-based web server can't possibly keep up, and luckily it doesn’t have to.

Instead, the way we deploy a Rails application into production is to use a front-end server, such as Apache, to handle requests from the client. Then, we use the HTTP proxying of Passenger to send requests that should be handled by Rails to one of any number of back-end application processes.

I assume you have installed Apache web server and it is running on your machine.

Run following commands to install Passenger:

```<code>$ gem install passenger -v 5.0.30
$ passenger-install-apache2-module
</code>```

If the necessary dependencies aren’t met, the latter command will tell you what you need to do. If this happens, follow the provided instructions, and try the Passenger install command again.

During the process, it’ll ask you to update your Apache configuration. The first request will be to enable your freshly built module, which involves adding lines such as the following to your Apache configuration.

```<code>LoadModule passenger_module /home/devel/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/passenger-5.1.5/buildout/apache2/mod_passenger.so
<IfModule mod_passenger.c>
    PassengerRoot /home/devel/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/passenger-5.1.5
    PassengerDefaultRuby /home/devel/.rbenv/versions/2.4.0/bin/ruby
</IfModule>
</code>```

(Note: Passenger will tell you the exact lines to copy and paste into this file, so use those, not these)

To find out where your Apache configuration file is, try issuing the following command:

```<code>$ apachectl -V | grep HTTPD_ROOT
$ apachectl -V | grep SERVER_CONFIG_FILE
</code>```

Deploying the Application

The previous step needs to be done only once per server, this step is actually once per application. Substitute your host's name, your application's directory path, and a secret key in the following:

```<code><VirtualHost *:80>
  ServerName depot.yourhost.com
  DocumentRoot /home/devel/depot/public/
  SetEnv SECRET_KEY_BASE "0123456789abcdef"
  SetEnv DEPOT_DATABASE_PASSWORD "some-password"
  <Directory /home/devel/depot/public/>
    AllowOverride all
    Options -MultiViews
    Require all granted
  </Directory>
</VirtualHost>
</code>```

Use following command to generate a suitable key to be used as the secret. This key is used to encrypt cookies that are sent to the client.

```<code>$ bin/rails secret
</code>```

Here we are using SetEnv directive to define environment variables, instead of keeping our secret key and database password in config files for
production mode.

The final step is to restart our Apache web server:

```<code>$ sudo apachectl restart
</code>```

Body:
I have got some source code or rails project and I need to to run in on local machine. Actually on Ubuntu virtual machine.

I am not sure what all I need to install and configure in order to run it locally. Is there a standard way to find it all throughout source code?

I have figure out that application is using SQL Lite in development environment and MySQL in production environment.

from config/database.rb

# MySQL.  Versions 4.1 and 5.0 are recommended.
#
# Install the MySQL driver:
#   gem install mysql2
#
# And be sure to use new-style password hashing:
#   http://dev.mysql.com/doc/refman/5.0/en/old-client.html
development:
  adapter: sqlite3
  database: db/development.sqlite3
  pool: 5
  timeout: 5000

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  adapter: sqlite3
  database: db/test.sqlite3
  pool: 5
  timeout: 5000

staging:
  adapter: mysql2
  database: appname_staging
  username: rails
  password: somepassword
  host: localhost

production:
  adapter: mysql2
  database: appname_production
  username: rails
  password: somepassword
  host: localhost

Also I have set proper version of ruby and rails and install it with rvm. I know that the versions are correct because of .ruby-gemset .ruby-version files. Also I did bundle install and all gems from Gemfile installed successfully.

ruby -v => ruby 1.9.3p551
rails -v => 3.2.13

apache2 -v => Server version: Apache/2.4.7 (Ubuntu)
              Server built:   Oct 14 2015 14:18:49

mysql -V => mysql  Ver 14.14 Distrib 5.5.46,
            for debian-linux-gnu (i686) using readline 6.3

lsb_release -a => No LSB modules are available.
                  Distributor ID:   Ubuntu
                  Description:  Ubuntu 14.04.3 LTS
                  Release:  14.04
                  Codename: trusty

This is pretty much where my expertise stops. I am not sure  which web server application should use. Is it predefined in source code somewhere?

I spot that there is apache, passenger and moonshine are used.

from app/manifests/application_manifest.rb

# The default_stack recipe install Rails, Apache, Passenger, the database from
  # database.yml, Postfix, Cron, logrotate and NTP. See lib/moonshine/manifest/rails.rb
  # for details. To customize, remove this recipe and specify the components you want.
  recipe :default_stack
  recipe :ssh

I also not sure what is exactly purpose of each of these individually.

How apache as web server can recognize and interpret ruby code?

I would be happy if I could host any rails app on apache. I have created some very simple app and tries these steps https://www.linode.com/docs/websites/ror/ruby-on-rails-with-apache-on-ubuntu-10-04-lucid but it always opens default apache web page.

I am not usre where to start. I just have a bunch of questions adn a lot of confustion. I do not understand how the ROR on apache actually works.

Is the passenger the thing upon apache that interprets ruby code?

I show that nginx is alternative for passenger but it is also alternative for apache, it confuses me even more.

Thanks for any help.

Body:
The web is an extremely concurrent environment. Production web server such as Apache can work on several requests — even tens or hundreds of requests — at the same time. A single-process, Ruby-based web server can't possibly keep up, and luckily it doesn’t have to.

Instead, the way we deploy a Rails application into production is to use a front-end server, such as Apache, to handle requests from the client. Then, we use the HTTP proxying of Passenger to send requests that should be handled by Rails to one of any number of back-end application processes.

I assume you have installed Apache web server and it is running on your machine.

Run following commands to install Passenger:

$ gem install passenger -v 5.0.30
$ passenger-install-apache2-module

If the necessary dependencies aren’t met, the latter command will tell you what you need to do. If this happens, follow the provided instructions, and try the Passenger install command again.

During the process, it’ll ask you to update your Apache configuration. The first request will be to enable your freshly built module, which involves adding lines such as the following to your Apache configuration.

LoadModule passenger_module /home/devel/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/passenger-5.1.5/buildout/apache2/mod_passenger.so
<IfModule mod_passenger.c>
    PassengerRoot /home/devel/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/passenger-5.1.5
    PassengerDefaultRuby /home/devel/.rbenv/versions/2.4.0/bin/ruby
</IfModule>

(Note: Passenger will tell you the exact lines to copy and paste into this file, so use those, not these)

To find out where your Apache configuration file is, try issuing the following command:

$ apachectl -V | grep HTTPD_ROOT
$ apachectl -V | grep SERVER_CONFIG_FILE

Deploying the Application

The previous step needs to be done only once per server, this step is actually once per application. Substitute your host's name, your application's directory path, and a secret key in the following:

<VirtualHost *:80>
  ServerName depot.yourhost.com
  DocumentRoot /home/devel/depot/public/
  SetEnv SECRET_KEY_BASE "0123456789abcdef"
  SetEnv DEPOT_DATABASE_PASSWORD "some-password"
  <Directory /home/devel/depot/public/>
    AllowOverride all
    Options -MultiViews
    Require all granted
  </Directory>
</VirtualHost>

Use following command to generate a suitable key to be used as the secret. This key is used to encrypt cookies that are sent to the client.

$ bin/rails secret

Here we are using SetEnv directive to define environment variables, instead of keeping our secret key and database password in config files for
production mode.

The final step is to restart our Apache web server:

$ sudo apachectl restart


来源: stackexchange

问:
mysql - selecting values from a table given column number
is it possible in mysql to select a value from a table by specifying the column number instead of the column name ?</p>

答:
I don't think it is possible "directly" BUT with a query linked to the ORDINAL_POSITION field of the COLUMNS table from the information_schema should do the work!

Edit: COLUMNS table contains all the fields of all tables (and their positions)

ContentLicense: CC BY-SA 2.5


问:
Laravel 5 getting ID from URL
I have a table view in which I can click an button icon and redirect to another page carrying the id of the row that has been clicked.

```<code>@foreach ($patients as $patient)
    <tr>
        <td>{{ $patient->pID }}</td>
        <td>{{ $patient->pName }}</td>
        <td>{{ $patient->pAddress }}</td>
        <td>{{ $patient->pBday }}</td>
        <td>{{ $patient->pPhone}}</td>
        <td>{{ $patient->pEcon }}</td>
        <td>{{ $patient->pDreg }}</td>
        <td></td>
        <td>
            <a href="{{ URL::to('visit/'.$patient->pID) }}">
                <img src="../images/viewvisit.png" style="width:30px; height:30px;">
            </a>
        </td>
        <td>
            <a href="{{ URL::to('addeditvisit/'.$patient->pID) }}">
                <img src="../images/visit.png" style="width:30px; height:30px;">
            </a>
        </td>
        <td>
            <a href="{{ URL::to('editpatient/'.$patient->pID) }}">
                <img src="../images/update.png" style="width:30px; height:30px;">
            </a>
        </td>
        <td>
            <a href="{{ URL::to('deletepatient/'.$patient->pID) }}">
                <img src="../images/delete.png" style="width:30px; height:30px;">
            </a>
        </td>
    </tr>
@endforeach
</code>```

what I want is to get the id from the URL and put it in a variable so that I can utilize it my other page.

I'm currently stuck with this controller function.

```<code>public function index(Request $request) {

    $doctors = Doctor::where('dStatus', 0)
        ->lists('dName', 'dID');
    $beds = Bed::where('bStatus', 0)
        ->lists('bName', 'bID');
    $patient = Patient::patient();
    // $uri = $request->path('patient');

    return View::make('pages.addeditvisit', [
        'doctors'=>$doctors,
        'beds'=>$beds,
        'patient'=>$patient->pID
    ]);
}
</code>```

答:
Simple example:</p>

```<code>as link=>   example.com/user/1

as rout=> Route::get('user/{id}', 'UserController@user');

as UserController function

public function user($id){

    echo $id;

}

output => 1
</code>```

ContentLicense: CC BY-SA 3.0

Title: Laravel 5 getting ID from URL

Body:
I have a table view in which I can click an button icon and redirect to another page carrying the id of the row that has been clicked.

@foreach ($patients as $patient)

        {{ $patient->pID }}
        {{ $patient->pName }}
        {{ $patient->pAddress }}
        {{ $patient->pBday }}
        {{ $patient->pPhone}}
        {{ $patient->pEcon }}
        {{ $patient->pDreg }}

            pID) }}">

            pID) }}">

            pID) }}">

            pID) }}">

@endforeach

what I want is to get the id from the URL and put it in a variable so that I can utilize it my other page.

I'm currently stuck with this controller function.

public function index(Request $request) {

    $doctors = Doctor::where('dStatus', 0)
        ->lists('dName', 'dID');
    $beds = Bed::where('bStatus', 0)
        ->lists('bName', 'bID');
    $patient = Patient::patient();
    // $uri = $request->path('patient');

    return View::make('pages.addeditvisit', [
        'doctors'=>$doctors,
        'beds'=>$beds,
        'patient'=>$patient->pID
    ]);
}

Body:
Simple example:

as link=>   example.com/user/1

as rout=> Route::get('user/{id}', 'UserController@user');

as UserController function

public function user($id){

    echo $id;

}

output => 1


问:
Building hierarchy tree using JSON
I have a list of objects with a C_PARENT field.This parent field references another object in the list. I would like to create a tree hierarchy from this list based on this field.

Here is my data.

```<code>[{
    "C_ID" : 1.0,
    "C_TITLE" : "Sparklers",
    "C_PARENT" : 0.0,
    "C_STATUS" : "Active"
},

{
    "C_ID" : 2.0,
    "C_TITLE" : "Twinklers",
    "C_PARENT" : 0,
    "C_STATUS" : "Active"
},

{
    "C_ID" : 3.0,
    "C_TITLE" : "Candles",
    "C_PARENT" : 0.0,
    "C_STATUS" : "Active"
},

{
    "C_ID" : 4.0,
    "C_TITLE" : "Chakkars",
    "C_PARENT" : 0.0,
    "C_STATUS" : "Active"
},

{
    "C_ID" : 5.0,
    "C_TITLE" : "Colour Chakkars",
    "C_PARENT" : 4.0,
    "C_STATUS" : "Active"
},

{
    "C_ID" : 6.0,
    "C_TITLE" : "Fancy Chakkars",
    "C_PARENT" : 4.0,
    "C_STATUS" : "Active"
},

{
    "C_ID" : 7.0,
    "C_TITLE" : "Fountains",
    "C_PARENT" : 0.0,
    "C_STATUS" : "Active"
},

{
    "C_ID" : 8.0,
    "C_TITLE" : "Whistling Fountains",
    "C_PARENT" : 7.0,
    "C_STATUS" : "Active"
},

{
    "C_ID" : 9.0,
    "C_TITLE" : "Fancy Fountains",
    "C_PARENT" : 7.0,
    "C_STATUS" : "Active"
},

{
    "C_ID" : 10.0,
    "C_TITLE" : "Fancy Colour Fountains",
    "C_PARENT" : 7.0,
    "C_STATUS" : "Active"
},

{
    "C_ID" : 11.0,
    "C_TITLE" : "Rockets",
    "C_PARENT" : 0.0,
    "C_STATUS" : "Active"
}]
</code>```

I need convert into tree structure.

```<code>[
  {
    'C_ID': 1,
    'C_TITLE': 'Sparklers',
    'C_PARENT': 0,
    'C_STATUS':'Active'
  },
  {
    "C_ID" : 2.0,
    "C_TITLE" : "Twinklers",
    "C_PARENT" : 0,
    "C_STATUS" : "Active"
  },
  {
    "C_ID" : 3.0,
    "C_TITLE" : "Candles",
    "C_PARENT" : 0.0,
    "C_STATUS" : "Active"
  }
  {
    '"C_ID" : 4.0,
    "C_TITLE" : "Chakkars",
    "C_PARENT" : 0.0,
    "C_STATUS" : "Active"
    children:  [
      {
        "C_ID" : 5.0,
        "C_TITLE" : "Colour Chakkars",
        "C_PARENT" : 4.0,
        "C_STATUS" : "Active"
      },
      {
        "C_ID" : 6.0,
        "C_TITLE" : "Fancy Chakkars",
        "C_PARENT" : 4.0,
        "C_STATUS" : "Active"
      }
    ]
]
</code>```

I have no idea.

Kindly advice me,

Thanks

答:
I normaly used to create a new string with propertly info

```<code>String.prototype.replaceAll = function (search, replacement) {
  return this.replace(new RegExp(search, 'g'), replacement);
};

var data = JSON.parse('[{"C_ID" : 1.0,"C_TITLE" : "Sparklers","C_PARENT" : 0.0, "C_STATUS" : "Active"},{    "C_ID" : 2.0,    "C_TITLE" : "Twinklers",    "C_PARENT" : 0,    "C_STATUS" : "Active"},{   "C_ID" : 3.0,    "C_TITLE" : "Candles",    "C_PARENT" : 0.0,    "C_STATUS" : "Active"},{    "C_ID" : 4.0,    "C_TITLE" : "Chakkars",    "C_PARENT" : 0.0,    "C_STATUS" : "Active"},{    "C_ID" : 5.0,    "C_TITLE" : "Colour Chakkars",    "C_PARENT" : 4.0,    "C_STATUS" : "Active"},{    "C_ID" : 6.0,    "C_TITLE" : "Fancy Chakkars",    "C_PARENT" : 4.0,    "C_STATUS" : "Active"},{    "C_ID" : 7.0,    "C_TITLE" : "Fountains",    "C_PARENT" : 0.0,    "C_STATUS" : "Active"},{    "C_ID" : 8.0,    "C_TITLE" : "Whistling Fountains",    "C_PARENT" : 7.0,    "C_STATUS" : "Active"},{    "C_ID" : 9.0,    "C_TITLE" : "Fancy Fountains",    "C_PARENT" : 7.0,    "C_STATUS" : "Active"},{    "C_ID" : 10.0,    "C_TITLE" : "Fancy Colour Fountains",    "C_PARENT" : 7.0,    "C_STATUS" : "Active"},{    "C_ID" : 11.0,    "C_TITLE" : "Rockets",    "C_PARENT" : 0.0,    "C_STATUS" : "Active"}]');

var result = '[';

for (i = 0; i < data.length; i++) {
  if (data[i].C_PARENT == 0 || data[i].C_PARENT == "0") {
    if (i != 0)
      result += ']},';
    result += '{"C_ID" : ' + data[i].C_ID + ', "C_TITLE" : "' + data[i].C_TITLE + '", "C_PARENT" : ' + data[i].C_PARENT + ', "C_STATUS" : "' + data[i].C_STATUS + '", "children" : [';
  } else {
    result += '{"C_ID" : ' + data[i].C_ID + ', "C_TITLE" : "' + data[i].C_TITLE + '", "C_PARENT" : ' + data[i].C_PARENT + ', "C_STATUS" : "' + data[i].C_STATUS + '"},';
  }
}
result += ']}]';
result = result.replaceAll("},]", "}]");
var a = JSON.parse(result);
document.getElementById('result').innerHTML = result + "<br/><br/><br/>" + a;
</code>```

https://jsfiddle.net/g9h9a9ep/

Title: Building hierarchy tree using JSON

Body:
I have a list of objects with a C_PARENT field.This parent field references another object in the list. I would like to create a tree hierarchy from this list based on this field.

Here is my data.

[{
    "C_ID" : 1.0,
    "C_TITLE" : "Sparklers",
    "C_PARENT" : 0.0,
    "C_STATUS" : "Active"
},

{
    "C_ID" : 2.0,
    "C_TITLE" : "Twinklers",
    "C_PARENT" : 0,
    "C_STATUS" : "Active"
},

{
    "C_ID" : 3.0,
    "C_TITLE" : "Candles",
    "C_PARENT" : 0.0,
    "C_STATUS" : "Active"
},

{
    "C_ID" : 4.0,
    "C_TITLE" : "Chakkars",
    "C_PARENT" : 0.0,
    "C_STATUS" : "Active"
},

{
    "C_ID" : 5.0,
    "C_TITLE" : "Colour Chakkars",
    "C_PARENT" : 4.0,
    "C_STATUS" : "Active"
},

{
    "C_ID" : 6.0,
    "C_TITLE" : "Fancy Chakkars",
    "C_PARENT" : 4.0,
    "C_STATUS" : "Active"
},

{
    "C_ID" : 7.0,
    "C_TITLE" : "Fountains",
    "C_PARENT" : 0.0,
    "C_STATUS" : "Active"
},

{
    "C_ID" : 8.0,
    "C_TITLE" : "Whistling Fountains",
    "C_PARENT" : 7.0,
    "C_STATUS" : "Active"
},

{
    "C_ID" : 9.0,
    "C_TITLE" : "Fancy Fountains",
    "C_PARENT" : 7.0,
    "C_STATUS" : "Active"
},

{
    "C_ID" : 10.0,
    "C_TITLE" : "Fancy Colour Fountains",
    "C_PARENT" : 7.0,
    "C_STATUS" : "Active"
},

{
    "C_ID" : 11.0,
    "C_TITLE" : "Rockets",
    "C_PARENT" : 0.0,
    "C_STATUS" : "Active"
}]

I need convert into tree structure.

[
  {
    'C_ID': 1,
    'C_TITLE': 'Sparklers',
    'C_PARENT': 0,
    'C_STATUS':'Active'
  },
  {
    "C_ID" : 2.0,
    "C_TITLE" : "Twinklers",
    "C_PARENT" : 0,
    "C_STATUS" : "Active"
  },
  {
    "C_ID" : 3.0,
    "C_TITLE" : "Candles",
    "C_PARENT" : 0.0,
    "C_STATUS" : "Active"
  }
  {
    '"C_ID" : 4.0,
    "C_TITLE" : "Chakkars",
    "C_PARENT" : 0.0,
    "C_STATUS" : "Active"
    children:  [
      {
        "C_ID" : 5.0,
        "C_TITLE" : "Colour Chakkars",
        "C_PARENT" : 4.0,
        "C_STATUS" : "Active"
      },
      {
        "C_ID" : 6.0,
        "C_TITLE" : "Fancy Chakkars",
        "C_PARENT" : 4.0,
        "C_STATUS" : "Active"
      }
    ]
]

I have no idea.

Kindly advice me,

Thanks

Body:
I normaly used to create a new string with propertly info

String.prototype.replaceAll = function (search, replacement) {
  return this.replace(new RegExp(search, 'g'), replacement);
};

var data = JSON.parse('[{"C_ID" : 1.0,"C_TITLE" : "Sparklers","C_PARENT" : 0.0, "C_STATUS" : "Active"},{    "C_ID" : 2.0,    "C_TITLE" : "Twinklers",    "C_PARENT" : 0,    "C_STATUS" : "Active"},{   "C_ID" : 3.0,    "C_TITLE" : "Candles",    "C_PARENT" : 0.0,    "C_STATUS" : "Active"},{    "C_ID" : 4.0,    "C_TITLE" : "Chakkars",    "C_PARENT" : 0.0,    "C_STATUS" : "Active"},{    "C_ID" : 5.0,    "C_TITLE" : "Colour Chakkars",    "C_PARENT" : 4.0,    "C_STATUS" : "Active"},{    "C_ID" : 6.0,    "C_TITLE" : "Fancy Chakkars",    "C_PARENT" : 4.0,    "C_STATUS" : "Active"},{    "C_ID" : 7.0,    "C_TITLE" : "Fountains",    "C_PARENT" : 0.0,    "C_STATUS" : "Active"},{    "C_ID" : 8.0,    "C_TITLE" : "Whistling Fountains",    "C_PARENT" : 7.0,    "C_STATUS" : "Active"},{    "C_ID" : 9.0,    "C_TITLE" : "Fancy Fountains",    "C_PARENT" : 7.0,    "C_STATUS" : "Active"},{    "C_ID" : 10.0,    "C_TITLE" : "Fancy Colour Fountains",    "C_PARENT" : 7.0,    "C_STATUS" : "Active"},{    "C_ID" : 11.0,    "C_TITLE" : "Rockets",    "C_PARENT" : 0.0,    "C_STATUS" : "Active"}]');

var result = '[';

for (i = 0; i < data.length; i++) {
  if (data[i].C_PARENT == 0 || data[i].C_PARENT == "0") {
    if (i != 0)
      result += ']},';
    result += '{"C_ID" : ' + data[i].C_ID + ', "C_TITLE" : "' + data[i].C_TITLE + '", "C_PARENT" : ' + data[i].C_PARENT + ', "C_STATUS" : "' + data[i].C_STATUS + '", "children" : [';
  } else {
    result += '{"C_ID" : ' + data[i].C_ID + ', "C_TITLE" : "' + data[i].C_TITLE + '", "C_PARENT" : ' + data[i].C_PARENT + ', "C_STATUS" : "' + data[i].C_STATUS + '"},';
  }
}
result += ']}]';
result = result.replaceAll("},]", "}]");
var a = JSON.parse(result);
document.getElementById('result').innerHTML = result + "<br/><br/><br/>" + a;

https://jsfiddle.net/g9h9a9ep/


问:
How Do I Bind Values From DropDownListFor To My Controller?
I have a select control with static values in my view and I intend the user select a value and it binds to my controller so I can use it in the required action method.

My View -

```<code>@model StockProject.ViewModels.EquityViewModel
@using (Html.BeginForm(FormMethod.Post)){

@{
  var selectList = new SelectList(
  new List<SelectListItem>
  {
    new SelectListItem {Text = "BOOKED", Value = "1"},
    new SelectListItem {Text = "EXECUTING", Value = "2"},
    new SelectListItem {Text = "EXECUTED", Value = "3"},
    new SelectListItem {Text = "SUSPENDED", Value = "4"},
    new SelectListItem {Text = "CANCELLED", Value = "5"},
    }, "Value", "Text");
   }
@Html.DropDownListFor(model => model.status, selectList, new { @class = "form-control", name = "status", id = "status" })

<div class="col-md-3 form-group">
    <button type="button" class="btn btn-success btn-block form-control" onclick="location.href='@Url.Action("Equity", "Order")'">
         Go
         <i class="fa fa-arrow-circle-right"></i>
    </button>
</div>
}
</code>```

ViewModel -

```<code>public class EquityViewModel
{
    public int CustomerId { get; set; }
    public string status { get; set; }
    public DateTime startdate { get; set; }
    public DateTime enddate { get; set; }
    public List<ListEquityOrder> ListOrderEquity { get; set; }

    public EquityViewModel()
    {
        ListOrderEquity = new List<ListEquityOrder>();

    }
}
</code>```

Controller -

```<code>[HttpGet]
public IActionResult Equity()
{
  var modelview = new EquityViewModel();
  var model = new EquityRequest();

  model.CustomerId = _appSettings.TestCustomerId;
  model.RequestStartPoint = 0;
  model.NoOfRequests = 1000000;
  model.Null = null;
  model.Status = modelview.status;
  model.StartDate = modelview.StartDate;
  model.EndDate =  modelview.EndDate;
  model.Equity = "EQUITY";

  EquityResponse ListEquityOrders = _genericService.CallSoapAction<EquityResponse, EquityRequest>(model, "findCustomerOrdersBySecurityType");

  List<ListEquityOrder> findCusOrder = new List<ListEquityOrder>();
  foreach (var t in ListEquityOrders.Item)
  {
    ListEquityOrder listOrder = new ListEquityOrder();

    listOrder.BusinessOffice = t.BusinessOffice;
    listOrder.CustomerLabel = t.CustomerLabel;
    listOrder.CustomerName = t.CustomerName;
    listOrder.Exchange = t.Exchange;
    listOrder.FixOrderStatus = t.FixOrderStatus;
    //adding other data values to the list

    findCusOrder.Add(listOrder);
   }
   modelview.ListOrderEquity = findCusOrder;

   return View(modelview);
 }
</code>```

Anytime the user clicks on the submit button, no values are passed the controls - the DropDownListFor and TexBoxes. I have tried FormCollection but that doesn't work. Please how do I resolve this?

答:
You can use the following code getting the expected output.

In your model

```<code>public enum BookingDetails
    {
        BOOKED = 1, EXECUTING = 2, EXECUTED = 3, SUSPENDED = 4, CANCELLED = 5
    }

    public class SomeModel
    {
        public BookingDetails bookingDetails { get; set; }

        public static IEnumerable<SelectListItem> GetBookingDetailsSelectItems()
        {
            yield return new SelectListItem { Text = "BOOKED", Value = "1" };
            yield return new SelectListItem { Text = "EXECUTING", Value = "2" };
            yield return new SelectListItem { Text = "EXECUTED", Value = "3" };
            yield return new SelectListItem { Text = "SUSPENDED", Value = "4" };
            yield return new SelectListItem { Text = "CANCELLED", Value = "5" };
        }
    }
</code>```

Note : The above model only deals with dropdown values. If you want to do more then fell free to extend the class

Then your controller should be like below

```<code>public class MyController : Controller
    {
        // GET: My
        public ActionResult MyAction()
        {
            // shows your form when you load the page
            return View();
        }

        [HttpPost]
        public ActionResult MyAction(SomeModel model)
        {

            var selectedBookingDetails = model.bookingDetails;// this will be the selected dropdown item text.

            return View(model);
        }
    }
</code>```

then view

```<code>@model SomeModel

@using (Html.BeginForm("MyAction", "My", FormMethod.Post))
{
@Html.DropDownListFor(m => m.bookingDetails, SomeModel.GetBookingDetailsSelectItems())
<input type="submit" value="Send" />
}
</code>```

Note : please include the correct namespace of model

Body:
I have a select control with static values in my view and I intend the user select a value and it binds to my controller so I can use it in the required action method.

My View -

@model StockProject.ViewModels.EquityViewModel
@using (Html.BeginForm(FormMethod.Post)){

@{
  var selectList = new SelectList(
  new List<SelectListItem>
  {
    new SelectListItem {Text = "BOOKED", Value = "1"},
    new SelectListItem {Text = "EXECUTING", Value = "2"},
    new SelectListItem {Text = "EXECUTED", Value = "3"},
    new SelectListItem {Text = "SUSPENDED", Value = "4"},
    new SelectListItem {Text = "CANCELLED", Value = "5"},
    }, "Value", "Text");
   }
@Html.DropDownListFor(model => model.status, selectList, new { @class = "form-control", name = "status", id = "status" })

    <button type="button" class="btn btn-success btn-block form-control" onclick="location.href='@Url.Action("Equity", "Order")'">
         Go

    </button>

}

ViewModel -

public class EquityViewModel
{
    public int CustomerId { get; set; }
    public string status { get; set; }
    public DateTime startdate { get; set; }
    public DateTime enddate { get; set; }
    public List<ListEquityOrder> ListOrderEquity { get; set; }

    public EquityViewModel()
    {
        ListOrderEquity = new List<ListEquityOrder>();

    }
}

Controller -

[HttpGet]
public IActionResult Equity()
{
  var modelview = new EquityViewModel();
  var model = new EquityRequest();

  model.CustomerId = _appSettings.TestCustomerId;
  model.RequestStartPoint = 0;
  model.NoOfRequests = 1000000;
  model.Null = null;
  model.Status = modelview.status;
  model.StartDate = modelview.StartDate;
  model.EndDate =  modelview.EndDate;
  model.Equity = "EQUITY";

  EquityResponse ListEquityOrders = _genericService.CallSoapAction<EquityResponse, EquityRequest>(model, "findCustomerOrdersBySecurityType");

  List<ListEquityOrder> findCusOrder = new List<ListEquityOrder>();
  foreach (var t in ListEquityOrders.Item)
  {
    ListEquityOrder listOrder = new ListEquityOrder();

    listOrder.BusinessOffice = t.BusinessOffice;
    listOrder.CustomerLabel = t.CustomerLabel;
    listOrder.CustomerName = t.CustomerName;
    listOrder.Exchange = t.Exchange;
    listOrder.FixOrderStatus = t.FixOrderStatus;
    //adding other data values to the list

    findCusOrder.Add(listOrder);
   }
   modelview.ListOrderEquity = findCusOrder;

   return View(modelview);
 }

Anytime the user clicks on the submit button, no values are passed the controls - the DropDownListFor and TexBoxes. I have tried FormCollection but that doesn't work. Please how do I resolve this?

Body:
You can use the following code getting the expected output.

In your model

public enum BookingDetails
    {
        BOOKED = 1, EXECUTING = 2, EXECUTED = 3, SUSPENDED = 4, CANCELLED = 5
    }

    public class SomeModel
    {
        public BookingDetails bookingDetails { get; set; }

        public static IEnumerable<SelectListItem> GetBookingDetailsSelectItems()
        {
            yield return new SelectListItem { Text = "BOOKED", Value = "1" };
            yield return new SelectListItem { Text = "EXECUTING", Value = "2" };
            yield return new SelectListItem { Text = "EXECUTED", Value = "3" };
            yield return new SelectListItem { Text = "SUSPENDED", Value = "4" };
            yield return new SelectListItem { Text = "CANCELLED", Value = "5" };
        }
    }

Note : The above model only deals with dropdown values. If you want to do more then fell free to extend the class

Then your controller should be like below

public class MyController : Controller
    {
        // GET: My
        public ActionResult MyAction()
        {
            // shows your form when you load the page
            return View();
        }

        [HttpPost]
        public ActionResult MyAction(SomeModel model)
        {

            var selectedBookingDetails = model.bookingDetails;// this will be the selected dropdown item text.

            return View(model);
        }
    }

then view

@model SomeModel

@using (Html.BeginForm("MyAction", "My", FormMethod.Post))
{
@Html.DropDownListFor(m => m.bookingDetails, SomeModel.GetBookingDetailsSelectItems())
<input type="submit" value="Send" />
}

Note : please include the correct namespace of model


问:
iOS: Modal ViewController with transparent background
I'm trying to present a view controller modally, with a transparent background. My goal is to let both the presenting and presented view controllers's view to be displayed at the same time. The problem is, when the presenting animation finishes, the presenting view controller's view disappears.

```<code>- (IBAction)pushModalViewControllerButtonPressed:(id)sender
{
    ModalViewController *modalVC = [[ModalViewController alloc] init];
    [self presentViewController:modalVC animated:YES completion:nil];
}
</code>```

I know I could just add the view as a subview, but I'd like to avoid this solution for some reason. How could I fix it?

答:
Set navigation's modalPresentationStyle to UIModalPresentationCustom

and set your presented view controller's background color as clear color.

Body:
I'm trying to present a view controller modally, with a transparent background. My goal is to let both the presenting and presented view controllers's view to be displayed at the same time. The problem is, when the presenting animation finishes, the presenting view controller's view disappears.

- (IBAction)pushModalViewControllerButtonPressed:(id)sender
{
    ModalViewController *modalVC = [[ModalViewController alloc] init];
    [self presentViewController:modalVC animated:YES completion:nil];
}

I know I could just add the view as a subview, but I'd like to avoid this solution for some reason. How could I fix it?


问:
Rmarkdown render from script
I'm trying to knit an Rmd to pdf from a script so I can set an AWS service to generate reports, problem is, within Rstudio (knit button) it works fine but if I try to generate the document using rmarkdown::render('diagnostic.Rmd',output_format =  pdf_document(latex_engine = "pdflatex"), output_file = "diagnostique.pdf")I get this error:

```<code>! Missing $ inserted.
<inserted text>
                $
l.141 \$\ge
pandoc: Error producing PDF
Error: pandoc document conversion failed with error 43
</code>```

Note that I'm using engine = pdflatexwhich produces the results I want, I've also tried xelatex and lualatex with success using lualatexwith a huge cost in quality (reports generated with lualatex do not compile as expected).

I have looked everywhere for this missing $without finding the mistake.
Any advice on where to search or what to do would be much appreciated.

答:
The error is TeX's error.

So, line 141 mean line 141 of TeX file, not Rmd file.

Keep your intermediate TeX file and check line 141 of it.

YAML front matter is like this:

```<code>---
title: "Title"
output:
  pdf_document:
    keep_tex: true
---
</code>```

http://rmarkdown.rstudio.com/pdf_document_format.html#keeping_intermediate_tex

Title: Rmarkdown render from script

Body:
I'm trying to knit an Rmd to pdf from a script so I can set an AWS service to generate reports, problem is, within Rstudio (knit button) it works fine but if I try to generate the document using rmarkdown::render('diagnostic.Rmd',output_format =  pdf_document(latex_engine = "pdflatex"), output_file = "diagnostique.pdf")I get this error:

! Missing $ inserted.
<inserted text>
                $
l.141 \$\ge
pandoc: Error producing PDF
Error: pandoc document conversion failed with error 43

Note that I'm using engine = pdflatexwhich produces the results I want, I've also tried xelatex and lualatex with success using lualatexwith a huge cost in quality (reports generated with lualatex do not compile as expected).

I have looked everywhere for this missing $without finding the mistake.
Any advice on where to search or what to do would be much appreciated.

Body:
The error is TeX's error.

So, line 141 mean line 141 of TeX file, not Rmd file.

Keep your intermediate TeX file and check line 141 of it.

YAML front matter is like this:

---
title: "Title"
output:
  pdf_document:
    keep_tex: true
---

http://rmarkdown.rstudio.com/pdf_document_format.html#keeping_intermediate_tex


问:
Prefix for testing methods in Unit: "test" vs "should"
It is a common practice to prefix the tests method names in JUnit with "test". But in the last few years, some people changed this to the prefix "should".

If I want to test the customer creation in a database, I would normally name the method "testCustomerCreation". However, some people would name "shouldCreateCustomer".

This is a lot of personal taste when I am the only person in the project or when everyone else in the project agrees with me. But when/where this is not the case, some divergences or inconsistent mixes starts to shows up.

I readed somewhere an article of a guy that named his methods like "testShouldCreateCustomer", and for this reason he decided to drop the "test" prefix. But in fact he wasn't prefixing with "test", he was using "testShould" and changed to "should". Obviously, this did not convinced me.

I am personally strongly inclined to stick to "test" prefix because the methods names normally starts with verbs in the infinitive form ("get", "set", "add", "remove", "clear", "send", "receive", "open", "close", "read", "write", "create", "list", "pop", "print", etc, so is "test"). So, prefixing a method name with "should" makes it sound really very strange for me, looks wrong.

So, what is the real good reason to use "should" instead of "test"? What are the great advantages and disadvantages?

答:
I prefer the test suffix. It's possible that you might have a method with a prefix of should in your project e.g. shouldBuy and your test would then be called testShouldBuy because shouldShouldBuy would just look very strange.

I also use the MoreUnit Eclipse plugin which will automatically create a test method prefixed with test when I press Ctrl+U or jump to the test method when I press Ctrl+J. (Although you can configure which prefix it uses.) If you are not consistent with your naming, automated tools such as MoreUnit won't be able to help you with your testing.


问:
Trying to stop removing `div` if it's length at `0` or `1`. can someone help me?
Trying to stop removing div if it's length at 0 or 1. can someone help me?

Here is link: https://jsfiddle.net/Issact/ncqnv8zs/

HTML & JS:

$(document).ready(function() {

  $('.div').click(function() {
    $(this).remove();
    var divLength = $('.main div').length;
    $('.mainLength').text(divLength + " " + 'divs');

    if (divLength === 1) {
      $(this).stop().remove();
    }

  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <div class="div">Div one</div>
  <div class="div">Div Two</div>
  <div class="div">Div Three</div>
  <div class="div">Div Four</div>
</div>

<div class="mainLength">
</div></code>```

答:
Try with this:</p>

```<code>        var divLength = $('.main div').length;
          $('.mainLength').text(divLength + " " + 'divs');

          if(divLength > 1){
            $(this).remove();
          }
</code>```

Body:
Trying to stop removing div if it's length at 0 or 1. can someone help me?

Here is link: https://jsfiddle.net/Issact/ncqnv8zs/

HTML & JS:

$(document).ready(function() {

  $('.div').click(function() {
    $(this).remove();
    var divLength = $('.main div').length;
    $('.mainLength').text(divLength + " " + 'divs');

    if (divLength === 1) {
      $(this).stop().remove();
    }

  });
});

Div one

Div Two

Div Three

Div Four

Body:
Try with this:

        var divLength = $('.main div').length;
          $('.mainLength').text(divLength + " " + 'divs');

          if(divLength > 1){
            $(this).remove();
          }


问:
Check any one of given words available in a string Java
Hello i am trying to implement one logic

1) I'll get multiple messages
(ex message:
Solution not working,
Missed something,
Message Failed,
Working as expected
)

2) I have list words (Not working,Missed,Failed)

I need to consider the messages only which contains any one of the words

have tried like string.contains(word1) || string.contains(word2) but there is n number of words.
Thank you

答:
Here is complete solution for your problem :

```<code>package com.sujit;

import java.util.ArrayList;
import java.util.List;

public class CompareMessages{
    public static void main(String[] args) {
        //Assume the messages as per you said
        List<String> messages = new ArrayList<>();
        messages.add("Solution not working");
        messages.add("Message Failed");
        messages.add("Missed something");
        messages.add("This message will be ignored");

        //Your standard list of words
        List<String> list = new ArrayList<>();
        list.add("Not working");
        list.add("missed");
        list.add("failed");

        Integer count=0;
        String msg = null;  //this will store which message will be ignored
        for (String string : messages) {
            for(String standard : list) {
                if(string.toLowerCase().contains(standard.toLowerCase())){ //check if message if present in your standard list
                    count = 1;  //if it is present, Count becomes 1
                    if(count==1){
                        msg = null;
                        break;   // we can break the loop for current message to be checked with standard list if it is present
                    }
                }
                else{
                    count=0;   // if the message is not your standard, then count becomes 0
                    msg = string;
                }
            }
        }
        if(count==0){
            System.out.println(msg);  //finally you can get which messages is wrong according to your standard list
        }
    }
}
</code>```

Let me know if you face any issue while understanding my code

Body:
Here is complete solution for your problem :

package com.sujit;

import java.util.ArrayList;
import java.util.List;

public class CompareMessages{
    public static void main(String[] args) {
        //Assume the messages as per you said
        List<String> messages = new ArrayList<>();
        messages.add("Solution not working");
        messages.add("Message Failed");
        messages.add("Missed something");
        messages.add("This message will be ignored");

        //Your standard list of words
        List<String> list = new ArrayList<>();
        list.add("Not working");
        list.add("missed");
        list.add("failed");

        Integer count=0;
        String msg = null;  //this will store which message will be ignored
        for (String string : messages) {
            for(String standard : list) {
                if(string.toLowerCase().contains(standard.toLowerCase())){ //check if message if present in your standard list
                    count = 1;  //if it is present, Count becomes 1
                    if(count==1){
                        msg = null;
                        break;   // we can break the loop for current message to be checked with standard list if it is present
                    }
                }
                else{
                    count=0;   // if the message is not your standard, then count becomes 0
                    msg = string;
                }
            }
        }
        if(count==0){
            System.out.println(msg);  //finally you can get which messages is wrong according to your standard list
        }
    }
}

Let me know if you face any issue while understanding my code


问:
Trouble installing luasocket/lfs using luarocks
I installed luarocks and now I am trying to use it to install luasocket.

My command is

```<code>luarocks install luasocket-2.0.2-3.win32-x86.rock
</code>```

and the response I get is

```<code>C:\Program Files (x86)\LuaRocks\lua\luarocks\command_line.lua:186: bad argument #1 to 'require' (string expected, got table)
</code>```

The line of code in command_line.lua giving trouble is

```<code>if commands[command] then
    local cmd = require(commands[command])
</code>```

and putting trace writes in the code reveals that commands[command] is indeed a table, of length zero.

This sort of fundamental runtime error is way beyond anything a Lua novice can be expected to fix. Any suggestions?

Edit

Turns out it's not just luasocket. I get the same problem with

```<code>luarocks install luafilesystem
</code>```

答:
Turns out that this is caused by having an old LuaRocks 2.0.10 installation that I wasn't aware of. It was put there by a failed attempt to install LuaDist-Batteries.

Solution here: https://github.com/luarocks/luarocks/issues/714 .

Body:
I installed luarocks and now I am trying to use it to install luasocket.

My command is

luarocks install luasocket-2.0.2-3.win32-x86.rock

and the response I get is

C:\Program Files (x86)\LuaRocks\lua\luarocks\command_line.lua:186: bad argument #1 to 'require' (string expected, got table)

The line of code in command_line.lua giving trouble is

if commands[command] then
    local cmd = require(commands[command])

and putting trace writes in the code reveals that commands[command] is indeed a table, of length zero.

This sort of fundamental runtime error is way beyond anything a Lua novice can be expected to fix. Any suggestions?

Edit

Turns out it's not just luasocket. I get the same problem with

luarocks install luafilesystem


问:
Postgres Encryption of configuration files
Currently in Postgres the largest security hole is the .conf files that the database relies on, this is because someone with access to the system (not necessarily the database) can modify the files and gain entry.  Because of this I am seeking out resources on how to encrypt those .conf files and then decrypt them during each session of the database.  Performance is not really an issue at this point.  Does anyone have any resources on this or has anyone developed any prototypes that utilize this functionality?

Edit

Since there seems to be some confusion here about what it is I am asking.  The scenario can best be illustrated on a Windows box with the following groups:

1) Administrators  System Administrators

2) Database Administrators  Postgres Administrators

3) Auditors Security Auditors

The Auditors group typically needs access to log files and configuration files to ensure system security.  However, the issue comes when a member of the Auditors group needs to view the Postgres configuration and log files.  If this member decides that they want to access the database even though they do not have a database account it is a very short task to break in .  How does one go about preventing this?  Answers such as: Get better auditors are quite poor as you can never fully predict what people will do.

答: So, are you trying to prevent root from making changes?  Cause just a normal user can't change those files, and if you don't trust root, you've already lost.</p>


问:
Remove duplicate records by comparing two data tables in c#
I have two data tables. One have all records and other data table have only few records. I have to insert records in third table which are not in second table but want to do it only with c# not linq.I tried with for and foreach loop but not getting exact.</p>

答:
i would not recommend to do this, like ever. Foreach within foreach is a very bad idea, there are better solutions (like merging) out there. Try consider using linq. But you could try something like</p>

```<code>foreach (datarow dr1 in datatable1)
{
    bool add = true;

    foreach (datarow dr2 in datatable2)
    {
         // Make sure the itemarray[x] is the proper indetifier
         if (dr2.itemarray[0].toString() == dr1.itemarray[0])
         {
             add = false;
             break;
         }
    }
    if (add)
    {
        // add record to datatable3
    }
}
</code>```

Body:
i would not recommend to do this, like ever. Foreach within foreach is a very bad idea, there are better solutions (like merging) out there. Try consider using linq. But you could try something like

foreach (datarow dr1 in datatable1)
{
    bool add = true;

    foreach (datarow dr2 in datatable2)
    {
         // Make sure the itemarray[x] is the proper indetifier
         if (dr2.itemarray[0].toString() == dr1.itemarray[0])
         {
             add = false;
             break;
         }
    }
    if (add)
    {
        // add record to datatable3
    }
}


问:
Unable to read files by using akka stream
We are trying to read files from akka streams. Files contains logs and the application is simple for write the logs into new files. But when, run our program, we are getting unexpected output. Our code is a below:

```<code>class LogsAkkaStream {

  implicit val system = ActorSystem("AkkaStreams")
  implicit val ec = system.dispatcher
  implicit val materializer = ActorMaterializer()

  val source: Source[ByteString, Future[IOResult]] = FileIO.fromPath(Paths.get("/home/harmeet/workspace/mylogs.logs"))
  val sink: Sink[ByteString, Future[IOResult]] = FileIO.toPath(Paths.get("."), Set(CREATE, WRITE, APPEND))
  val runnableGraph: RunnableGraph[Future[IOResult]] = source.to(sink)

  runnableGraph.run().foreach { result =>
    println(s"${result.status}, ${result.count} bytes read. ")
  }
}

object LogsAkkaStream extends App {
  new LogsAkkaStream
}
</code>```

mylogs.logs contains 1000 line record, but output of this program is : Success(Done), 0 bytes read. Still, we are not getting the actual program.

答:
When I put in known-working paths to files then it works in my REPL.

You'll want to make sure the path to your source file is correct, and you'll want to put a correct destination path to a file.

Also, you'll want to use toMat instead of to so that you can get both the IOResult of the Read operations as well as the Write operations. (I'd recommend doing _ zip _ so you get a Future[(IOResult, IOResult)]).

Body:
We are trying to read files from akka streams. Files contains logs and the application is simple for write the logs into new files. But when, run our program, we are getting unexpected output. Our code is a below:

class LogsAkkaStream {

  implicit val system = ActorSystem("AkkaStreams")
  implicit val ec = system.dispatcher
  implicit val materializer = ActorMaterializer()

  val source: Source[ByteString, Future[IOResult]] = FileIO.fromPath(Paths.get("/home/harmeet/workspace/mylogs.logs"))
  val sink: Sink[ByteString, Future[IOResult]] = FileIO.toPath(Paths.get("."), Set(CREATE, WRITE, APPEND))
  val runnableGraph: RunnableGraph[Future[IOResult]] = source.to(sink)

  runnableGraph.run().foreach { result =>
    println(s"${result.status}, ${result.count} bytes read. ")
  }
}

object LogsAkkaStream extends App {
  new LogsAkkaStream
}

mylogs.logs contains 1000 line record, but output of this program is : Success(Done), 0 bytes read. Still, we are not getting the actual program.


问:
Use fade-in and delay with ng-repeat to display list items
I am trying to display list items one by one with some delay. For that I managed to do something like this:

```<code>  $("#dropDownMenu li").each(function(i) {
    $(this).delay(1000 * i).fadeIn(100);
});
</code>```

It works good when list is something like

```<code>    <li>one</li>
    <li>two</li>
    <li>three</li>
</code>```

JSFiddle

But it does't work when I use ng-repeat in a list, something like this

```<code><li ng-repeat="time in msg.time">{{time}}<li>
</code>```

How can I make it work with ng-repeat?

答:
You should add items one by one with delay via $timeout:

angular.module('app', [])
.controller('ctrl', ['$scope', '$timeout', function($scope, $timeout) {
    var items = [
        'First',
        'Second',
        'Third',
        'Fourth',
        'Fifth'
      ];

    $scope.items = [];

    function showNext(array, index){
      $timeout(function(x){
        $scope.items.push(x);
        if(++index < array.length)
          showNext(array, index);
      }, 1000, true, array[index])
    }

    showNext(items, 0);

}])```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//code.angularjs.org/snapshot/angular.min.js"></script>

<ul ng-app='app' ng-controller='ctrl'>
  <li ng-repeat='item in items'>{{item}}</li>
</ul></code>```

Body:
I am trying to display list items one by one with some delay. For that I managed to do something like this:

  $("#dropDownMenu li").each(function(i) {
    $(this).delay(1000 * i).fadeIn(100);
});

It works good when list is something like

one

two

three

JSFiddle

But it does't work when I use ng-repeat in a list, something like this

{{time}}

How can I make it work with ng-repeat?

Body:
You should add items one by one with delay via $timeout:

angular.module('app', [])
.controller('ctrl', ['$scope', '$timeout', function($scope, $timeout) {
    var items = [
        'First',
        'Second',
        'Third',
        'Fourth',
        'Fifth'
      ];

    $scope.items = [];

    function showNext(array, index){
      $timeout(function(x){
        $scope.items.push(x);
        if(++index < array.length)
          showNext(array, index);
      }, 1000, true, array[index])
    }

    showNext(items, 0);

}])

<script src="//code.angularjs.org/snapshot/angular.min.js"></script>

<ul ng-app='app' ng-controller='ctrl'>
  <li ng-repeat='item in items'>{{item}}</li>
</ul>


问:
C# MVVM pattern update UI in Infinite loop thread?
I have a background thread to listen data, so this infinite loop to output data.

And, I using a ObservableCollection to bind a ListBox and show log.

I try to use Dispather.BeginInvoke, but no use, it not realtime. I have no idea for update UI in MVVM.

xaml

```<code><ListBox x:Name="lsb_log" Width="auto" ItemsSource="{Binding DisplayLogs}"/>
</code>```

code

```<code>private ObservableCollection<string> _displayLogs;
public ObservableCollection<string> DisplayLogs
{
     get
     {
         return _displayLogs;
     }
}

public Testpro()
{
    _displayLogs = new ObservableCollection<string>();

    Task.Run(new Action(outputData));
}

private void outputData()
{
    string str = "";
    while (true)
    {
        string newString = GetInfoString();

        if (string.IsNullOrWhiteSpace(newString) || str == newString)
            continue;

        str = newString;

        Debug.WriteLine(str);
        Application.Current.Dispatcher.BeginInvoke((Action)delegate ()
        {
                DisplayLogs.Add(str);
        });
    }
}
</code>```

*Edit:

GetInfoString will call by a dll file.

答:
You can use async-await therefore. Your OutputData-Method can look something like:

```<code>private async void OutputData(IProgress<string> onProgress)
{
    await Task.Factory.StartNew(() =>
    {
        string str = string.Empty;

        while (true)
        {
            string newString = GetInfoString();
            if(string.IsNullOrWhiteSpace(newString) || str == newString)
                continue;

            str = newString;

            // call the UI to update your bound collection
            onProgress.Report(str);

            // give the ui some time to respond before continue with your endless-loop
            Thread.Sleep(200);
        }
    });
}
</code>```

And you can call this method with:

```<code>OutputData(new Progress<string>((str) =>
{
    DisplayLogs.Add(str);
}));
</code>```

That's it

Body:
I have a background thread to listen data, so this infinite loop to output data.

And, I using a ObservableCollection to bind a ListBox and show log.

I try to use Dispather.BeginInvoke, but no use, it not realtime. I have no idea for update UI in MVVM.

xaml

<ListBox x:Name="lsb_log" Width="auto" ItemsSource="{Binding DisplayLogs}"/>

code

private ObservableCollection<string> _displayLogs;
public ObservableCollection<string> DisplayLogs
{
     get
     {
         return _displayLogs;
     }
}

public Testpro()
{
    _displayLogs = new ObservableCollection<string>();

    Task.Run(new Action(outputData));
}

private void outputData()
{
    string str = "";
    while (true)
    {
        string newString = GetInfoString();

        if (string.IsNullOrWhiteSpace(newString) || str == newString)
            continue;

        str = newString;

        Debug.WriteLine(str);
        Application.Current.Dispatcher.BeginInvoke((Action)delegate ()
        {
                DisplayLogs.Add(str);
        });
    }
}

*Edit:

GetInfoString will call by a dll file.

Body:
You can use async-await therefore. Your OutputData-Method can look something like:

private async void OutputData(IProgress<string> onProgress)
{
    await Task.Factory.StartNew(() =>
    {
        string str = string.Empty;

        while (true)
        {
            string newString = GetInfoString();
            if(string.IsNullOrWhiteSpace(newString) || str == newString)
                continue;

            str = newString;

            // call the UI to update your bound collection
            onProgress.Report(str);

            // give the ui some time to respond before continue with your endless-loop
            Thread.Sleep(200);
        }
    });
}

And you can call this method with:

OutputData(new Progress<string>((str) =>
{
    DisplayLogs.Add(str);
}));

That's it


问:
C++/CLI convert existing application do managed code
I've got an existing application written in Borland C++ Builder. My client wants it rewritten in C#/WPF. This requires a lot of work and is a complex task because I need to rewrite the whole (huge) algorithm. I was thinking of a way to reuse the code and to be able to create only GUI in C#/WPF. Is this possible? Would that be easy? How can I make C++ classes visible to .NET ?

If you could give me brief answers with some links/examples I would be grateful.

答:
Well, As far as i can remember by head, you can use interops for that matter.
It is in fact better to continue using a code that was for a long time tested, and is stable. With net Interop Services you can create a very good bridge between the new app and the old one.

examples:

http://www.daniweb.com/forums/thread136041.html

http://msdn.microsoft.com/en-us/library/aa645736%28v=vs.71%29.aspx

http://www.codeguru.com/cpp/cpp/cpp_managed/interop/article.php/c6867


问:
Kotlin in xml onClick not work
I learning kotlin, and now for me not cearly some moment. I have xml

```<code><ImageView
                    android:id="@+id/aries"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="10dp"
                    android:tag="1"
                    android:onClick="clickItemHoro"
                    android:src="@drawable/aries" />
</code>```

and fragment

```<code>class ChooseYourHoroscope : Fragment(){

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.fragment_welcome_old, container, false)

        return view;
    }

    fun clickItemHoro(v: View?){
        Log.e("clickItemHoro", v!!.tag.toString())
    }

}
</code>```

when i click button i have error:

Could not find method clickItemHoro(View) in a parent or ancestor
  Context for android:onClick attribute defined on view class
  android.support.v7.widget.AppCompatImageView with id 'aries'

why it happen? Code vary simple, but it not work, i cant understand why

答:
As mentioned above it's a good idea to add the Kotlin extensions, additionally you could set an onClickListener on the ImageView directly in your code instead of declaring the method in your xml files: onClick:

aries.setOnClickListener { doSomething() }

Title: Kotlin in xml onClick not work

Body:
I learning kotlin, and now for me not cearly some moment. I have xml

<ImageView
                    android:id="@+id/aries"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="10dp"
                    android:tag="1"
                    android:onClick="clickItemHoro"
                    android:src="@drawable/aries" />

and fragment

class ChooseYourHoroscope : Fragment(){

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.fragment_welcome_old, container, false)

        return view;
    }

    fun clickItemHoro(v: View?){
        Log.e("clickItemHoro", v!!.tag.toString())
    }

}

when i click button i have error:

Could not find method clickItemHoro(View) in a parent or ancestor
  Context for android:onClick attribute defined on view class
  android.support.v7.widget.AppCompatImageView with id 'aries'

why it happen? Code vary simple, but it not work, i cant understand why


问:
Login in with Alamofire : Could not cast value of type '__NSSingleEntryDictionaryI' (0x103860210) to 'NSString' (0x102e66c40)
Hi I am new to programming and I'm stuck at this error. I am logging in from Xcode to MySQL, but I am unable to move on to home page. My code works fine in PHP and I am unable to login.

Below is my code:

```<code>@IBAction func Login(_ sender: UIButton)
{
    let URL_USER_REGISTER = "http://localhost/login.php"

    let parameters: Parameters = [
            "username":username.text!,
            "password":password.text!
    ]

    Alamofire.request(URL_USER_REGISTER, method: .post, parameters: parameters).responseJSON
    {
        response in
        //printing response
        print(response)

        if let result = response.result.value
        {
            let resultValue:String = result as! String;

            if (resultValue == "login_success")
            {
                //login is successful
                UserDefaults.standard.set(true, forKey: "isUserLoggedIn")
                UserDefaults.standard.synchronize();

                self.dismiss(animated: true, completion: nil)
            }
        }
    }
}
</code>```

It returns:

login_success Could not cast value of type
  '__NSSingleEntryDictionaryI' (0x103860210) to 'NSString'
  (0x102e66c40).

That's why I am unable to move on to my home page.

答:
Try another way of retrieving your http result and adding a failure enclosure. Not knowing the output format of you login.php doesn't help but it should look like this:

```<code>@IBAction func Login(_ sender: UIButton)
{
    let URL_USER_REGISTER = "http://localhost/login.php"

    let parameters: Parameters=[

        "username":username.text!,

        "password":password.text!

         ]

    Alamofire.request(.POST, URL_USER_REGISTER, parameters: parameters, encoding: ParameterEncoding.URL).responseJSON { result in
        switch result {
            case .Success(let data):
                let json = JSON(data)
                let resultValue = json["value"].string
                if (resultValue == "login_success")
                {
                    //login is successful
                    UserDefaults.standard.set(true, forKey: "isUserLoggedIn")
                    UserDefaults.standard.synchronize();

                    self.dismiss(animated: true, completion: nil)
                }
            case .Failure(_, let error):
                print("Request failed with error: \(error)")
        }
    }

}
</code>```

Source: How to get the result value of Alamofire.request().responseJSON in swift 2?

Body:
Hi I am new to programming and I'm stuck at this error. I am logging in from Xcode to MySQL, but I am unable to move on to home page. My code works fine in PHP and I am unable to login.

Below is my code:

@IBAction func Login(_ sender: UIButton)
{
    let URL_USER_REGISTER = "http://localhost/login.php"

    let parameters: Parameters = [
            "username":username.text!,
            "password":password.text!
    ]

    Alamofire.request(URL_USER_REGISTER, method: .post, parameters: parameters).responseJSON
    {
        response in
        //printing response
        print(response)

        if let result = response.result.value
        {
            let resultValue:String = result as! String;

            if (resultValue == "login_success")
            {
                //login is successful
                UserDefaults.standard.set(true, forKey: "isUserLoggedIn")
                UserDefaults.standard.synchronize();

                self.dismiss(animated: true, completion: nil)
            }
        }
    }
}

It returns:

login_success Could not cast value of type
  '__NSSingleEntryDictionaryI' (0x103860210) to 'NSString'
  (0x102e66c40).

That's why I am unable to move on to my home page.

Body:
Try another way of retrieving your http result and adding a failure enclosure. Not knowing the output format of you login.php doesn't help but it should look like this:

@IBAction func Login(_ sender: UIButton)
{
    let URL_USER_REGISTER = "http://localhost/login.php"

    let parameters: Parameters=[

        "username":username.text!,

        "password":password.text!

         ]

    Alamofire.request(.POST, URL_USER_REGISTER, parameters: parameters, encoding: ParameterEncoding.URL).responseJSON { result in
        switch result {
            case .Success(let data):
                let json = JSON(data)
                let resultValue = json["value"].string
                if (resultValue == "login_success")
                {
                    //login is successful
                    UserDefaults.standard.set(true, forKey: "isUserLoggedIn")
                    UserDefaults.standard.synchronize();

                    self.dismiss(animated: true, completion: nil)
                }
            case .Failure(_, let error):
                print("Request failed with error: \(error)")
        }
    }

}

Source: How to get the result value of Alamofire.request().responseJSON in swift 2?


问:
Why is there an object file in my "Binary and Entitlements" list
When I send my .ipa file to iTunesConnect via Xcode 6.2, there is a compiled object file (MoneyPowerLoveVC.o) listed under "Binary and Entitlements".

It doesn't appear to hurt anything, but it bugs me.  Why is it there?

答: I have encountered such a problem, the problem has been solved, need to find a folder that contains the files in the  "Binary and Entitlements" list, I found this folder repeat in my project, a yellow folder, a blue folder, delete duplicate blue folder，you can solve the problem.</p>


问:
Server-to-Android feedback: Best practice?
In our app we have a quite a lot of settings, some only applicable to the server (like privacy settings) and others mostly to the app (like location or text-to-speech settings).

We are now moving these settings from native (where most will report back to the server) to webviews. That means loading a settings webpage in a webview on the app thus acting (changing settings) directly on the server.

In case a webview setting should effect the app itself, the server will need to send feedback to the app on the setting change. In this case I could create a receiver to catch a JSON sent back from the server, or use some kind of a silent push notification.

It there a better strait forward way of sending a feedback like that?

答:
I would suggest implementing a push notification based update. The workflow would be as follows:-

Generate a firebase token on the android device and save the token against the current logged in account on the server.

2.When the settings are modified, let the server call the firebase push notification API indicating that a settings change has occurred.

3.In the callback when the push notification is received, make a request to the server asking for the new set of settings (JSON or whatever) and store it offline in the Shared Preferences or Storage.

IMPORTANT: Make sure your push notification callback is called even when the app is closed. (Data Message type of push notification)


问:
xpages register a anonymous user to names.nsf with login name and email
Case: Create a web application to register user through the Name.nsf on the server.

userA

userB

means there have 2 database related.

First database: Anonymous(web) allow to key in there information through the database.

Second database: Names.nsf

First database with "full" access user must be allow to create a user in the names nsf or create an email address for user!

Question

Do i just need to link the names.nsf in server view ($VIMPeopleByLastName) and create document of those web-user?

答: Look at the documentation regarding Directory Assistance. It sounds like that would be the approach required.</p>


问:
Using JDBC in setup for a Jmeter Junit test
I was trying to use the JDBC to connect to my MySQL database in the setup and teardown methods of my Junit tests that are being run through Jmeter. Jmeter will create multiple threads, each of which will run one instance of my test. </p>

<p>The issue that I run into, is if I instantiate my datasource in the setup of my Junit test, then my connection pool runs out of connections. Is there a way to design my test so that this does not happen? I'm trying to avoid increasing my max MySQL connections to solve this issue. </p>

答:
Yes, make sure that each test closes the connection and returns it to the pool when it's done.  Sounds like that's not happening, but I can't be sure.

If that's not the case, I'd recommend tuning your connection and thread pool sizes better so you don't run out.

Body:
I was trying to use the JDBC to connect to my MySQL database in the setup and teardown methods of my Junit tests that are being run through Jmeter. Jmeter will create multiple threads, each of which will run one instance of my test.

The issue that I run into, is if I instantiate my datasource in the setup of my Junit test, then my connection pool runs out of connections. Is there a way to design my test so that this does not happen? I'm trying to avoid increasing my max MySQL connections to solve this issue.


问:
Which Google api to use for getting user's first name, last name, picture, etc?
I have the oauth authorization with google working correctly and am getting data from the contacts api. Now, I want to programmatically get a gmail user's first name, last name and picture. Which google api can i use to get this data?</p>

答:
Use this code to get firstName and lastName of a google user:

```<code>final HttpTransport transport = new NetHttpTransport();
final JsonFactory jsonFactory = new JacksonFactory();
GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(transport, jsonFactory)
        .setAudience(Arrays.asList(clientId))
        .setIssuer("https://accounts.google.com")
        .build();

GoogleIdToken idToken = null;
try {
    idToken = verifier.verify(googleAuthenticationPostResponse.getId_token());
} catch (GeneralSecurityException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
GoogleIdToken.Payload payload = null;
if (idToken != null) {
    payload = idToken.getPayload();
}
String firstName = payload.get("given_name").toString();
String lastName = payload.get("family_name").toString();
</code>```

Body:
Use this code to get firstName and lastName of a google user:

final HttpTransport transport = new NetHttpTransport();
final JsonFactory jsonFactory = new JacksonFactory();
GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(transport, jsonFactory)
        .setAudience(Arrays.asList(clientId))
        .setIssuer("https://accounts.google.com")
        .build();

GoogleIdToken idToken = null;
try {
    idToken = verifier.verify(googleAuthenticationPostResponse.getId_token());
} catch (GeneralSecurityException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
GoogleIdToken.Payload payload = null;
if (idToken != null) {
    payload = idToken.getPayload();
}
String firstName = payload.get("given_name").toString();
String lastName = payload.get("family_name").toString();

ContentLicense: CC BY-SA 4.0


问:
how decrease click for opening contact in Android
I'm new to android. I want to open contacts after getting permission. My problem is at start I need to click the button tow time, one for getting permission and one for opening contacts.

Is there any way to open contacts immediately after getting permission without any need for 2nd click

答:
yes you can handle request permission result like this

1.ask permission in button click event

```<code> btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String permission = android.Manifest.permission.READ_CONTACTS;
            if (ActivityCompat.checkSelfPermission(SearchCityClass.this, permission)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(SearchCityClass.this, new String[]
                        {permission}, PERMISSION_CODE);

            } else {
                    isPermissionGranted(true);

            }
        }

    });
</code>```

2. handle permission result in onRequestPermissionsResult

```<code>@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                       @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == PERMISSION_CODE) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

             isPermissionGranted(true);

        } else {

             isPermissionGranted(false);
        }
    }

}
</code>```

3.now create a method for like this

```<code>public void isPermissionGranted(boolean permission) {
    if (!permission) {
      // permission not granted
    } else {
     // add here your code beacuse permisiion is granted
</code>```

}

Body:
yes you can handle request permission result like this

1.ask permission in button click event

 btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String permission = android.Manifest.permission.READ_CONTACTS;
            if (ActivityCompat.checkSelfPermission(SearchCityClass.this, permission)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(SearchCityClass.this, new String[]
                        {permission}, PERMISSION_CODE);

            } else {
                    isPermissionGranted(true);

            }
        }

    });

2. handle permission result in onRequestPermissionsResult

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                       @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == PERMISSION_CODE) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

             isPermissionGranted(true);

        } else {

             isPermissionGranted(false);
        }
    }

}

3.now create a method for like this

public void isPermissionGranted(boolean permission) {
    if (!permission) {
      // permission not granted
    } else {
     // add here your code beacuse permisiion is granted

}


问:
Java - access to variable within inner class or assign a value to final variable
I need to create several buttons and upload files. So I want to create a function to set these buttons. However, I'm getting a compilation error inside of my setNewButton.

My code is shown as below:

public class Solution extends JFrame {
    private static final String FILE_NAME_1 = "my file1";
    private File file1;
    private void setNewButton(Container contentPane, final String fileName, String format, File file) {
        contentPane.add(Box.createVerticalStrut(5));
        final Label label = new Label("Select " + fileName + " in ." + format +" format");
        contentPane.add(label);
        contentPane.add(Box.createVerticalStrut(10));
        Button selection = new Button("Select " + fileName);
        contentPane.add(selection);
        selection.addActionListener(new FileSelectionListener("Only " + format + " is allowed", format) {
            @Override
            protected void setSelection(File selectedFile) {
                file = selectedFile;  // compilation error here
                label.setText("Selected" + fileName + selectedFile.getAbsolutePath());
            }
        });
    }

    public uploadFiles() {
        Container contentPane = this.getContentPane();
        setNewButton(contentPane, FILE_NAME_1, "xls", file1);
    }
}
```

<p>The error is: <code>Variable file is accessed from within inner class, needs to be declared final</code></p>

<p>I have checked some similar questions in stackoverflow. I know <code>file</code> has to be final like <code>label</code> and <code>fileName</code> here.</p>

<p>However <code>file</code> here could be <code>final</code> since I would like to assign <code>selectedFile</code> to it.</p>

<p>I would like to know if there is any walkaround for this problem.</p>

<p>Any help would be appreciated. :)</p>

<p>Thanks to @M. Prokhorov and @Chang Liu.
According to  JLS 8.1.3. Inner Classes and Enclosing Instances</p>

<blockquote>
  <p>Any local variable, formal parameter, or exception parameter used but not declared in an inner class must either be declared final or be effectively final, or a compile-time error occurs where the use is attempted.</p>
</blockquote>

<p>So when I tried to send a parameter <code>file</code> inside <code>FileSlectionListener</code>, there will be a compile error. However, the member <code>file1</code> inside Solution is not local variable, so if I delete the <code>file</code> from my method, there will be no error. So @talex 's anwser is right in this case.</p>

<p>However since my problem is to find a method to pass a <code>File</code> to inner class and assign the variable with <code>selectedFile</code>, I couldn't find a way for it. My workaround is based on @Chang Liu's answer.</p>

<p>My revised code is as below:</p>

<pre class="lang-java prettyprint-override"><code>public class Solution extends JFrame {
    private static final String FILE_NAME_1 = "my file1";
    private File file1;
    private void setNewButton(Container contentPane, final String fileName, String format) {
        contentPane.add(Box.createVerticalStrut(5));
        final Label label = new Label("Select " + fileName + " in ." + format +" format");
        contentPane.add(label);
        contentPane.add(Box.createVerticalStrut(10));
        Button selection = new Button("Select " + fileName);
        contentPane.add(selection);
        selection.addActionListener(new FileSelectionListener("Only " + format + " is allowed", format) {
            @Override
            protected void setSelection(File selectedFile) {
                setFile(selectedFile, fileName);  // no compilation error here
                label.setText("Selected" + fileName + selectedFile.getAbsolutePath());
            }
        });
    }

    public uploadFiles() {
        Container contentPane = this.getContentPane();
        setNewButton(contentPane, FILE_NAME_1, "xls", file1);
    }

    private void setFile(File file, String fileName) {
        switch (fileName) {
            case FILE_NAME_1:
                sollFile = file;
                break;
            default:
                throw new AssertionError("Unknown File");
        }
    }
}
</code>```

Still, welcome to give me any advise if you have a better answer. :)

答:
As stated from M. Prokhorov's comment, if you go to the JLS 8.1.3. Inner Classes and Enclosing Instances, you will see it is stated that:

Any local variable, formal parameter, or exception parameter used but not declared in an inner class must either be declared final or be effectively final, or a compile-time error occurs where the use is attempted.

Similar rules on variable use apply in the body of a lambda expression.

So the parameter File file of method setNewButton as a variable is not effectively final in your inner class new FileSelectionListener's method setSelection, i.e., you assigned a new value to this variable, which makes it not effectively final.

Some workaround to resolve this compile-time error, by defining a setter for file instead of passing an argument (but I am not sure whether this is a best practice):

```<code>public class Solution extends JFrame {
    private static final String FILE_NAME_1 = "Selected SOLL:";
    private File file;
    private void setNewButton(Container contentPane, final String fileName, String format) {
        contentPane.add(Box.createVerticalStrut(5));
        final Label label = new Label("Select " + fileName + " in ." + format +" format");
        contentPane.add(label);
        contentPane.add(Box.createVerticalStrut(10));
        Button selection = new Button("Select " + fileName);
        contentPane.add(selection);
        selection.addActionListener(new FileSelectionListener("Only " + format + " is allowed", format) {
            @Override
            protected void setSelection(File selectedFile) {
                setFile(selectedFile);  // call file setter here
                label.setText("Selected" + fileName + selectedFile.getAbsolutePath());
            }
        });
    }

    // define a setter for your File member
    private void setFile(File file) {
        this.file = file;
    }

    public void uploadFiles() {
        Container contentPane = this.getContentPane();
        setNewButton(contentPane, FILE_NAME_1, "xls");
    }
}
</code>```

Body:
I need to create several buttons and upload files. So I want to create a function to set these buttons. However, I'm getting a compilation error inside of my setNewButton.

My code is shown as below:

public class Solution extends JFrame {
    private static final String FILE_NAME_1 = "my file1";
    private File file1;
    private void setNewButton(Container contentPane, final String fileName, String format, File file) {
        contentPane.add(Box.createVerticalStrut(5));
        final Label label = new Label("Select " + fileName + " in ." + format +" format");
        contentPane.add(label);
        contentPane.add(Box.createVerticalStrut(10));
        Button selection = new Button("Select " + fileName);
        contentPane.add(selection);
        selection.addActionListener(new FileSelectionListener("Only " + format + " is allowed", format) {
            @Override
            protected void setSelection(File selectedFile) {
                file = selectedFile;  // compilation error here
                label.setText("Selected" + fileName + selectedFile.getAbsolutePath());
            }
        });
    }

    public uploadFiles() {
        Container contentPane = this.getContentPane();
        setNewButton(contentPane, FILE_NAME_1, "xls", file1);
    }
}

The error is: Variable file is accessed from within inner class, needs to be declared final

I have checked some similar questions in stackoverflow. I know file has to be final like label and fileName here.

However file here could be final since I would like to assign selectedFile to it.

I would like to know if there is any walkaround for this problem.

Any help would be appreciated. :)

Thanks to @M. Prokhorov and @Chang Liu.
According to  JLS 8.1.3. Inner Classes and Enclosing Instances

Any local variable, formal parameter, or exception parameter used but not declared in an inner class must either be declared final or be effectively final, or a compile-time error occurs where the use is attempted.

So when I tried to send a parameter file inside FileSlectionListener, there will be a compile error. However, the member file1 inside Solution is not local variable, so if I delete the file from my method, there will be no error. So @talex 's anwser is right in this case.

However since my problem is to find a method to pass a File to inner class and assign the variable with selectedFile, I couldn't find a way for it. My workaround is based on @Chang Liu's answer.

My revised code is as below:

public class Solution extends JFrame {
    private static final String FILE_NAME_1 = "my file1";
    private File file1;
    private void setNewButton(Container contentPane, final String fileName, String format) {
        contentPane.add(Box.createVerticalStrut(5));
        final Label label = new Label("Select " + fileName + " in ." + format +" format");
        contentPane.add(label);
        contentPane.add(Box.createVerticalStrut(10));
        Button selection = new Button("Select " + fileName);
        contentPane.add(selection);
        selection.addActionListener(new FileSelectionListener("Only " + format + " is allowed", format) {
            @Override
            protected void setSelection(File selectedFile) {
                setFile(selectedFile, fileName);  // no compilation error here
                label.setText("Selected" + fileName + selectedFile.getAbsolutePath());
            }
        });
    }

    public uploadFiles() {
        Container contentPane = this.getContentPane();
        setNewButton(contentPane, FILE_NAME_1, "xls", file1);
    }

    private void setFile(File file, String fileName) {
        switch (fileName) {
            case FILE_NAME_1:
                sollFile = file;
                break;
            default:
                throw new AssertionError("Unknown File");
        }
    }
}

Still, welcome to give me any advise if you have a better answer. :)

Body:
As stated from M. Prokhorov's comment, if you go to the JLS 8.1.3. Inner Classes and Enclosing Instances, you will see it is stated that:

Any local variable, formal parameter, or exception parameter used but not declared in an inner class must either be declared final or be effectively final, or a compile-time error occurs where the use is attempted.

Similar rules on variable use apply in the body of a lambda expression.

So the parameter File file of method setNewButton as a variable is not effectively final in your inner class new FileSelectionListener's method setSelection, i.e., you assigned a new value to this variable, which makes it not effectively final.

Some workaround to resolve this compile-time error, by defining a setter for file instead of passing an argument (but I am not sure whether this is a best practice):

public class Solution extends JFrame {
    private static final String FILE_NAME_1 = "Selected SOLL:";
    private File file;
    private void setNewButton(Container contentPane, final String fileName, String format) {
        contentPane.add(Box.createVerticalStrut(5));
        final Label label = new Label("Select " + fileName + " in ." + format +" format");
        contentPane.add(label);
        contentPane.add(Box.createVerticalStrut(10));
        Button selection = new Button("Select " + fileName);
        contentPane.add(selection);
        selection.addActionListener(new FileSelectionListener("Only " + format + " is allowed", format) {
            @Override
            protected void setSelection(File selectedFile) {
                setFile(selectedFile);  // call file setter here
                label.setText("Selected" + fileName + selectedFile.getAbsolutePath());
            }
        });
    }

    // define a setter for your File member
    private void setFile(File file) {
        this.file = file;
    }

    public void uploadFiles() {
        Container contentPane = this.getContentPane();
        setNewButton(contentPane, FILE_NAME_1, "xls");
    }
}


问:
Is there a method for generating a rectangular matrix?
I'm generating networks using the rgnm function from the sna package. E.g.

```<code>int_mat <- rgnm (1,10,33)
</code>```

Is there a method that I can use to produce a non-square matrix (e.g. 10 x 11 matrix) using this or another function?

Thanks!

答:
This seems to do what you want.</p>

```<code>n_rows <- 10; n_cols <- 11; n_1s <- 33
elements <- rep(0, n_rows* n_cols)
elements[sample(1:length(elements), 33)] <- 1
int_mat <- matrix(elements, nrow=n_rows, ncol=n_cols)
</code>```

Body:
I'm generating networks using the rgnm function from the sna package. E.g.

int_mat <- rgnm (1,10,33)

Is there a method that I can use to produce a non-square matrix (e.g. 10 x 11 matrix) using this or another function?

Thanks!

Body:
This seems to do what you want.

n_rows <- 10; n_cols <- 11; n_1s <- 33
elements <- rep(0, n_rows* n_cols)
elements[sample(1:length(elements), 33)] <- 1
int_mat <- matrix(elements, nrow=n_rows, ncol=n_cols)


问:
ASP.NET MVC Set Views folder on controller
If you have created a controller like:

```<code>public class ProjectLoginController : Controller
{
    /// <summary>
    /// GET: /login
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    [AllowAnonymous]
    public ActionResult Login()
    {
        return View();
    }
}
</code>```

It will search for the login view in the ProjectLogin or the Shared folder.

Is it possible to tell MVC for this controller to search in the views folder Account under Viewsinstead of doing:

```<code>return View("~/Views/Account/Login.cshtml");
</code>```

or:

```<code>return View("../Account/Login");
</code>```

答:
Yes you can do this by following ways:

```<code>return View("../Account/Login");
</code>```

or

```<code>return RedirectToAction("LogIn", "Account");
</code>```

Body:
If you have created a controller like:

public class ProjectLoginController : Controller
{
    ///
    /// GET: /login
    ///
    /// <returns></returns>
    [HttpGet]
    [AllowAnonymous]
    public ActionResult Login()
    {
        return View();
    }
}

It will search for the login view in the ProjectLogin or the Shared folder.

Is it possible to tell MVC for this controller to search in the views folder Account under Viewsinstead of doing:

return View("~/Views/Account/Login.cshtml");

or:

return View("../Account/Login");

Body:
Yes you can do this by following ways:

return View("../Account/Login");

or

return RedirectToAction("LogIn", "Account");


问:
Is setting the value of Server.ScriptTimeout enough to prevent page timeouts?
On an administrative page with a long running process we're setting the following:

```<code>protected void Page_Load(object sender, EventArgs e)
{
        this.Server.ScriptTimeout = 300;
        //other code
}
</code>```

Is this enough that should prevent that page from timing out as it does what it needs to? I have no control over the process and how long it runs but we've found that 5 minutes is more than enough time, yet we're still getting intermittent errors of:

```<code>System.Web.HttpException: Request timed out.
</code>```

We've tried upping the value to 600 with really no difference and in any testing we've done we can never get the actual process to run for that long. Is there elsewhere that we need to be setting timeout values that won't affect the entire application and only the specific page we need the longer timeout value on?

答:
I think you should never have a "script" that can take up to 5 min to run in Web App ,expecially into the page load! Why don't you create a web service or somethig that wrap this process? then you can use any Async pattern to invoke it avoiding to make the page stack on one the same call

anyway have a look at the link below for more detail about the Default server time out

http://msdn.microsoft.com/en-us/library/ms524831(VS.90).aspx

Body:
On an administrative page with a long running process we're setting the following:

protected void Page_Load(object sender, EventArgs e)
{
        this.Server.ScriptTimeout = 300;
        //other code
}

Is this enough that should prevent that page from timing out as it does what it needs to? I have no control over the process and how long it runs but we've found that 5 minutes is more than enough time, yet we're still getting intermittent errors of:

System.Web.HttpException: Request timed out.

We've tried upping the value to 600 with really no difference and in any testing we've done we can never get the actual process to run for that long. Is there elsewhere that we need to be setting timeout values that won't affect the entire application and only the specific page we need the longer timeout value on?