问:
On a cpu with constant_tsc and nonstop_tsc, why does my time drift?
I am running this test on a cpu with constant_tsc and nonstop_tsc

```<code>$ grep -m 1 ^flags /proc/cpuinfo | sed 's/ /\n/g' | egrep "constant_tsc|nonstop_tsc"
constant_tsc
nonstop_tsc
</code>```

Step 1: Calculate the tick rate of the tsc:

I calculate _ticks_per_ns as the median over a number of observations. I use rdtscp to ensure in-order execution.

```<code>static const int trials = 13;
std::array<double, trials> rates;

for (int i = 0; i < trials; ++i)
{
    timespec beg_ts, end_ts;
    uint64_t beg_tsc, end_tsc;

    clock_gettime(CLOCK_MONOTONIC, &beg_ts);
    beg_tsc = rdtscp();

    uint64_t elapsed_ns;
    do
    {
        clock_gettime(CLOCK_MONOTONIC, &end_ts);
        end_tsc = rdtscp();

        elapsed_ns = to_ns(end_ts - beg_ts); // calculates ns between two timespecs
    }
    while (elapsed_ns < 10 * 1e6); // busy spin for 10ms

    rates[i] = (double)(end_tsc - beg_tsc) / (double)elapsed_ns;
}

std::nth_element(rates.begin(), rates.begin() + trials/2, rates.end());

_ticks_per_ns = rates[trials/2];
</code>```

Step 2: Calculate starting wall clock time and tsc

```<code>uint64_t beg, end;
timespec ts;

// loop to ensure we aren't interrupted between the two tsc reads
while (1)
{
    beg = rdtscp();
    clock_gettime(CLOCK_REALTIME, &ts);
    end = rdtscp();

    if ((end - beg) <= 2000) // max ticks per clock call
        break;
}

_start_tsc        = end;
_start_clock_time = to_ns(ts); // converts timespec to ns since epoch
</code>```

Step 3: Create a function which can return wall clock time from the tsc

```<code>uint64_t tsc_to_ns(uint64_t tsc)
{
    int64_t diff = tsc - _start_tsc;
    return _start_clock_time + (diff / _ticks_per_ns);
}
</code>```

Step 4: Run in a loop, printing wallclock time from clock_gettime and from rdtscp

```<code>// lock the test to a single core
cpu_set_t mask;
CPU_ZERO(&mask);
CPU_SET(6, &mask);
sched_setaffinity(0, sizeof(cpu_set_t), &mask);

while (1)
{
    timespec utc_now;
    clock_gettime(CLOCK_REALTIME, &utc_now);
    uint64_t utc_ns = to_ns(utc_now);
    uint64_t tsc_ns = tsc_to_ns(rdtscp());

    uint64_t ns_diff = tsc_ns - utc_ns;

    std::cout << "clock_gettime " << ns_to_str(utc_ns) << '\n';
    std::cout << "tsc_time      " << ns_to_str(tsc_ns) << " diff=" << ns_diff << "ns\n";

    sleep(10);
}
</code>```

Output:

```<code>clock_gettime 11:55:34.824419837
tsc_time      11:55:34.824419840 diff=3ns
clock_gettime 11:55:44.826260245
tsc_time      11:55:44.826260736 diff=491ns
clock_gettime 11:55:54.826516358
tsc_time      11:55:54.826517248 diff=890ns
clock_gettime 11:56:04.826683578
tsc_time      11:56:04.826684672 diff=1094ns
clock_gettime 11:56:14.826853056
tsc_time      11:56:14.826854656 diff=1600ns
clock_gettime 11:56:24.827013478
tsc_time      11:56:24.827015424 diff=1946ns
</code>```

Questions:

It is quickly evident that the times calculated in these two ways rapidly drift apart.

I'm assuming that with constant_tsc and nonstop_tsc that the tsc rate is constant.

Is this the on board clock that is drifting? Surely it doesn't drift at this rate?

What is the cause of this drift?

Is there anything I can do to keep them in sync (other than very frequently recalculating _start_tsc and _start_clock_time in step 2)?

答:
Is this the on board clock that is drifting? Surely it doesn't drift at this rate?

No, they shouldn't drift

What is the cause of this drift?

NTP service or similar that runs your OS. They affects clock_gettime(CLOCK_REALTIME, ...);

Is there anything I can do to keep them in sync (other than very frequently recalculating _start_tsc and _start_clock_time in step 2)?
Yes you can ease the problem.

1 You can try to use CLOCK_MONOTONIC instead of CLOCK_REALTIME.

2 You can calculate the difference as a linear function from the time and apply it to compensate the drifting. But it will not be very reliable because time services doesn't adjust the time as linear function. But it will give you some more accuracy. Periodically you can do readjustment.

Some drifting you can get because you calculate _ticks_per_ns not accurately. You can check it by running you program several times. If results are not reproducible, it is mean that you calculate your _ticks_per_ns incorrectly. It is better to use statistics method then just an average value.

Also please note, _ticks_per_ns you are calculating by using CLOCK_MONOTONIC, which is related to TSC.

Next you are using CLOCK_REALTIME. It provides the system time. If your system has NTP or similar service, the time will be adjusted.

Your difference is around 2 micro seconds per minute. It is 0.002 * 24*60 = 2.9 milli seconds a day. It is a great accuracy for CPU clock. 3 ms a day it is a 1 second a year.

Body:
I am running this test on a cpu with constant_tsc and nonstop_tsc

$ grep -m 1 ^flags /proc/cpuinfo | sed 's/ /\n/g' | egrep "constant_tsc|nonstop_tsc"
constant_tsc
nonstop_tsc

Step 1: Calculate the tick rate of the tsc:

I calculate _ticks_per_ns as the median over a number of observations. I use rdtscp to ensure in-order execution.

static const int trials = 13;
std::array<double, trials> rates;

for (int i = 0; i < trials; ++i)
{
    timespec beg_ts, end_ts;
    uint64_t beg_tsc, end_tsc;

    clock_gettime(CLOCK_MONOTONIC, &beg_ts);
    beg_tsc = rdtscp();

    uint64_t elapsed_ns;
    do
    {
        clock_gettime(CLOCK_MONOTONIC, &end_ts);
        end_tsc = rdtscp();

        elapsed_ns = to_ns(end_ts - beg_ts); // calculates ns between two timespecs
    }
    while (elapsed_ns < 10 * 1e6); // busy spin for 10ms

    rates[i] = (double)(end_tsc - beg_tsc) / (double)elapsed_ns;
}

std::nth_element(rates.begin(), rates.begin() + trials/2, rates.end());

_ticks_per_ns = rates[trials/2];

Step 2: Calculate starting wall clock time and tsc

uint64_t beg, end;
timespec ts;

// loop to ensure we aren't interrupted between the two tsc reads
while (1)
{
    beg = rdtscp();
    clock_gettime(CLOCK_REALTIME, &ts);
    end = rdtscp();

    if ((end - beg) <= 2000) // max ticks per clock call
        break;
}

_start_tsc        = end;
_start_clock_time = to_ns(ts); // converts timespec to ns since epoch

Step 3: Create a function which can return wall clock time from the tsc

uint64_t tsc_to_ns(uint64_t tsc)
{
    int64_t diff = tsc - _start_tsc;
    return _start_clock_time + (diff / _ticks_per_ns);
}

Step 4: Run in a loop, printing wallclock time from clock_gettime and from rdtscp

// lock the test to a single core
cpu_set_t mask;
CPU_ZERO(&mask);
CPU_SET(6, &mask);
sched_setaffinity(0, sizeof(cpu_set_t), &mask);

while (1)
{
    timespec utc_now;
    clock_gettime(CLOCK_REALTIME, &utc_now);
    uint64_t utc_ns = to_ns(utc_now);
    uint64_t tsc_ns = tsc_to_ns(rdtscp());

    uint64_t ns_diff = tsc_ns - utc_ns;

    std::cout << "clock_gettime " << ns_to_str(utc_ns) << '\n';
    std::cout << "tsc_time      " << ns_to_str(tsc_ns) << " diff=" << ns_diff << "ns\n";

    sleep(10);
}

Output:

clock_gettime 11:55:34.824419837
tsc_time      11:55:34.824419840 diff=3ns
clock_gettime 11:55:44.826260245
tsc_time      11:55:44.826260736 diff=491ns
clock_gettime 11:55:54.826516358
tsc_time      11:55:54.826517248 diff=890ns
clock_gettime 11:56:04.826683578
tsc_time      11:56:04.826684672 diff=1094ns
clock_gettime 11:56:14.826853056
tsc_time      11:56:14.826854656 diff=1600ns
clock_gettime 11:56:24.827013478
tsc_time      11:56:24.827015424 diff=1946ns

Questions:

It is quickly evident that the times calculated in these two ways rapidly drift apart.

I'm assuming that with constant_tsc and nonstop_tsc that the tsc rate is constant.

Is this the on board clock that is drifting? Surely it doesn't drift at this rate?

What is the cause of this drift?

Is there anything I can do to keep them in sync (other than very frequently recalculating _start_tsc and _start_clock_time in step 2)?


来源: stackexchange

问:
Python: writing to CSV in a for-loop, conditionally adding value in particular column
Here's an example of the contents of my CSV file:

```<code>Fruit, colour, ripe,

apple, green,,
banana, yellow,,
pineapple, green,,
plum, purple,,
</code>```

I want to loop through the contents of the CSV file and according to a test (extrinsic to the CSV data, using an input value supplied to the enclosing function), end up with something like this:

```<code>Fruit, colour, ripe,

apple, green, true,
banana, yellow,,
pineapple, green,,
plum, purple, true,
</code>```

My current code looks like this:

```<code>csv_data = csv.reader(open('./data/fruit_data.csv', 'r'))
for row in csv_data:
    fruit = row[0]
    if fruit == input:
    # Here, write 'true' in the 'ripe' column.
</code>```

It's easy enough to add new data in one go, using the CSV module or pandas, but here I need to add the data iteratively. It seems that I can't change the CSV file in place(?), but if I write out to a different CSV file, it's going to overwrite on each match within the loop, so it'll only reflect that value.

答:
If you create a temporary file, you can write your rows as you read them. If you use os.rename on Unix, "the renaming will be an atomic operation":

```<code>import csv
import os

def update_fruit_data(input):
    csv_file_name = 'data/fruit_data.csv'
    tmp_file_name = "%s.tmp" % csv_file_name
    # Update fruit data
    with open(csv_file_name, 'r') as csv_input_file:
        csv_reader = csv.reader(csv_input_file)
        with open(tmp_file_name, 'w') as csv_output_file:
            csv_writer = csv.writer(csv_output_file)
            for row in csv_reader:
                fruit = row[0]
                if fruit == input:
                    row[2] = 'true'
                csv_writer.writerow(row)
    # Rename tmp file to csv file
    os.rename(tmp_file_name, csv_file_name)

while True:
    input = get_input()
    update_fruit_data(input)
</code>```

The get_input here is a stand-in for whatever you use to get the value of input.

ContentLicense: CC BY-SA 3.0

Body:
Here's an example of the contents of my CSV file:

Fruit, colour, ripe,

apple, green,,
banana, yellow,,
pineapple, green,,
plum, purple,,

I want to loop through the contents of the CSV file and according to a test (extrinsic to the CSV data, using an input value supplied to the enclosing function), end up with something like this:

Fruit, colour, ripe,

apple, green, true,
banana, yellow,,
pineapple, green,,
plum, purple, true,

My current code looks like this:

csv_data = csv.reader(open('./data/fruit_data.csv', 'r'))
for row in csv_data:
    fruit = row[0]
    if fruit == input:
    # Here, write 'true' in the 'ripe' column.

It's easy enough to add new data in one go, using the CSV module or pandas, but here I need to add the data iteratively. It seems that I can't change the CSV file in place(?), but if I write out to a different CSV file, it's going to overwrite on each match within the loop, so it'll only reflect that value.

Body:
If you create a temporary file, you can write your rows as you read them. If you use os.rename on Unix, "the renaming will be an atomic operation":

import csv
import os

def update_fruit_data(input):
    csv_file_name = 'data/fruit_data.csv'
    tmp_file_name = "%s.tmp" % csv_file_name
    # Update fruit data
    with open(csv_file_name, 'r') as csv_input_file:
        csv_reader = csv.reader(csv_input_file)
        with open(tmp_file_name, 'w') as csv_output_file:
            csv_writer = csv.writer(csv_output_file)
            for row in csv_reader:
                fruit = row[0]
                if fruit == input:
                    row[2] = 'true'
                csv_writer.writerow(row)
    # Rename tmp file to csv file
    os.rename(tmp_file_name, csv_file_name)

while True:
    input = get_input()
    update_fruit_data(input)

The get_input here is a stand-in for whatever you use to get the value of input.


问:
One button to fire toggle functions? Press button -> toggleOn(), press again -> toggleOff(), press again -> toggleOn()
Is it possible to use the same onClick from a button to make it a "toggle"?

I have a button, <button>Toggle</button> and basically toggling it on should execute either toggleOn() or toggleOff().

How do I do this with just onClick property?

答:
I can imagine different ways to achieve it.

The first to come to my mind would be something like:

var button = document.getElementById('toggle');
var state = document.getElementById('current-state');

button.addEventListener("click", toggleState);

function toggleState() {
  if ( button.dataset.state == "on" ) {
    button.dataset.state = "off";
    state.innerHTML = "I'm off";
  } else {
    button.dataset.state = "on";
    state.innerHTML = "I'm on";
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="toggle" data-state="off">Toggle me!</button>

<div id="current-state">I'm off</div></code>```

Body:
I can imagine different ways to achieve it.

The first to come to my mind would be something like:

var button = document.getElementById('toggle');
var state = document.getElementById('current-state');

button.addEventListener("click", toggleState);

function toggleState() {
  if ( button.dataset.state == "on" ) {
    button.dataset.state = "off";
    state.innerHTML = "I'm off";
  } else {
    button.dataset.state = "on";
    state.innerHTML = "I'm on";
  }
}

<button id="toggle" data-state="off">Toggle me!</button>

<div id="current-state">I'm off</div>


答:
A similar but slightly more compact approach to Alex Young's:

function toggleOn() {
  console.log( 'on' );
}

function toggleOff() {
  console.log( 'off' );
}

var button = document.getElementById( 'button' );

button.addEventListener( 'click', function clickToggle() {
  clickToggle.state = !clickToggle.state;
  clickToggle.state ? toggleOn() : toggleOff();
} );```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="button">Toggle</button></code>```

This uses the fact that you can attach properties to named functions this way. I'm not sure what the exact terminology for this is.

To address Joe Frambach's valid concerns, addressed in the comments, you could change it to:

```<code>button.addEventListener( 'click', function clickToggle() {
  clickToggle.state = !clickToggle.state;
  return ( clickToggle.state ? toggleOn : toggleOff ).apply( this, arguments );
} );
</code>```

Title: One button to fire toggle functions? Press button -> toggleOn(), press again -> toggleOff(), press again -> toggleOn()

Body:
Is it possible to use the same onClick from a button to make it a "toggle"?

I have a button, <button>Toggle</button> and basically toggling it on should execute either toggleOn() or toggleOff().

How do I do this with just onClick property?

Body:
A similar but slightly more compact approach to Alex Young's:

function toggleOn() {
  console.log( 'on' );
}

function toggleOff() {
  console.log( 'off' );
}

var button = document.getElementById( 'button' );

button.addEventListener( 'click', function clickToggle() {
  clickToggle.state = !clickToggle.state;
  clickToggle.state ? toggleOn() : toggleOff();
} );

<button id="button">Toggle</button>

This uses the fact that you can attach properties to named functions this way. I'm not sure what the exact terminology for this is.

To address Joe Frambach's valid concerns, addressed in the comments, you could change it to:

button.addEventListener( 'click', function clickToggle() {
  clickToggle.state = !clickToggle.state;
  return ( clickToggle.state ? toggleOn : toggleOff ).apply( this, arguments );
} );


问:
Stored proc - union query syntax error
I have an issue with a dynamic query inside a sproc I have in mysql.

Now this query executes fine when I execute it directly in phpmyadmin however this seems to spring up a syntax error upon execution.

```<code>BEGIN
SET @sql = 'set @my_id=24;
set @rank=0;
select * from (
    (
     select *, @rank:=@rank+1 as x from `list_content` where `id` > @my_id order by `id`)
     union (select *, @rank:=@rank+1 as x from `list_content` where `id` < @my_id order by `id`)
    ) `list_content` WHERE `listId` = 15 limit 4';

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
</code>```

I really need this to work somehow as I need to change some field names with params I pass through.

The execution error I get is ...

```<code>MySQL said: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'set @rank=0;
select * from (
    (
     select *, @rank:=@rank+1 as x from `list_c' at line 2
</code>```

I presume this is a limitation with a prep query if I can execute it outside of this environment with no problems.

Thanks

答:
You need to declare a delimiter or else the ; will end your procedure. Like this:

```<code>delimiter //
CREATE PROCEDURE whatever_you_named_it
BEGIN
SET @sql = 'set @my_id=24;
set @rank=0;
select * from (
    (
     select *, @rank:=@rank+1 as x from `list_content` where `id` > @my_id order by `id`)
     union (select *, @rank:=@rank+1 as x from `list_content` where `id` < @my_id order by `id`)
    ) `list_content` WHERE `listId` = 15 limit 4';

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
//
</code>```

Then you can set the delimiter back to ; with

```<code>delimiter ;
</code>```

Title: Stored proc - union query syntax error

Body:
I have an issue with a dynamic query inside a sproc I have in mysql.

Now this query executes fine when I execute it directly in phpmyadmin however this seems to spring up a syntax error upon execution.

BEGIN
SET @sql = 'set @my_id=24;
set @rank=0;
select * from (
    (
     select *, @rank:=@rank+1 as x from `list_content` where `id` > @my_id order by `id`)
     union (select *, @rank:=@rank+1 as x from `list_content` where `id` < @my_id order by `id`)
    ) `list_content` WHERE `listId` = 15 limit 4';

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END

I really need this to work somehow as I need to change some field names with params I pass through.

The execution error I get is ...

MySQL said: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'set @rank=0;
select * from (
    (
     select *, @rank:=@rank+1 as x from `list_c' at line 2

I presume this is a limitation with a prep query if I can execute it outside of this environment with no problems.

Thanks

Body:
You need to declare a delimiter or else the ; will end your procedure. Like this:

delimiter //
CREATE PROCEDURE whatever_you_named_it
BEGIN
SET @sql = 'set @my_id=24;
set @rank=0;
select * from (
    (
     select *, @rank:=@rank+1 as x from `list_content` where `id` > @my_id order by `id`)
     union (select *, @rank:=@rank+1 as x from `list_content` where `id` < @my_id order by `id`)
    ) `list_content` WHERE `listId` = 15 limit 4';

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
//

Then you can set the delimiter back to ; with

delimiter ;


问:
Which (OS X) dtrace probe fires when a page is faulted in from disk?
I'm writing up a document about page faulting and am trying to get some concrete numbers to work with, so I wrote up a simple program that reads 12*1024*1024 bytes of data.  Easy:

```<code>int main()
{
  FILE*in = fopen("data.bin", "rb");
  int i;
  int total=0;
  for(i=0; i<1024*1024*12; i++)
    total += fgetc(in);
  printf("%d\n", total);
}
</code>```

So yes, it goes through and reads the entire file.  The issue is that I need the dtrace probe that is going to fire 1536 times during this process (12M/8k).  Even if I count all of the fbt:mach_kernel:vm_fault*: probes and all of the vminfo::: probes, I don't hit 500, so I know I'm not finding the right probes.

Anyone know where I can find the dtrace probes that fire when a page is faulted in from disk?

UPDATE:

On the off chance that the issue was that there was some intelligent pre-fetching going on in the stdio functions, I tried the following:

```<code>int main()
{
  int in = open("data.bin", O_RDONLY | O_NONBLOCK);
  int i;
  int total=0;
  char buf[128];
  for(i=0; i<1024*1024*12; i++)
  {
    read(in, buf, 1);
    total += buf[0];
  }
  printf("%d\n", total);
}
</code>```

This version takes MUCH longer to run (42s real time, 10s of which was user and the rest was system time - page faults, I'm guessing) but still generates one fifth as many faults as I would expect.

For the curious, the time increase is not due to loop overhead and casting (char to int.)  The code version that does just these actions takes .07 seconds.

答:
I was down the same rathole recently.  I don't have my DTrace scripts or test programs available just now, but I will give you the following advice:

1.) Get your hands on OS X Internals by Amit Singh and read section 8.3 on virtual memory (this will get you in the right frame of reference for selecting DTrace probes).

2.) Get your hands on Solaris Performance and Tools by Brendan Gregg / Jim Mauro.  Read the section on virtual memory and pay close attention to the example DTrace scripts that make use of the vminfo provider.

3.) OS X is definitely prefetching large chunks of pages from the filesystem, and your test program is playing right into this optimization (since you're reading sequentially).  Interestingly, this is not the case for Solaris.  Try randomly accessing the big array to defeat the prefetch.

ContentLicense: CC BY-SA 2.5

Body:
I'm writing up a document about page faulting and am trying to get some concrete numbers to work with, so I wrote up a simple program that reads 12*1024*1024 bytes of data.  Easy:

int main()
{
  FILE*in = fopen("data.bin", "rb");
  int i;
  int total=0;
  for(i=0; i<1024*1024*12; i++)
    total += fgetc(in);
  printf("%d\n", total);
}

So yes, it goes through and reads the entire file.  The issue is that I need the dtrace probe that is going to fire 1536 times during this process (12M/8k).  Even if I count all of the fbt:mach_kernel:vm_fault*: probes and all of the vminfo::: probes, I don't hit 500, so I know I'm not finding the right probes.

Anyone know where I can find the dtrace probes that fire when a page is faulted in from disk?

UPDATE:

On the off chance that the issue was that there was some intelligent pre-fetching going on in the stdio functions, I tried the following:

int main()
{
  int in = open("data.bin", O_RDONLY | O_NONBLOCK);
  int i;
  int total=0;
  char buf[128];
  for(i=0; i<1024*1024*12; i++)
  {
    read(in, buf, 1);
    total += buf[0];
  }
  printf("%d\n", total);
}

This version takes MUCH longer to run (42s real time, 10s of which was user and the rest was system time - page faults, I'm guessing) but still generates one fifth as many faults as I would expect.

For the curious, the time increase is not due to loop overhead and casting (char to int.)  The code version that does just these actions takes .07 seconds.


问:
How to keep seeder files separate and clean in laravel?
I want to keep my seeder files separate. for example UsersTableSeeder.php , PostsTableSeeder.php and then call them in main seeder file (DatabaseSeeder.php) :

Example:

```<code>use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{

    public function run()
    {
         $this->call(UsersTableSeeder::class);
         $this->call(PostsTableSeeder::class);
    }
}
</code>```

usersTableSeeder.php :

```<code><?php namespace App\Seeds;

    use Illuminate\Database\Seeder;
    use App\User;

    class UserTableSeeder extends Seeder {

        public function run()
        {
            //DB::table('users')->delete();

            // user1
            User::create(array(
                'name' => 'ahmad',
                'email' => 'ahmad@ahmad.com',
                'password' => 'ahmad'
            ));
        }
    }
</code>```

my UsersTableSeeder.php and PostsTableSeeder.php files are in the same
directory that DatabaseSeeder.php is.

should I use psr-4 autoloading ? how?

答:
You may have to run composer dump-autoload. It worked for me.

As a side note, it'd be cleaner to use PSR-4 for seeds and migrations (tests already do).

Body:
I want to keep my seeder files separate. for example UsersTableSeeder.php , PostsTableSeeder.php and then call them in main seeder file (DatabaseSeeder.php) :

Example:

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{

    public function run()
    {
         $this->call(UsersTableSeeder::class);
         $this->call(PostsTableSeeder::class);
    }
}

usersTableSeeder.php :

<?php namespace App\Seeds;

    use Illuminate\Database\Seeder;
    use App\User;

    class UserTableSeeder extends Seeder {

        public function run()
        {
            //DB::table('users')->delete();

            // user1
            User::create(array(
                'name' => 'ahmad',
                'email' => 'ahmad@ahmad.com',
                'password' => 'ahmad'
            ));
        }
    }

my UsersTableSeeder.php and PostsTableSeeder.php files are in the same
directory that DatabaseSeeder.php is.

should I use psr-4 autoloading ? how?


问:
NodeJS / Express: what is "app.use"?
In the docs for the NodeJS express module, the example code has app.use(...).

What is the use function and where is it defined?

答:
Middleware is a general term for software that serves to "glue together" so
app.use is a method to configure the middleware, for example: to parse and handle the body of request:
 app.use(bodyParser.urlencoded({ extended: true }));
 app.use(bodyParser.json());
there are many middlewares you can use in your express application
just read the doc :
http://expressjs.com/en/guide/using-middleware.html</p>

Title: NodeJS / Express: what is "app.use"?


问:
Google MDL Lite : How can I progmmatically init a checkbox or switch?
in google's material design lite framework When I load this HTML into the page sometime after its already loaded I don't see the nice little switch like i do if this HTML was present before the library was loaded.

https://getmdl.io/components/index.html#toggles-section

```<code><label class="mdl-switch mdl-js-switch mdl-js-ripple-effect" for="switch-1">
  <input type="checkbox" id="switch-1" class="mdl-switch__input" checked>
  <span class="mdl-switch__label"></span>
</label>
</code>```

is there a function I can run to init the elements as they appear? I have searched for hours with failure as my only result :(

答:
found out how to update registered components by reading the .js file.

```<code>componentHandler.upgradeAllRegistered()
</code>```

Body:
in google's material design lite framework When I load this HTML into the page sometime after its already loaded I don't see the nice little switch like i do if this HTML was present before the library was loaded.

https://getmdl.io/components/index.html#toggles-section

  <input type="checkbox" id="switch-1" class="mdl-switch__input" checked>

is there a function I can run to init the elements as they appear? I have searched for hours with failure as my only result :(

Body:
found out how to update registered components by reading the .js file.

componentHandler.upgradeAllRegistered()


问:
KeyError in Tensorflow when calling predict on trained model
I have trained a LinearRegressor with two features: x,y and the label: l

```<code>def train_input_fn():
    x = [1,2,3,4]
    y = [2,3,4,5]
    feature_cols = tf.constant(x)
    labels = tf.constant(y)
    return feature_cols, labels

x = tf.contrib.layers.real_valued_column("x")
y = tf.contrib.layers.real_valued_column("y")
m = tf.contrib.learn.LinearRegressor(feature_columns=[ x,y],
                                      model_dir=model_dir)
m.fit(input_fn=train_input_fn, steps=100)
</code>```

After training I want to predict from two new values

```<code>new_sample = np.array([20,20])
m.predict(new_sample)
</code>```

but I get this error message when calling predict

```<code>File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/layers/python/layers/feature_column.py", line 870, in insert_transformed_feature
input_tensor = columns_to_tensors[self.name]
KeyError: 'x'
</code>```

Does anyone know why I get KeyError?

答:
I am not an expert in Tensorflow but this works for me:</p>

```<code>new_sample = np.array([20,20],dtype='float32')
empty_y = np.zeros(len(new_sample),dtype='float32')
prediction_x = tf.contrib.learn.io.numpy_input_fn({"x":new_sample},empty_y, batch_size=45,    num_epochs=100)
forecast = list(estimator.predict(input_fn=prediction_x,as_iterable=False))
</code>```

Body:
I have trained a LinearRegressor with two features: x,y and the label: l

def train_input_fn():
    x = [1,2,3,4]
    y = [2,3,4,5]
    feature_cols = tf.constant(x)
    labels = tf.constant(y)
    return feature_cols, labels

x = tf.contrib.layers.real_valued_column("x")
y = tf.contrib.layers.real_valued_column("y")
m = tf.contrib.learn.LinearRegressor(feature_columns=[ x,y],
                                      model_dir=model_dir)
m.fit(input_fn=train_input_fn, steps=100)

After training I want to predict from two new values

new_sample = np.array([20,20])
m.predict(new_sample)

but I get this error message when calling predict

File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/layers/python/layers/feature_column.py", line 870, in insert_transformed_feature
input_tensor = columns_to_tensors[self.name]
KeyError: 'x'

Does anyone know why I get KeyError?

Body:
I am not an expert in Tensorflow but this works for me:

new_sample = np.array([20,20],dtype='float32')
empty_y = np.zeros(len(new_sample),dtype='float32')
prediction_x = tf.contrib.learn.io.numpy_input_fn({"x":new_sample},empty_y, batch_size=45,    num_epochs=100)
forecast = list(estimator.predict(input_fn=prediction_x,as_iterable=False))


问:
The numbers in my javascript will not add
So I need the code to use addition on random numbers in the array. If the sum is greater then ten, it should say "over" else it would be "under."

`

```<code>function arraries(){
       var oneten = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
               document.getElementById('demo').innerHTML = addy(oneten);
   }

function addy(oneten){
     var n;
    var output;
    var sum = "";

    for (i = 0; i < 4; i++){
        n = Math.floor((Math.random() * 10) + 1);
        sum += parseFloat(oneten[n])}

    if (sum > 10){
        return "over";

    }
    else { return  "under";}

}
</code>```

The problem here is that the debugger decipher the numbers as strings. While running the sum would equal "1234" instead of 10 (which is 1 + 2 + 3 + 4) and thus it will always return "over". How can I make sure that the data will be treat as actually numbers instead of strings? I used parseFloat and parseInt but I got the same results

答: Mabybe you can try to set sum = 0, because like this js will concatenate into a string instead of into a int</p>

Body:
So I need the code to use addition on random numbers in the array. If the sum is greater then ten, it should say "over" else it would be "under."

`

function arraries(){
       var oneten = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
               document.getElementById('demo').innerHTML = addy(oneten);
   }

function addy(oneten){
     var n;
    var output;
    var sum = "";

    for (i = 0; i < 4; i++){
        n = Math.floor((Math.random() * 10) + 1);
        sum += parseFloat(oneten[n])}

    if (sum > 10){
        return "over";

    }
    else { return  "under";}

}

The problem here is that the debugger decipher the numbers as strings. While running the sum would equal "1234" instead of 10 (which is 1 + 2 + 3 + 4) and thus it will always return "over". How can I make sure that the data will be treat as actually numbers instead of strings? I used parseFloat and parseInt but I got the same results


问:
How much low-level stuff to expose in an API?
When designing the public API of a generic library, how much of the low-level stuff that's used internally should be exposed?  On the one hand, users should not depend too heavily on implementation details, and too many low-level functions/classes might clutter the API.  Therefore, the knee-jerk response might be "none".  On the other hand, some of the low-level functionality might be useful to people, and exposing more of it can prevent abstraction inversion (the re-implementing of low-level constructs on top of high-level constructs).

Furthermore, exposing more low-level details could provide performance shortcuts.  For example, let's say you have a function to find the median of an array.  The principle of least surprise says that you should duplicate the array so that users of your API don't have to care that its implementation involves the side effect of reordering elements.  Should you, in this case, note that median() costs a memory allocation and provide another function that bypasses the allocation, but will arbitrarily reorder the user's input?

What are some general guidelines for how much of this kind of detail to expose?

答:
As little as is possible.

The more details you expose, the more likely a change will break a consumer.

OwnerDisplayName: dsimcha

OwnerDisplayName: Mitch Wheat


问:
force download using readfile not working
this is an index.php

```<code><form action="verify.php" method="post" target="_blank">
        <input name="filename" type="hidden" value="media.mp4"><p></p>
        <input name="filesize" type="hidden" value="10 MB">
        <div align="center">
            <input alt="Download" src="download.png" type="image" width="225">
        </div>
</form>
</code>```

this is an verify.php

```<code><meta http-equiv="refresh" content="5; url=download.php?file=<?php echo $file; ?>">
</code>```

this is an download.php

```<code><?php
$file = $_GET['file'];
header('Content-type: video/mp4');
header('Content-Disposition: attachment; filename="uploads/' . $file . '"');
?>
</code>```

And the media files are stored in uploads directory this code need to force mp4 to download unfortunately it is not downloading from correct path.

this is the output in console: /download.php?file=media.mp4".

in order to make it work it should be /uploads/media.mp4 ... please help! tell me what im doing wrong?

答:
According to the PHP Documentation</p>

```<code>// This line is where you put the name of the file the client will be receipt
header('Content-Disposition: attachment; filename="downloaded.pdf"');

// This line is where you define which file you will send to the client
readfile('original.pdf');
</code>```

Body:
this is an index.php

<form action="verify.php" method="post" target="_blank">
        <input name="filename" type="hidden" value="media.mp4">

        <input name="filesize" type="hidden" value="10 MB">

            <input alt="Download" src="download.png" type="image" width="225">

</form>

this is an verify.php

<meta http-equiv="refresh" content="5; url=download.php?file=<?php echo $file; ?>">

this is an download.php

<?php
$file = $_GET['file'];
header('Content-type: video/mp4');
header('Content-Disposition: attachment; filename="uploads/' . $file . '"');
?>

And the media files are stored in uploads directory this code need to force mp4 to download unfortunately it is not downloading from correct path.

this is the output in console: /download.php?file=media.mp4".

in order to make it work it should be /uploads/media.mp4 ... please help! tell me what im doing wrong?

Body:
According to the PHP Documentation

// This line is where you put the name of the file the client will be receipt
header('Content-Disposition: attachment; filename="downloaded.pdf"');

// This line is where you define which file you will send to the client
readfile('original.pdf');


问:
Ionic app - same content in every button
I've downloaded this free template: git, and tried to add some content, but the content repeats for every button and i can't find a solution to add different content to different buttons.

I have this "item.html" which is where I add the content that repeats for every button (as shown below), if I create for example "item_workshops.html", how do I specify that i want that page linked to the "workshops" button? Or there is any other way?

item.html

```<code><ion-view class="itemView" view-title="{{item.title}}" ng-style="{ 'background-color': item.color }">
  <ion-content class="center-content animated slideInUp" overflow-scroll="true">

  <i class="ion-ionic" style="font-size:22em;color:white;"></i>
    <header>
      <p></p>
        <p>
          <h10>PROGRAMA<p> </p></h10>
        </p>
      </header>

<!-- I want this to be linked to the "workshops" button -->
  <i class="ion-ios-alarm" style="font-size:22em;color:white;"></i>
    <header>
      <p></p>
        <p>
          <h10>Workshops<p> </p></h10>
        </p>
      </header>

  </ion-content>
</ion-view>
</code>```

item.js (controller)

```<code>(function() {
'use strict';

    angular
        .module('App')
        .controller('ItemController', ItemController);

    ItemController.$inject = ['$scope', '$stateParams', '$ionicViewSwitcher', '$state', '$ionicHistory'];
    function ItemController($scope, $stateParams, $ionicViewSwitcher, $state, $ionicHistory) {

        $scope.item = {
            title: $stateParams.title,
            icon: $stateParams.icon,
            color: $stateParams.color
        };

        if (!$scope.item.color) {
            $ionicViewSwitcher.nextDirection('back');
            $ionicHistory.nextViewOptions({
                disableBack: true,
                disableAnimate : true,
                historyRoot  : true
            });
            $state.go('app.gallery');
        }
    }
})();
</code>```

app.js (controller)

```<code>    (function () {
        'use strict';

        angular
            .module('App')
            .controller('AppController', AppController);

        AppController.$inject = ['$scope', '$ionicPopover'];
        function AppController($scope, $ionicPopover) {

            $scope.items = [
                {
                    color: "#3a3a3a",
                    icon: "ion-ionic",
                    title: "Programa"
                },
                {
                    color: "#536582",
                    icon: "ion-ios-alarm",
                    title: "Workshops"
                }
//removed the other buttons to minimize the code
            ];
        }
    })();
</code>```

gallery.js (controller)

```<code>(function() {
'use strict';

    angular
        .module('App')
        .controller('GalleryController', GalleryController);

    GalleryController.$inject = ['$scope', '$state'];
    function GalleryController($scope, $state) {

        $scope.openItem = function(item){
            $state.go('app.item', { title: item.title, icon: item.icon, color: item.color });
        };
    }
})();
</code>```

app.js

```<code>$stateProvider
    .state('app', {
        url: '/app',
        abstract: true,
        controller: 'AppController',
        templateUrl: 'templates/menu.html'
    })
    .state('app.gallery', {
        url: "/gallery",
        cache: false,
        views: {
            viewContent: {
                templateUrl: "templates/gallery.html",
                controller: 'GalleryController'
            }
        }
    })
    .state('app.item', {
        url: "/item/{title}",
        params: {
            color: null,
            icon: null
        },
        cache: false,
        views: {
            viewContent: {
                templateUrl: "templates/item.html",
                controller: 'ItemController'
            }
        }
    });
</code>```

Thanks in advance.

答:
In the gallery.js create a condition for the state you want to go,

for example:

```<code>$scope.openItem = function(item){
 if(item.title == "Workshop")
    $state.go('app.workshop', { title: item.title});
 else if(item.title == "Videos")
     $state.go('app.videos', { title: item.title});
  ...
};
</code>```

Body:
I've downloaded this free template: git, and tried to add some content, but the content repeats for every button and i can't find a solution to add different content to different buttons.

I have this "item.html" which is where I add the content that repeats for every button (as shown below), if I create for example "item_workshops.html", how do I specify that i want that page linked to the "workshops" button? Or there is any other way?

item.html

<ion-view class="itemView" view-title="{{item.title}}" ng-style="{ 'background-color': item.color }">
  <ion-content class="center-content animated slideInUp" overflow-scroll="true">

          <h10>PROGRAMA

</h10>

          <h10>Workshops

</h10>

  </ion-content>
</ion-view>

item.js (controller)

(function() {
'use strict';

    angular
        .module('App')
        .controller('ItemController', ItemController);

    ItemController.$inject = ['$scope', '$stateParams', '$ionicViewSwitcher', '$state', '$ionicHistory'];
    function ItemController($scope, $stateParams, $ionicViewSwitcher, $state, $ionicHistory) {

        $scope.item = {
            title: $stateParams.title,
            icon: $stateParams.icon,
            color: $stateParams.color
        };

        if (!$scope.item.color) {
            $ionicViewSwitcher.nextDirection('back');
            $ionicHistory.nextViewOptions({
                disableBack: true,
                disableAnimate : true,
                historyRoot  : true
            });
            $state.go('app.gallery');
        }
    }
})();

app.js (controller)

    (function () {
        'use strict';

        angular
            .module('App')
            .controller('AppController', AppController);

        AppController.$inject = ['$scope', '$ionicPopover'];
        function AppController($scope, $ionicPopover) {

            $scope.items = [
                {
                    color: "#3a3a3a",
                    icon: "ion-ionic",
                    title: "Programa"
                },
                {
                    color: "#536582",
                    icon: "ion-ios-alarm",
                    title: "Workshops"
                }
//removed the other buttons to minimize the code
            ];
        }
    })();

gallery.js (controller)

(function() {
'use strict';

    angular
        .module('App')
        .controller('GalleryController', GalleryController);

    GalleryController.$inject = ['$scope', '$state'];
    function GalleryController($scope, $state) {

        $scope.openItem = function(item){
            $state.go('app.item', { title: item.title, icon: item.icon, color: item.color });
        };
    }
})();

app.js

$stateProvider
    .state('app', {
        url: '/app',
        abstract: true,
        controller: 'AppController',
        templateUrl: 'templates/menu.html'
    })
    .state('app.gallery', {
        url: "/gallery",
        cache: false,
        views: {
            viewContent: {
                templateUrl: "templates/gallery.html",
                controller: 'GalleryController'
            }
        }
    })
    .state('app.item', {
        url: "/item/{title}",
        params: {
            color: null,
            icon: null
        },
        cache: false,
        views: {
            viewContent: {
                templateUrl: "templates/item.html",
                controller: 'ItemController'
            }
        }
    });

Thanks in advance.

Body:
In the gallery.js create a condition for the state you want to go,

for example:

$scope.openItem = function(item){
 if(item.title == "Workshop")
    $state.go('app.workshop', { title: item.title});
 else if(item.title == "Videos")
     $state.go('app.videos', { title: item.title});
  ...
};

ContentLicense: CC BY-SA 4.0


问:
Using Python within R notebook
I have been using ipython (Jupyter) notebook for my tasks with R and Python. Recently, I explored R Notebook and I found the kind of functionalities I wish they were in Jupyter Notebook implemented in R Notebook. So, I want to switch to R Notebook. However, when using Python in R Notebook, I could not cache the python results and use output from one chunk in another chunk. Further, I am not able to generate the python plots inline. It gives me plots in a new window, not in the notebook itself. To just provide some reproducible code, the code below works fine and gives an output if you put it in a single chunk but if you divide it into a couple of chunks, you cannot call outputs from one chunk in another chunk. The figure also pops up in a new window.

```<code>```{python}
 # Import necessary modules
 from sklearn import datasets
 import matplotlib.pyplot as plt
 from sklearn.model_selection import train_test_split
 from sklearn.neighbors import KNeighborsClassifier
 import numpy as np

 # Load the digits dataset: digits
 digits = datasets.load_digits()

 # Create feature and target arrays
 X = digits.data
 y = digits.target

# Split into training and test set
 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2,    random_state = 42, stratify = y)

# Setup arrays to store train and test accuracies
 neighbors = np.arange(1, 9)
 train_accuracy = np.empty(len(neighbors))
 test_accuracy = np.empty(len(neighbors))

  # Loop over different values of k
 for i, k in enumerate(neighbors):
  # Setup a k-NN Classifier with k neighbors: knn
    knn = KNeighborsClassifier(n_neighbors = k)

    # Fit the classifier to the training data
    knn.fit(X_train,y_train)

    #Compute accuracy on the training set
    train_accuracy[i] = knn.score(X_train, y_train)

    #Compute accuracy on the testing set
     test_accuracy[i] = knn.score(X_test, y_test)

  # Generate plot
 plt.title('k-NN: Varying Number of Neighbors')
 plt.plot(neighbors, test_accuracy, label = 'Testing Accuracy')
 plt.plot(neighbors, train_accuracy, label = 'Training Accuracy')
 plt.legend()
 plt.xlabel('Number of Neighbors')
 plt.ylabel('Accuracy')
 plt.show()
 ```
</code>```

The plot below shows up in a new window. Not inline in the Notebook.

答:
I think the right way to deal with this is using rPython. Using this library you can execute python code and get the results as R variables. Check this link to see an example:

https://github.com/rajshah4/tensorflow_shiny/blob/master/server.R

Title: Using Python within R notebook

Body:
I have been using ipython (Jupyter) notebook for my tasks with R and Python. Recently, I explored R Notebook and I found the kind of functionalities I wish they were in Jupyter Notebook implemented in R Notebook. So, I want to switch to R Notebook. However, when using Python in R Notebook, I could not cache the python results and use output from one chunk in another chunk. Further, I am not able to generate the python plots inline. It gives me plots in a new window, not in the notebook itself. To just provide some reproducible code, the code below works fine and gives an output if you put it in a single chunk but if you divide it into a couple of chunks, you cannot call outputs from one chunk in another chunk. The figure also pops up in a new window.

```{python}
 # Import necessary modules
 from sklearn import datasets
 import matplotlib.pyplot as plt
 from sklearn.model_selection import train_test_split
 from sklearn.neighbors import KNeighborsClassifier
 import numpy as np

 # Load the digits dataset: digits
 digits = datasets.load_digits()

 # Create feature and target arrays
 X = digits.data
 y = digits.target

# Split into training and test set
 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2,    random_state = 42, stratify = y)

# Setup arrays to store train and test accuracies
 neighbors = np.arange(1, 9)
 train_accuracy = np.empty(len(neighbors))
 test_accuracy = np.empty(len(neighbors))

  # Loop over different values of k
 for i, k in enumerate(neighbors):
  # Setup a k-NN Classifier with k neighbors: knn
    knn = KNeighborsClassifier(n_neighbors = k)

    # Fit the classifier to the training data
    knn.fit(X_train,y_train)

    #Compute accuracy on the training set
    train_accuracy[i] = knn.score(X_train, y_train)

    #Compute accuracy on the testing set
     test_accuracy[i] = knn.score(X_test, y_test)

  # Generate plot
 plt.title('k-NN: Varying Number of Neighbors')
 plt.plot(neighbors, test_accuracy, label = 'Testing Accuracy')
 plt.plot(neighbors, train_accuracy, label = 'Training Accuracy')
 plt.legend()
 plt.xlabel('Number of Neighbors')
 plt.ylabel('Accuracy')
 plt.show()
 ```

The plot below shows up in a new window. Not inline in the Notebook.


问:
How do I get same result without using enumerate?
I do not need char in this example, but I include it to get my desired results.

```<code>charlist = [strval[0:count+1] for count, char in enumerate(strval)]
</code>```

How do I get the same result without using enumerate?

答:
```<code>xrange(len(strval))
</code>```

Body:
I do not need char in this example, but I include it to get my desired results.

charlist = [strval[0:count+1] for count, char in enumerate(strval)]

How do I get the same result without using enumerate?

Body: xrange(len(strval))


问:
How should I structure two types of Roles in a Rails application?
I am working on a Ruby on Rails application that has two kinds of "Roles".

One will be where a user has multiple roles, such as "Admin", "Team Lead", etc. these will be defined in the seeds file and not generated by the user.

The other will be generated by a User and assigned to other users, such as "Chef", "Waiter", etc.

They are both similar in that they only have a name column. The former will be used with an authorization tool such as CanCanCan. I currently plan to allow users and roles to have many of the other using a has_many :through relationship.

```<code>class Role
  has_many :user_roles
  has_many :users, through: :user_roles
end

class User
  has_many :user_roles
  has_many :roles, through: :user_roles
end

class UserRole
  belongs_to :user
  belongs_to :role
end
</code>```

My questions are:

Should the latter ("Chef", "Waiter", etc) be put in the same table? Separate tables?

Should I use some kind of inheritance?

What's a good practice for this situation?

I plan to use the term "Role" in the user interface for the latter, showing what "Roles" a user has. The former I guess is more about what privileges they have within the application.

答:
Also, You can go just using Users table and adding role column as integer and give them a role code in default 0 integer.

```<code>#app/helpers/roles_helper.rb

module RolesHelper
  @roles = {
    'Default' => 0,
    'Waiter' => 10,
    'Chef' => 20,
    'Superadmin' => 30
  }

class << self

  def list_roles
    @roles.map{|k,v| [k,v] }
  end

  def code(str)
    return @roles[str]
  end

  def value(id)
    return @roles.key(id)
  end
end

  def require_default_users
    unless current_user && current_user.role >= RolesHelper.code('Waiter')
      redirect_to root_url(host: request.domain)
    end
  end

  def require_superadmin_users
    unless current_user && current_user.role >= RolesHelper.code('Superadmin')
      redirect_to courses_path
    end
  end
end
</code>```

access in controllers

sample:

```<code>class Admin::AdminController < ApplicationController
 include RolesHelper

  def sample_action_method
    require_default_users #if non admin user redirect ...

    puts "All Roles: #{RolesHelper.list_roles}"
    puts "Value: #{RolesHelper.value(30)}"
    puts "Code: #{RolesHelper.code('Superuser')}"
  end
end
</code>```

Body:
I am working on a Ruby on Rails application that has two kinds of "Roles".

One will be where a user has multiple roles, such as "Admin", "Team Lead", etc. these will be defined in the seeds file and not generated by the user.

The other will be generated by a User and assigned to other users, such as "Chef", "Waiter", etc.

They are both similar in that they only have a name column. The former will be used with an authorization tool such as CanCanCan. I currently plan to allow users and roles to have many of the other using a has_many :through relationship.

class Role
  has_many :user_roles
  has_many :users, through: :user_roles
end

class User
  has_many :user_roles
  has_many :roles, through: :user_roles
end

class UserRole
  belongs_to :user
  belongs_to :role
end

My questions are:

Should the latter ("Chef", "Waiter", etc) be put in the same table? Separate tables?

Should I use some kind of inheritance?

What's a good practice for this situation?

I plan to use the term "Role" in the user interface for the latter, showing what "Roles" a user has. The former I guess is more about what privileges they have within the application.

Body:
Also, You can go just using Users table and adding role column as integer and give them a role code in default 0 integer.

#app/helpers/roles_helper.rb

module RolesHelper
  @roles = {
    'Default' => 0,
    'Waiter' => 10,
    'Chef' => 20,
    'Superadmin' => 30
  }

class << self

  def list_roles
    @roles.map{|k,v| [k,v] }
  end

  def code(str)
    return @roles[str]
  end

  def value(id)
    return @roles.key(id)
  end
end

  def require_default_users
    unless current_user && current_user.role >= RolesHelper.code('Waiter')
      redirect_to root_url(host: request.domain)
    end
  end

  def require_superadmin_users
    unless current_user && current_user.role >= RolesHelper.code('Superadmin')
      redirect_to courses_path
    end
  end
end

access in controllers

sample:

class Admin::AdminController < ApplicationController
 include RolesHelper

  def sample_action_method
    require_default_users #if non admin user redirect ...

    puts "All Roles: #{RolesHelper.list_roles}"
    puts "Value: #{RolesHelper.value(30)}"
    puts "Code: #{RolesHelper.code('Superuser')}"
  end
end


答:
Shouldn't you declare the sum variable as a number? Also, you don't need parseFloat function, the oneten array elements are already typeof number.

Another thing - Math.random() * 10) + 1 loss numbers from the 1 - 10 range and in your case it will return undefined because there's no item in the oneten array with index 10. Use Math.random() * 10 instead, which will return numbers from 0 - 9 range.

function arraries() {
  var oneten = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  document.getElementById('demo').innerHTML = addy(oneten);
}

function addy(oneten) {
  var n;
  var output;
  var sum = 0;

  for (i = 0; i < 4; i++) {
    n = Math.floor((Math.random() * 10));
    sum += oneten[n];
  }
  console.log(sum);

  if (sum > 10) {
    return "over";

  } else {
    return "under";
  }

}

arraries();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id='demo'></p></code>```

Title: The numbers in my javascript will not add

Body:
Shouldn't you declare the sum variable as a number? Also, you don't need parseFloat function, the oneten array elements are already typeof number.

Another thing - Math.random() * 10) + 1 loss numbers from the 1 - 10 range and in your case it will return undefined because there's no item in the oneten array with index 10. Use Math.random() * 10 instead, which will return numbers from 0 - 9 range.

function arraries() {
  var oneten = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  document.getElementById('demo').innerHTML = addy(oneten);
}

function addy(oneten) {
  var n;
  var output;
  var sum = 0;

  for (i = 0; i < 4; i++) {
    n = Math.floor((Math.random() * 10));
    sum += oneten[n];
  }
  console.log(sum);

  if (sum > 10) {
    return "over";

  } else {
    return "under";
  }

}

arraries();

<p id='demo'></p>


问:
List Comprehensions with a condition on an array?
I have an array that contains tuples that look like this: [((Int, Int), Int)]. I am trying to create a new array with list comprehensions that says to only add all 3 Ints if the 3rd Int == a certain number. I have it written as

```<code>newArray = [((x,y),z) | ((x,y),z)<-oldArray, (snd oldArray) == 5]
</code>```

However, when I try to run the code that contains this, it says "couldn't match expected type" and point the error at my conditional. "Couldn't match expected type '(a0, Int)' with actual type '[((Int, Int), Int)]'".

答: oldArray is a list, always and forever, even inside the comprehension, so snd can't be applied to it. Use z == 5 instead.

Body:
I have an array that contains tuples that look like this: [((Int, Int), Int)]. I am trying to create a new array with list comprehensions that says to only add all 3 Ints if the 3rd Int == a certain number. I have it written as

newArray = [((x,y),z) | ((x,y),z)<-oldArray, (snd oldArray) == 5]

However, when I try to run the code that contains this, it says "couldn't match expected type" and point the error at my conditional. "Couldn't match expected type '(a0, Int)' with actual type '[((Int, Int), Int)]'".


答:
If you do not want to use enumerate, use range since all you want is count value

```<code>>>> strval = "abcd"
>>> for count, char in enumerate(strval): print count, char
...
0 a
1 b
2 c
3 d
>>> for count in range(len(strval)): print count
...
0
1
2
3
>>>
</code>```

Title: How do I get same result without using enumerate?

Body:
If you do not want to use enumerate, use range since all you want is count value

>>> strval = "abcd"
>>> for count, char in enumerate(strval): print count, char
...
0 a
1 b
2 c
3 d
>>> for count in range(len(strval)): print count
...
0
1
2
3
>>>


答:
As mysql manual on prepared statements says:

SQL syntax for prepared statements does not support multi-statements
  (that is, multiple statements within a single string separated by ;
  characters).

This means that you cannot have 3 statements on your prepared statement. However, the same section of the manual also says that

A prepared statement is also global to the session.

This means that you can move the set statements outside of the prepared statement into the code of the dtored proc and the session variables will be available within the prepared statement.

Title: Stored proc - union query syntax error

Body:
I have an issue with a dynamic query inside a sproc I have in mysql.

Now this query executes fine when I execute it directly in phpmyadmin however this seems to spring up a syntax error upon execution.

BEGIN
SET @sql = 'set @my_id=24;
set @rank=0;
select * from (
    (
     select *, @rank:=@rank+1 as x from `list_content` where `id` > @my_id order by `id`)
     union (select *, @rank:=@rank+1 as x from `list_content` where `id` < @my_id order by `id`)
    ) `list_content` WHERE `listId` = 15 limit 4';

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END

I really need this to work somehow as I need to change some field names with params I pass through.

The execution error I get is ...

MySQL said: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'set @rank=0;
select * from (
    (
     select *, @rank:=@rank+1 as x from `list_c' at line 2

I presume this is a limitation with a prep query if I can execute it outside of this environment with no problems.

Thanks


问:
Does groupby automatically group over all non numeric columns in pandas?
I have a sample of a dataset below (only showing the first couple rows but there are 193 rows):

```<code>country,beer_servings,spirit_servings,wine_servings,total_litres_of_pure_alcohol,continent
Afghanistan,0,0,0,0.0,Asia
Albania,89,132,54,4.9,Europe
Algeria,25,0,14,0.7,Africa
Andorra,245,138,312,12.4,Europe
Angola,217,57,45,5.9,Africa
Antigua & Barbuda,102,128,45,4.9,North America
...
</code>```

When I run this: drinks.groupby('continent').head()

I get back a dataframe with 30 rows. But in those 30 rows I still have duplicate names for the continent. For example in the image below you can see that Europe is repeated two times (at rows 1 and 3):

I am not able to understand why I am still having two rows with the same continent when I grouped by continent originally?

In this case is the groupby operation also grouping by the country even though I never specified it in the groupby function? Since I know in SQL you are supposed to use an aggregate function like max, min, sum, etc. But in this case I don't have to pass in an aggregate function and I get the result above.

答: drinks.groupby('continent').head([n=5]) returns the first n rows from each group, but then reorders them by the original index. Try calling drinks.groupby('continent').head(1), and you will see that only one country from each continent is included in the result.

Body:
I have a sample of a dataset below (only showing the first couple rows but there are 193 rows):

country,beer_servings,spirit_servings,wine_servings,total_litres_of_pure_alcohol,continent
Afghanistan,0,0,0,0.0,Asia
Albania,89,132,54,4.9,Europe
Algeria,25,0,14,0.7,Africa
Andorra,245,138,312,12.4,Europe
Angola,217,57,45,5.9,Africa
Antigua & Barbuda,102,128,45,4.9,North America
...

When I run this: drinks.groupby('continent').head()

I get back a dataframe with 30 rows. But in those 30 rows I still have duplicate names for the continent. For example in the image below you can see that Europe is repeated two times (at rows 1 and 3):

I am not able to understand why I am still having two rows with the same continent when I grouped by continent originally?

In this case is the groupby operation also grouping by the country even though I never specified it in the groupby function? Since I know in SQL you are supposed to use an aggregate function like max, min, sum, etc. But in this case I don't have to pass in an aggregate function and I get the result above.


问:
Psci Uncaught ReferenceError: require is not defined when using port
I'm running psci with port for example

```<code>pulp psci -- -p9000
</code>```

and it borks with

```<code>Uncaught ReferenceError: require is not defined
    at PSCI.Data.BigInt (bundle.js:52952)
    at bundle.js:53042
</code>```

Found this require here

```<code>.psci_modules/node_modules/Data.BigInt/foreign.js
</code>```

I could not find some docs explaining this, am I doing this right?

答:
The problem is that Data.BigInt depends on the big-integer NPM package, which is not available in the browser when running with --port.

To make this work, you would need some way to provide a dummy require function in the browser.

Body:
I'm running psci with port for example

pulp psci -- -p9000

and it borks with

Uncaught ReferenceError: require is not defined
    at PSCI.Data.BigInt (bundle.js:52952)
    at bundle.js:53042

Found this require here

.psci_modules/node_modules/Data.BigInt/foreign.js

I could not find some docs explaining this, am I doing this right?


问:
UIPickerView isn't showing as inputview when UITextField begins to edit
I have managed to add a UIPickerView as an input view to UITextField in viewDidLoad, but now I want to make the UITextField as first responder when another textfield (with tag =4) ends editing. This is the code I'm using:

This is in the viewdidload, and all the other code needed to initialize the picker view is there:

```<code> UIPickerView *myPickerView = [[UIPickerView alloc] init];
    myPickerView.showsSelectionIndicator = YES;
    myPickerView.delegate = self;
    myPickerView.dataSource = self;
   myPickerView.backgroundColor = [UIColor colorWithRed:76/255.0 green:76/255.0 blue:76/255.0 alpha:1];
    textfieldInput.inputView = myPickerView;
</code>```

This is in my text field did end editing method:

```<code>-(void)textFieldDidEndEditing:(UITextField *)textField{
    if(textField.tag == 4){
        [textfieldInput becomeFirstResponder];
    }
</code>```

The problem is that when the textfieldInput becomes the first responder, the picker view isn't shown, instead the keyboard is presented.
Also, it should be mentioned that i have another textfield on top of this that gets resigned if it became the first responder and becomes hidden. This textfield is the textfield that has a tag of 4. (This textfield has been added for design reasons).

答:
This code works for me... are you sure that call the correct reference of textfield?

try: [self.textfield becomeFirstResponder];

Body:
I have managed to add a UIPickerView as an input view to UITextField in viewDidLoad, but now I want to make the UITextField as first responder when another textfield (with tag =4) ends editing. This is the code I'm using:

This is in the viewdidload, and all the other code needed to initialize the picker view is there:

 UIPickerView *myPickerView = [[UIPickerView alloc] init];
    myPickerView.showsSelectionIndicator = YES;
    myPickerView.delegate = self;
    myPickerView.dataSource = self;
   myPickerView.backgroundColor = [UIColor colorWithRed:76/255.0 green:76/255.0 blue:76/255.0 alpha:1];
    textfieldInput.inputView = myPickerView;

This is in my text field did end editing method:

-(void)textFieldDidEndEditing:(UITextField *)textField{
    if(textField.tag == 4){
        [textfieldInput becomeFirstResponder];
    }

The problem is that when the textfieldInput becomes the first responder, the picker view isn't shown, instead the keyboard is presented.
Also, it should be mentioned that i have another textfield on top of this that gets resigned if it became the first responder and becomes hidden. This textfield is the textfield that has a tag of 4. (This textfield has been added for design reasons).


问:
Java - get the current class name?
All I am trying to do is to get the current class name, and java appends a useless non-sense $1 to the end of my class name. How can I get rid of it and only return the actual class name?

```<code>String className = this.getClass().getName();
</code>```

答:
The combination of both answers. Also prints a method name:</p>

```<code>Class thisClass = new Object(){}.getClass();
String className = thisClass.getEnclosingClass().getSimpleName();
String methodName = thisClass.getEnclosingMethod().getName();
Log.d("app", className + ":" + methodName);
</code>```

Title: Java - get the current class name?

Body:
All I am trying to do is to get the current class name, and java appends a useless non-sense $1 to the end of my class name. How can I get rid of it and only return the actual class name?

String className = this.getClass().getName();

Body:
The combination of both answers. Also prints a method name:

Class thisClass = new Object(){}.getClass();
String className = thisClass.getEnclosingClass().getSimpleName();
String methodName = thisClass.getEnclosingMethod().getName();
Log.d("app", className + ":" + methodName);


问:
I want to pass a array to function my reference and return array
I wrote the code for a function which sorts an array, which I would then be able to access in main file .

The problem I am facing is that I am not able to understand how pass an array and to sort the array.

Initialization of function.

```<code>void sort (int *ary[], int len);
</code>```

Main function

```<code>int main ()
{
    int max [4]= {2,8,5,9};
    sort(&max, 4);
     for (int l =0; l<4;l++)
     {
         cout<< max[l]<< " "<< endl;
     }
    system("pause");
    return 0;
}
</code>```

function which will sort the array by bubble sort.

```<code>void sort (int *ary[], int len )
{
    int temp=0;
    for (int i = 0; i<len; i ++)
    {
        for (int j= 0 ; j<len ;j++)
        {
            if (ary[j]> ary[j+1])
            {
                temp = ary[j];
                ary[j] = ary[j+1];
                ary[j+1]= temp;
            }
        }
    }
}
</code>```

I get the following error message:

visual studio 2012\projects\problem2\problem2\pract.cpp(11): error
  C2664: 'sort' : cannot convert parameter 1 from 'int [4]' to 'int *[]'

How do I resolve this error?

答:
int *ary[] means an array of pointers. You can write int ary[] to take an array:

```<code>void sort(int ary[], int len);
</code>```

Since it's a function parameter, int ary[] means the same as int* ary, so the above is equivalent to:

```<code>void sort(int* ary, int len);
</code>```

Finally, call it like this (because of array-to-pointer decay):

```<code>sort(max, 4);
</code>```

Body:
I wrote the code for a function which sorts an array, which I would then be able to access in main file .

The problem I am facing is that I am not able to understand how pass an array and to sort the array.

Initialization of function.

void sort (int *ary[], int len);

Main function

int main ()
{
    int max [4]= {2,8,5,9};
    sort(&max, 4);
     for (int l =0; l<4;l++)
     {
         cout<< max[l]<< " "<< endl;
     }
    system("pause");
    return 0;
}

function which will sort the array by bubble sort.

void sort (int *ary[], int len )
{
    int temp=0;
    for (int i = 0; i<len; i ++)
    {
        for (int j= 0 ; j<len ;j++)
        {
            if (ary[j]> ary[j+1])
            {
                temp = ary[j];
                ary[j] = ary[j+1];
                ary[j+1]= temp;
            }
        }
    }
}

I get the following error message:

visual studio 2012\projects\problem2\problem2\pract.cpp(11): error
  C2664: 'sort' : cannot convert parameter 1 from 'int [4]' to 'int *[]'

How do I resolve this error?

Body:
int *ary[] means an array of pointers. You can write int ary[] to take an array:

void sort(int ary[], int len);

Since it's a function parameter, int ary[] means the same as int* ary, so the above is equivalent to:

void sort(int* ary, int len);

Finally, call it like this (because of array-to-pointer decay):

sort(max, 4);


问:
Regex Capture Groups in C#
I'm trying to come up with a regex that will split out a string in 3 different parts: Name, Address, and Phone Number.

This is what I currently have:

```<code>^(?<Name>\w.*)\s+(?<Address>\d+\s\w+.*\d{5,9})\s+(?<Phone>\d+.*)
</code>```

Here is what regex101 is giving me back with the following sample string:

But if I add in a '#' before the suite number, it works as planned:

I've even tried running just the address regex against the entire string in a separate instance and it worked just fine.  There's something going on with the capture groups that's throwing it off.  Any suggestions would be greatly appreciated!

答:
Try making the name non-greedy:</p>

```<code>^(?<Name>\w.*?)\s+(?<Address>\d+\s\w+.*\d{5,9})\s+(?<Phone>\d+.*)
</code>```

Title: Regex Capture Groups in C#

Body:
I'm trying to come up with a regex that will split out a string in 3 different parts: Name, Address, and Phone Number.

This is what I currently have:

^(?<Name>\w.*)\s+(?<Address>\d+\s\w+.*\d{5,9})\s+(?<Phone>\d+.*)

Here is what regex101 is giving me back with the following sample string:

But if I add in a '#' before the suite number, it works as planned:

I've even tried running just the address regex against the entire string in a separate instance and it worked just fine.  There's something going on with the capture groups that's throwing it off.  Any suggestions would be greatly appreciated!

Body:
Try making the name non-greedy:

^(?<Name>\w.*?)\s+(?<Address>\d+\s\w+.*\d{5,9})\s+(?<Phone>\d+.*)


问:
How to choose which jupyter notebook to run?
I have installed jupyter notebook for Python 3 (installed through pip) and for Python 2 (installed through anaconda stack which included scipy and scikit-learn and similar scientific tools).

When I run jupyter notebook in console it opens but I can choose only Python 2 kernel.

答:
In terminal try inputting this:

```<code>python3 -m pip install ipykernel
</code>```

and this:

```<code>python3 -m ipykernel install --user
</code>```

Then restart jupyter and anaconda and you should be able to select the other kernel version.

Body:
In terminal try inputting this:

python3 -m pip install ipykernel

and this:

python3 -m ipykernel install --user

Then restart jupyter and anaconda and you should be able to select the other kernel version.


问:
Making ACE editor resizable
Is there an option to add a handle to the ACE editor window for making the size of the editor window
changeable by the enduser? I tried to use interactjs.io and applied resizable(true) to the .ace_content class but without an effect. What is the preferred way here?</p>

答:
All of the answers on here are specific to handling the resize in JS, but none of them address how you could actually add or setup resizing (as using CSS3 resize attribute will be hidden behind scrollbar)

Here's my solution to resizing the Ace Editor window without jitter, using jQuery UI, or any other additional libs (as that is just additional bloat).

Dragging is handled by a 2px tall div, which on mousedown sets opacity to 0 on the editor, and then back to 1 on mouseup.

This essentially results in the wrapper div showing during the dragging, and then hidden afterwards. Profit!

var editor = ace.edit( "smyles_editor" );
var dragging = false;
var wpoffset = 0;

// If using WordPress uncomment line below as we have to
// 32px for admin bar, minus 1px to center in 2px slider bar
// wpoffset = 31;

editor.setTheme("ace/theme/monokai");
// inline must be true to syntax highlight PHP without opening <?php tag
editor.getSession().setMode( { path: "ace/mode/php", inline: true } );

$( '#smyles_dragbar' ).mousedown( function ( e ) {
 e.preventDefault();
 window.dragging = true;

 var smyles_editor = $( '#smyles_editor' );
 var top_offset = smyles_editor.offset().top - wpoffset;

 // Set editor opacity to 0 to make transparent so our wrapper div shows
 smyles_editor.css( 'opacity', 0 );

 // handle mouse movement
 $( document ).mousemove( function ( e ) {

  var actualY = e.pageY - wpoffset;
  // editor height
  var eheight = actualY - top_offset;

  // Set wrapper height
  $( '#smyles_editor_wrap' ).css( 'height', eheight);

  // Set dragbar opacity while dragging (set to 0 to not show)
  $( '#smyles_dragbar' ).css( 'opacity', 0.15 );

 } );

} );

$( document ).mouseup( function ( e ) {

 if ( window.dragging )
 {
  var smyles_editor = $( '#smyles_editor' );

  var actualY = e.pageY - wpoffset;
  var top_offset = smyles_editor.offset().top - wpoffset;
  var eheight = actualY - top_offset;

  $( document ).unbind( 'mousemove' );

  // Set dragbar opacity back to 1
  $( '#smyles_dragbar' ).css( 'opacity', 1 );

  // Set height on actual editor element, and opacity back to 1
  smyles_editor.css( 'height', eheight ).css( 'opacity', 1 );

  // Trigger ace editor resize()
  editor.resize();
  window.dragging = false;
 }

} );```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  margin: 40px;
}

#smyles_editor {
  height: 300px;
}

#smyles_editor_wrap {
 background-color: #cccccc;
 border-bottom: 1px solid #222222;
}

#smyles_dragbar {
 background-color: #222222;
 width: 100%;
 height: 2px;
 cursor: row-resize;
 opacity: 1;
}</code>```

  Vertically Resizable Ace Editor

function foo($awesome) {

 $x = 'Smyles make resizable window for youuuuu!';

 if( $awesome === TRUE ){
  $x = 'Enjoy!';
 }

 return x;
}

```

http://jsfiddle.net/tripflex/knnv5e7s/

Title: Making ACE editor resizable

Body:
All of the answers on here are specific to handling the resize in JS, but none of them address how you could actually add or setup resizing (as using CSS3 resize attribute will be hidden behind scrollbar)

Here's my solution to resizing the Ace Editor window without jitter, using jQuery UI, or any other additional libs (as that is just additional bloat).

Dragging is handled by a 2px tall div, which on mousedown sets opacity to 0 on the editor, and then back to 1 on mouseup.

This essentially results in the wrapper div showing during the dragging, and then hidden afterwards. Profit!

var editor = ace.edit( "smyles_editor" );
var dragging = false;
var wpoffset = 0;

// If using WordPress uncomment line below as we have to
// 32px for admin bar, minus 1px to center in 2px slider bar
// wpoffset = 31;

editor.setTheme("ace/theme/monokai");
// inline must be true to syntax highlight PHP without opening <?php tag
editor.getSession().setMode( { path: "ace/mode/php", inline: true } );

$( '#smyles_dragbar' ).mousedown( function ( e ) {
 e.preventDefault();
 window.dragging = true;

 var smyles_editor = $( '#smyles_editor' );
 var top_offset = smyles_editor.offset().top - wpoffset;

 // Set editor opacity to 0 to make transparent so our wrapper div shows
 smyles_editor.css( 'opacity', 0 );

 // handle mouse movement
 $( document ).mousemove( function ( e ) {

  var actualY = e.pageY - wpoffset;
  // editor height
  var eheight = actualY - top_offset;

  // Set wrapper height
  $( '#smyles_editor_wrap' ).css( 'height', eheight);

  // Set dragbar opacity while dragging (set to 0 to not show)
  $( '#smyles_dragbar' ).css( 'opacity', 0.15 );

 } );

} );

$( document ).mouseup( function ( e ) {

 if ( window.dragging )
 {
  var smyles_editor = $( '#smyles_editor' );

  var actualY = e.pageY - wpoffset;
  var top_offset = smyles_editor.offset().top - wpoffset;
  var eheight = actualY - top_offset;

  $( document ).unbind( 'mousemove' );

  // Set dragbar opacity back to 1
  $( '#smyles_dragbar' ).css( 'opacity', 1 );

  // Set height on actual editor element, and opacity back to 1
  smyles_editor.css( 'height', eheight ).css( 'opacity', 1 );

  // Trigger ace editor resize()
  editor.resize();
  window.dragging = false;
 }

} );

body {
  margin: 40px;
}

#smyles_editor {
  height: 300px;
}

#smyles_editor_wrap {
 background-color: #cccccc;
 border-bottom: 1px solid #222222;
}

#smyles_dragbar {
 background-color: #222222;
 width: 100%;
 height: 2px;
 cursor: row-resize;
 opacity: 1;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.6/ace.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2>
  Vertically Resizable Ace Editor
</h2>
<br/>
<div id="smyles_editor_wrap">
 <div id="smyles_editor">function foo($awesome) {

 $x = 'Smyles make resizable window for youuuuu!';

 if( $awesome === TRUE ){
  $x = 'Enjoy!';
 }

 return x;
}</div>
 <div id="smyles_dragbar"></div>
</div>

http://jsfiddle.net/tripflex/knnv5e7s/


答:
type coercion in javascript

```<code>var s = "1";
var i = 1;

var i = i+1;
// 2    int + int = int
var s2 = s+1;
// "11" str + int = str
var s3 = i+"1";
// "11" int + str = str
</code>```

Body:
So I need the code to use addition on random numbers in the array. If the sum is greater then ten, it should say "over" else it would be "under."

`

function arraries(){
       var oneten = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
               document.getElementById('demo').innerHTML = addy(oneten);
   }

function addy(oneten){
     var n;
    var output;
    var sum = "";

    for (i = 0; i < 4; i++){
        n = Math.floor((Math.random() * 10) + 1);
        sum += parseFloat(oneten[n])}

    if (sum > 10){
        return "over";

    }
    else { return  "under";}

}

The problem here is that the debugger decipher the numbers as strings. While running the sum would equal "1234" instead of 10 (which is 1 + 2 + 3 + 4) and thus it will always return "over". How can I make sure that the data will be treat as actually numbers instead of strings? I used parseFloat and parseInt but I got the same results

Body:
type coercion in javascript

var s = "1";
var i = 1;

var i = i+1;
// 2    int + int = int
var s2 = s+1;
// "11" str + int = str
var s3 = i+"1";
// "11" int + str = str


问:
How can I use the values Selected in a While Exists statement inside the While loop?
I'm new-ish to SQL and am trying to figure out how to use the values from the Select statement in a While Exists conditional loop.  The purpose is to combine multiple occurences of an attribute for a Document into a single field, and later pivot and join those results to the Document record.

For example, three tables exist like so:

ATTRIBUTES TABLE

ID, ATTRIBUTE_NAME

---------------------------

1, Created

2, Embedded_Image

...

ATTRIBUTE_VALUES TABLE

ATTRIBUTE_ID, VALUE, DOC_ID

-------------------------------------------

1, 2010/11/01, 1

2, 'Home.png', 1

2, 'Castle.png', 1

2, 'Apartment.jpg', 1

1, 2008/06/23, 2

2, 'Ski Jump.jpg', 2

2, 'Snowboarding.png', 2

...

DOCUMENTS TABLE

ID, TEXT

---------------------------

1, 'Homes of the ...'

2, 'Winter sports ...'

...

So a final Pivot and Join of the tables would look like so:

DOC_ID, TEXT, Created, Embedded_Image

----------------------------------------------------------------------------------------

1, 'Homes of the ...', 2010/11/01, 'Home.png,Castle.png,Apartment.jpg'

2, 'Winter sports ...', 2008/06/23, 'Ski Jump.jpg, Snowboarding.png'

The SQL While Exists condition I've tried to write looks like so:
    ```<code>
    DECLARE @LOOP_DOC_ID UNIQUEIDENTIFIER
    DECLARE @LOOP_ATTRIBUTE_NAME NVARCHAR(MAX)<br>
    WHILE EXISTS(
      SELECT [dbo].[ATTRIBUTE_VALUES].[DOC_ID], [dbo].[ATTRIBUTES].[ATTRIBUTE_NAME]
      FROM ([dbo].[ATTRIBUTE_VALUES] INNER JOIN [dbo].[ATTRIBUTES]
      ON [dbo].[ATTRIBUTE_VALUES].[ATTRIBUTE_ID] = [dbo].[ATTRIBUTES].[ID])
    )
    BEGIN
      SET @LOOP_DOC_ID = DOC_ID
      SET @LOOP_ATTRIBUTE_NAME = ATTRIBUTE_NAME<br>
      SELECT STUFF(
        (
          SELECT DISTINCT ',' + RTRIM(LTRIM([dbo].[ATTRIBUTE_VALUES].[VALUE]))
          FROM
            (
              [dbo].[ATTRIBUTE_VALUES] INNER JOIN [dbo].[ATTRIBUTES]
              ON [dbo].[ATTRIBUTE_VALUES].[ATTRIBUTE_ID] = [dbo].[ATTRIBUTES].[ID]
            )
          WHERE [dbo].[ATTRIBUTE_VALUES].[DOC_ID] = @LOOP_DOC_ID
                AND [dbo].[ATTRIBUTES].[ATTRIBUTE_NAME] = @LOOP_ATTRIBUTE_NAME
          ORDER BY ',' + RTRIM(LTRIM([dbo].[ATTRIBUTE_VALUES].[VALUE]))
          FOR XML PATH('')
        ), 1, 2, ''
      ) AS VALUE, @LOOP_DOC_ID AS DOC_ID, @LOOP_ATTRIBUTE_NAME AS ATTRIBUTE_NAME
    END
    </code>```
SQL Server doesn't like the lines where I'm trying to SET the variables to the values from the Select statement in the While Exists condition.

How can I use the [dbo].[ATTRIBUTE_VALUES].[DOC_ID], [dbo].[ATTRIBUTES].[ATTRIBUTE_NAME] values Selected in the While Exists conditional statement between the BEGIN and END statements?

Preferrably I would like to do away with the @LOOP_DOC_ID and @LOOP_ATTRIBUTE_NAME variables and deal directly with the values.

I've looked through forums that have talked about using Cursors to solve similar problems, but each one of them seem to recommend only using Cursors as a last resort due to their lack of speed.  I've also seen some people use stored procedures, but I can't use those, since my boss has ruled those as off-limits.  Am I in need of a Cursor, or is there a better way to do this?

答:
From your sample, and with support from common sense, I venture the hypothesis that

A document has a single creation date.

A document can have many embedded images.

So pivoting on creation date is straightforward:

```<code>SELECT DOC_ID
, VALUE AS Created
FROM ATTRIBUTE_VALUES
WHERE ATTRIBUTE_ID = 1
</code>```

and joining this subquery to your Documents table gives you the first three columns of your desired output.

Your final column summarizes multiple embedded images for each document.  I personally would use some standard reporting tool (e.g. MS Access or Crystal Reports).  Alternatively, create a new empty table with your four desired columns, populate the first three columns with a SQL INSERT statement, and then have Perl (or C#, or your favorite declarative language) query for the embedded images of each document, concatenate the results with commas, and insert the concatenation into your fourth column.

But if you want to do it in SQL, the concatenate-multiple-values question has been asked here before, e.g. in How to create a SQL Server function to "join" multiple rows from a subquery into a single delimited field?.

Body:
I'm new-ish to SQL and am trying to figure out how to use the values from the Select statement in a While Exists conditional loop.  The purpose is to combine multiple occurences of an attribute for a Document into a single field, and later pivot and join those results to the Document record.

For example, three tables exist like so:

ATTRIBUTES TABLE

ID, ATTRIBUTE_NAME

---------------------------

1, Created

2, Embedded_Image

...

ATTRIBUTE_VALUES TABLE

ATTRIBUTE_ID, VALUE, DOC_ID

-------------------------------------------

1, 2010/11/01, 1

2, 'Home.png', 1

2, 'Castle.png', 1

2, 'Apartment.jpg', 1

1, 2008/06/23, 2

2, 'Ski Jump.jpg', 2

2, 'Snowboarding.png', 2

...

DOCUMENTS TABLE

ID, TEXT

---------------------------

1, 'Homes of the ...'

2, 'Winter sports ...'

...

So a final Pivot and Join of the tables would look like so:

DOC_ID, TEXT, Created, Embedded_Image

----------------------------------------------------------------------------------------

1, 'Homes of the ...', 2010/11/01, 'Home.png,Castle.png,Apartment.jpg'

2, 'Winter sports ...', 2008/06/23, 'Ski Jump.jpg, Snowboarding.png'

The SQL While Exists condition I've tried to write looks like so:

    DECLARE @LOOP_DOC_ID UNIQUEIDENTIFIER
    DECLARE @LOOP_ATTRIBUTE_NAME NVARCHAR(MAX)

    WHILE EXISTS(
      SELECT [dbo].[ATTRIBUTE_VALUES].[DOC_ID], [dbo].[ATTRIBUTES].[ATTRIBUTE_NAME]
      FROM ([dbo].[ATTRIBUTE_VALUES] INNER JOIN [dbo].[ATTRIBUTES]
      ON [dbo].[ATTRIBUTE_VALUES].[ATTRIBUTE_ID] = [dbo].[ATTRIBUTES].[ID])
    )
    BEGIN
      SET @LOOP_DOC_ID = DOC_ID
      SET @LOOP_ATTRIBUTE_NAME = ATTRIBUTE_NAME

      SELECT STUFF(
        (
          SELECT DISTINCT ',' + RTRIM(LTRIM([dbo].[ATTRIBUTE_VALUES].[VALUE]))
          FROM
            (
              [dbo].[ATTRIBUTE_VALUES] INNER JOIN [dbo].[ATTRIBUTES]
              ON [dbo].[ATTRIBUTE_VALUES].[ATTRIBUTE_ID] = [dbo].[ATTRIBUTES].[ID]
            )
          WHERE [dbo].[ATTRIBUTE_VALUES].[DOC_ID] = @LOOP_DOC_ID
                AND [dbo].[ATTRIBUTES].[ATTRIBUTE_NAME] = @LOOP_ATTRIBUTE_NAME
          ORDER BY ',' + RTRIM(LTRIM([dbo].[ATTRIBUTE_VALUES].[VALUE]))
          FOR XML PATH('')
        ), 1, 2, ''
      ) AS VALUE, @LOOP_DOC_ID AS DOC_ID, @LOOP_ATTRIBUTE_NAME AS ATTRIBUTE_NAME
    END

SQL Server doesn't like the lines where I'm trying to SET the variables to the values from the Select statement in the While Exists condition.

How can I use the [dbo].[ATTRIBUTE_VALUES].[DOC_ID], [dbo].[ATTRIBUTES].[ATTRIBUTE_NAME] values Selected in the While Exists conditional statement between the BEGIN and END statements?

Preferrably I would like to do away with the @LOOP_DOC_ID and @LOOP_ATTRIBUTE_NAME variables and deal directly with the values.

I've looked through forums that have talked about using Cursors to solve similar problems, but each one of them seem to recommend only using Cursors as a last resort due to their lack of speed.  I've also seen some people use stored procedures, but I can't use those, since my boss has ruled those as off-limits.  Am I in need of a Cursor, or is there a better way to do this?

Body:
From your sample, and with support from common sense, I venture the hypothesis that

A document has a single creation date.

A document can have many embedded images.

So pivoting on creation date is straightforward:

SELECT DOC_ID
, VALUE AS Created
FROM ATTRIBUTE_VALUES
WHERE ATTRIBUTE_ID = 1

and joining this subquery to your Documents table gives you the first three columns of your desired output.

Your final column summarizes multiple embedded images for each document.  I personally would use some standard reporting tool (e.g. MS Access or Crystal Reports).  Alternatively, create a new empty table with your four desired columns, populate the first three columns with a SQL INSERT statement, and then have Perl (or C#, or your favorite declarative language) query for the embedded images of each document, concatenate the results with commas, and insert the concatenation into your fourth column.

But if you want to do it in SQL, the concatenate-multiple-values question has been asked here before, e.g. in How to create a SQL Server function to "join" multiple rows from a subquery into a single delimited field?.


问:
Set different directives per router-view
https://jsfiddle.net/guanzo/8fdbcaxo/2/

The Vue instance has 2  router-view's, foo and bar. How do i conditionally set directives, based on if the router-view is a foo or bar component? Right now i'm forced to give the same directives to these 2 child components, but what if i want to handle them differently?

Something like this

```<code><router-view v-if="isFoo" v-show="showFoo" ></router-view>
<router-view v-else-if="isBar" @click="handleClick" ></router-view>
</code>```

答:
One way is to have two separate named router-views, that way you can attach directives to the specific router-view that you want.

I've updated your fiddle to demonstrate this.

Don't overuse this, though. Think about whose responsibility is should be to handle the click event - App or Bar? If it's the latter, you might want to put the directive in the Bar component and communicate back to the parent component.

Body:
https://jsfiddle.net/guanzo/8fdbcaxo/2/

The Vue instance has 2  router-view's, foo and bar. How do i conditionally set directives, based on if the router-view is a foo or bar component? Right now i'm forced to give the same directives to these 2 child components, but what if i want to handle them differently?

Something like this

<router-view v-if="isFoo" v-show="showFoo" ></router-view>
<router-view v-else-if="isBar" @click="handleClick" ></router-view>


问:
Star B-V color index to apparent RGB color
I'm trying to convert a star's B-V color index to an apparent RGB color. Besides look up tables and color ramps, it seems like there's no well known algorithm for doing this.

What's a B-V color index?

It's a number astronomers assign to a star to indicate its apparent color. Hot stars (low B-V) are blue/purple and cool stars (high B-V) are red with those white/orange stars in between.

Initial algorithm

B-V to Kelvin

```<code>var t = 4600 * ((1 / ((0.92 * bv) + 1.7)) +(1 / ((0.92 * bv) + 0.62)) );
</code>```

Kelvin to xyY

If you model a star as a blackbody, then you can use a numerical approximation of the Planckian locus to compute the xy coordinates (CIE chromaticity)

```<code>// t to xyY
var x, y = 0;

if (t>=1667 && t<=4000) {
  x = ((-0.2661239 * Math.pow(10,9)) / Math.pow(t,3)) + ((-0.2343580 * Math.pow(10,6)) / Math.pow(t,2)) + ((0.8776956 * Math.pow(10,3)) / t) + 0.179910;
} else if (t > 4000 && t <= 25000) {
  x = ((-3.0258469 * Math.pow(10,9)) / Math.pow(t,3)) + ((2.1070379 * Math.pow(10,6)) / Math.pow(t,2)) + ((0.2226347 * Math.pow(10,3)) / t) + 0.240390;
}

if (t >= 1667 && t <= 2222) {
  y = -1.1063814 * Math.pow(x,3) - 1.34811020 * Math.pow(x,2) + 2.18555832 * x - 0.20219683;
} else if (t > 2222 && t <= 4000) {
  y = -0.9549476 * Math.pow(x,3) - 1.37418593 * Math.pow(x,2) + 2.09137015 * x - 0.16748867;
} else if (t > 4000 && t <= 25000) {
  y = 3.0817580 * Math.pow(x,3) - 5.87338670 * Math.pow(x,2) + 3.75112997 * x - 0.37001483;
}
</code>```

xyY to XYZ (Y = 1)

```<code>// xyY to XYZ, Y = 1
var Y = (y == 0)? 0 : 1;
var X = (y == 0)? 0 : (x * Y) / y;
var Z = (y == 0)? 0 : ((1 - x - y) * Y) / y;
</code>```

XYZ to RGB

```<code>var r = 0.41847 * X - 0.15866 * Y - 0.082835 * Z;
var g = -0.091169 * X + 0.25243 * Y + 0.015708 * Z;
var b = 0.00092090 * X - 0.0025498 * Y + 0.17860 * Z;
</code>```

Question

I ran this algorithm with the B-V color indexes: 1.2, 1.0, 0.59, 0.0, -0.29. This is what I got as output.

Why did I get this strange output? Hot stars are bluish but cold stars are brownish and there doesn't seem to be white/orange intermediate stars.

Update

Following on a comment by Ozan, it seemed like I was using a wrong matrix to convert XYZ to RGB. Since sRGB is the default color space on the web (or is it?), I'm now using the correct matrix followed by a gamma correction function (a = 0.055).

I now get this nice color ramp,

but there's still no red/violet at the extremities.

Demo

There's also a fiddle now that you can play with.

Update 2

If use a gamma of 0.5 and extend the range of B-V color indexes to be from 4.7 to -0.5, I get red at one extreme but still no violet. Here's the updated fiddle.

Body:
I'm trying to convert a star's B-V color index to an apparent RGB color. Besides look up tables and color ramps, it seems like there's no well known algorithm for doing this.

What's a B-V color index?

It's a number astronomers assign to a star to indicate its apparent color. Hot stars (low B-V) are blue/purple and cool stars (high B-V) are red with those white/orange stars in between.

Initial algorithm

B-V to Kelvin

var t = 4600 * ((1 / ((0.92 * bv) + 1.7)) +(1 / ((0.92 * bv) + 0.62)) );

Kelvin to xyY

If you model a star as a blackbody, then you can use a numerical approximation of the Planckian locus to compute the xy coordinates (CIE chromaticity)

// t to xyY
var x, y = 0;

if (t>=1667 && t<=4000) {
  x = ((-0.2661239 * Math.pow(10,9)) / Math.pow(t,3)) + ((-0.2343580 * Math.pow(10,6)) / Math.pow(t,2)) + ((0.8776956 * Math.pow(10,3)) / t) + 0.179910;
} else if (t > 4000 && t <= 25000) {
  x = ((-3.0258469 * Math.pow(10,9)) / Math.pow(t,3)) + ((2.1070379 * Math.pow(10,6)) / Math.pow(t,2)) + ((0.2226347 * Math.pow(10,3)) / t) + 0.240390;
}

if (t >= 1667 && t <= 2222) {
  y = -1.1063814 * Math.pow(x,3) - 1.34811020 * Math.pow(x,2) + 2.18555832 * x - 0.20219683;
} else if (t > 2222 && t <= 4000) {
  y = -0.9549476 * Math.pow(x,3) - 1.37418593 * Math.pow(x,2) + 2.09137015 * x - 0.16748867;
} else if (t > 4000 && t <= 25000) {
  y = 3.0817580 * Math.pow(x,3) - 5.87338670 * Math.pow(x,2) + 3.75112997 * x - 0.37001483;
}

xyY to XYZ (Y = 1)

// xyY to XYZ, Y = 1
var Y = (y == 0)? 0 : 1;
var X = (y == 0)? 0 : (x * Y) / y;
var Z = (y == 0)? 0 : ((1 - x - y) * Y) / y;

XYZ to RGB

var r = 0.41847 * X - 0.15866 * Y - 0.082835 * Z;
var g = -0.091169 * X + 0.25243 * Y + 0.015708 * Z;
var b = 0.00092090 * X - 0.0025498 * Y + 0.17860 * Z;

Question

I ran this algorithm with the B-V color indexes: 1.2, 1.0, 0.59, 0.0, -0.29. This is what I got as output.

Why did I get this strange output? Hot stars are bluish but cold stars are brownish and there doesn't seem to be white/orange intermediate stars.

Update

Following on a comment by Ozan, it seemed like I was using a wrong matrix to convert XYZ to RGB. Since sRGB is the default color space on the web (or is it?), I'm now using the correct matrix followed by a gamma correction function (a = 0.055).

I now get this nice color ramp,

but there's still no red/violet at the extremities.

Demo

There's also a fiddle now that you can play with.

Update 2

If use a gamma of 0.5 and extend the range of B-V color indexes to be from 4.7 to -0.5, I get red at one extreme but still no violet. Here's the updated fiddle.

Body:
@Spektre's answer in Swift 3.0:

private func bv2ToRGB(for bv: CGFloat, logging: Bool = false) -> Color {
    var bv = bv
    var t: CGFloat = 0
    var r: CGFloat = 0
    var g: CGFloat = 0
    var b: CGFloat = 0

    if bv < -0.4 { bv = -0.4}
    if bv > 2.0 { bv = 2.0}

    switch bv {
    case -0.4 ... 0.0:
        t = (bv+0.40)/(0.00+0.40)
        r = 0.61+(0.11*t)+(0.1*t*t)
    case 0.0 ... 0.4:
        t = (bv-0.00)/(0.40-0.00)
        r = 0.83+(0.17*t)
    case 0.4 ... 2.1:
        t = (bv-0.40)/(2.10-0.40)
        r = 1.00
    default: break
    }

    switch bv {
    case -0.4 ... 0.0:
        t = (bv+0.40)/(0.00+0.40)
        g = 0.70 + (0.07*t)+(0.1*t*t)
    case 0.0 ... 0.4:
        t = (bv-0.00)/(0.40-0.00)
        g = 0.87 + (0.11*t)
    case 0.4 ... 1.6:
        t = (bv-0.40)/(1.60-0.40)
        g = 0.98 - (0.16*t)
    case 1.6 ... 2.0:
        t = (bv-1.60)/(2.00-1.60)
        g = 0.82         - (0.5*t*t)
    default: break
    }

    switch bv {
    case -0.4 ... 0.4:
        t = (bv+0.40)/(0.40+0.40)
        b = 1.0
    case 0.4 ... 1.5:
        t = (bv-0.40)/(1.50-0.40)
        b = 1.00 - (0.47*t)+(0.1*t*t)
    case 1.5 ... 1.94:
        t = (bv-1.50)/(1.94-1.50)
        b = 0.63         - (0.6*t*t)
    default: break
    }

    #if os(OSX)
        return NSColor(calibratedRed: r, green: g, blue: b, alpha: 1.0)
    #else
        return UIColor(red: r, green: g, blue: b, alpha: 1.0)
    #endif
}


问:
Xamarin Forms: CachingStrategy not available
In Xamarin Forms i have added a Listview:

```<code><ListView x:Name="StudentView"  RowHeight="55"  SeparatorVisibility="None">
</code>```

Why the CachingStrategy property is not available? If i try to add that property, intellisense not show that property and seems not available

答:
On Visual Studio CachingStrategy IntelliSense don't work properly.

Try writing it manually:

```<code><ListView CachingStrategy="RecycleElement">
</code>```

Body:
In Xamarin Forms i have added a Listview:

<ListView x:Name="StudentView"  RowHeight="55"  SeparatorVisibility="None">

Why the CachingStrategy property is not available? If i try to add that property, intellisense not show that property and seems not available

Body:
On Visual Studio CachingStrategy IntelliSense don't work properly.

Try writing it manually:

<ListView CachingStrategy="RecycleElement">


问:
How can i implement the first name of the contact disappear as i scroll the contacts
In android contacts application, if I set the 'Sort list by' options to 'Last name', when I scroll the contacts list view, the first name of that contact is invisible. But the scrolling stop, the first name of the contact is visible.

I have a list view in my application, how can i get notified when does my list view stops scrolling?

Thank you.

答: See the Android API Demos app on the emulator; there's a "slow adapter" example that does this (source code). The key part is in the onScrollStateChanged method where it checks the scrollState for OnScrollListener.SCROLL_STATE_IDLE, SCROLL_STATE_TOUCH_SCROLL and SCROLL_STATE_FLING (and related state-check code in the getView method).