问:
What is the cause of the artifacts of this convoluted signal?
I am trying to find out the cause of the artifacts that appear after convolution, they are to be seen in the plot arround x = -.0016 and x= .0021 (please see the code below). I am convoluting the "lorentzian" function (or the derivative of the langevin function) which I define in the code, with 2 Dirac impulses in the function "ditrib".

I would appreciate your help.
Thank you
Here is my code:

```<code>    import numpy as np
    import matplotlib.pyplot as plt

    def Lorentzian(xx):
        if not hasattr(xx, '__iter__'):
            xx = [ xx ]
        res = np.zeros(len(xx))
        for i in range(len(xx)):
            x = xx[i]
            if np.fabs(x) < 0.1:
                res[i] =  1./3. - x**2/15. + 2.* x**4 / 189. - x**6/675. + 2.* x**8 / 10395. - 1382. * x**10 / 58046625. + 4. * x**12 / 1403325.
            else:
                res[i] = (1./x**2 - 1./np.sinh(x)**2)
        return res

    amp = 18e-3
    a = 1/.61e3
    b = 5.5
    t_min = 0
    dt = 1/5e6
    t_max = (10772) * dt
    t = np.arange(t_min,t_max,dt)
    x_min = -amp/b
    x_max = amp/b
    dx =  dt*(x_min-x_max)/(t_min-t_max)
    x = np.arange(x_min,x_max,dx)

    func1 = lambda x : Lorentzian(b*(x/a))

    def distrib(x):
        res = np.zeros(np.size(x))
        res[int(np.floor(np.size(x)/3))] = 1
        res[int(3*np.floor(np.size(x)/4))] = 3
        return res
    func2 = lambda x,xs : np.convolve(distrib(x), func1(xs), 'same')

    plt.plot(x, func2(x,x))
    plt.xlabel('x (m)')
    plt.ylabel('normalized signal')
</code>```

答:
try removing the "pedestal" of func1

```<code>func1(x)[0], func1(x)[-1]
Out[7]: (0.0082945964013920719, 0.008297677313152443)
</code>```

just subtract

```<code>func2 = lambda x,xs : np.convolve(distrib(x), func1(xs)-func1(x)[0], 'same')
</code>```

gives a smooth convolution curve

depending on the result you want you may have to add it back in after, weighted by the Dirac sum

Body:
I am trying to find out the cause of the artifacts that appear after convolution, they are to be seen in the plot arround x = -.0016 and x= .0021 (please see the code below). I am convoluting the "lorentzian" function (or the derivative of the langevin function) which I define in the code, with 2 Dirac impulses in the function "ditrib".

I would appreciate your help.
Thank you
Here is my code:

    import numpy as np
    import matplotlib.pyplot as plt

    def Lorentzian(xx):
        if not hasattr(xx, '__iter__'):
            xx = [ xx ]
        res = np.zeros(len(xx))
        for i in range(len(xx)):
            x = xx[i]
            if np.fabs(x) < 0.1:
                res[i] =  1./3. - x**2/15. + 2.* x**4 / 189. - x**6/675. + 2.* x**8 / 10395. - 1382. * x**10 / 58046625. + 4. * x**12 / 1403325.
            else:
                res[i] = (1./x**2 - 1./np.sinh(x)**2)
        return res

    amp = 18e-3
    a = 1/.61e3
    b = 5.5
    t_min = 0
    dt = 1/5e6
    t_max = (10772) * dt
    t = np.arange(t_min,t_max,dt)
    x_min = -amp/b
    x_max = amp/b
    dx =  dt*(x_min-x_max)/(t_min-t_max)
    x = np.arange(x_min,x_max,dx)

    func1 = lambda x : Lorentzian(b*(x/a))

    def distrib(x):
        res = np.zeros(np.size(x))
        res[int(np.floor(np.size(x)/3))] = 1
        res[int(3*np.floor(np.size(x)/4))] = 3
        return res
    func2 = lambda x,xs : np.convolve(distrib(x), func1(xs), 'same')

    plt.plot(x, func2(x,x))
    plt.xlabel('x (m)')
    plt.ylabel('normalized signal')

Body:
try removing the "pedestal" of func1

func1(x)[0], func1(x)[-1]
Out[7]: (0.0082945964013920719, 0.008297677313152443)

just subtract

func2 = lambda x,xs : np.convolve(distrib(x), func1(xs)-func1(x)[0], 'same')

gives a smooth convolution curve

depending on the result you want you may have to add it back in after, weighted by the Dirac sum


来源: stackexchange

问:
add background image in active class css bootstrap
I am using bootstrap tabs. I want to use a down arrow for active class on tabs.

```<code><ul class="nav nav-tabs" style="font-size:20px;">
                  <li><a  class="active" data-toggle="tab" href="#menu1"><span class="glyphicon glyphicon-sound-dolby"></span></a></li>
                  <li><a data-toggle="tab" href="#menu2"><span class="glyphicon glyphicon-send"></span></a></li>
                  <li><a data-toggle="tab" href="#menu3"><span class="glyphicon glyphicon-earphone"></span></a></li>
                  <li><a data-toggle="tab" href="#menu4"><span class="glyphicon glyphicon-send"></span></a></li>
                </ul>
</code>```

Here is css of active class.

```<code>.nav-tabs>li.active>a, .nav-tabs>li.active>a:focus, .nav-tabs>li.active>a:hover {
    color: #555;
    cursor: default;
    background-color: #fff;
    background: url('../image/down.png') no-repeat !important;
    border: 1px solid #ddd;
    border-bottom-color: transparent;
}
</code>```

Right now its just displaying white background for active class.
But not the image.
Kindly help me. Thank you

答:
Alternatively you can try this--

Working snippet

 .nav li.active  {

    cursor: default;
    background: url('https://www.w3schools.com/css/img_fjords.jpg') no-repeat !important;
     background-size: contain;
    border: 1px solid #ddd;
    border-bottom-color: transparent;
}
.nav-tabs>li.active>a, .nav-tabs>li.active>a:focus, .nav-tabs>li.active>a:hover {
  background-color: transparent !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<ul class="nav nav-tabs" style="font-size:20px;">
                  <li><span class="glyphicon glyphicon-sound-dolby"></span></li>
                  <li><span class="glyphicon glyphicon-send"></span></li>
                  <li><span class="glyphicon glyphicon-earphone"></span></li>
                  <li><span class="glyphicon glyphicon-send"></span></li>
                </ul></code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using bootstrap tabs. I want to use a down arrow for active class on tabs.

Here is css of active class.

.nav-tabs>li.active>a, .nav-tabs>li.active>a:focus, .nav-tabs>li.active>a:hover {
    color: #555;
    cursor: default;
    background-color: #fff;
    background: url('../image/down.png') no-repeat !important;
    border: 1px solid #ddd;
    border-bottom-color: transparent;
}

Right now its just displaying white background for active class.
But not the image.
Kindly help me. Thank you

Body:
Alternatively you can try this--

Working snippet

 .nav li.active  {

    cursor: default;
    background: url('https://www.w3schools.com/css/img_fjords.jpg') no-repeat !important;
     background-size: contain;
    border: 1px solid #ddd;
    border-bottom-color: transparent;
}
.nav-tabs>li.active>a, .nav-tabs>li.active>a:focus, .nav-tabs>li.active>a:hover {
  background-color: transparent !important;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<ul class="nav nav-tabs" style="font-size:20px;">
                  <li><a  class="active" data-toggle="tab" href="#menu1"><span class="glyphicon glyphicon-sound-dolby"></span></a></li>
                  <li><a data-toggle="tab" href="#menu2"><span class="glyphicon glyphicon-send"></span></a></li>
                  <li><a data-toggle="tab" href="#menu3"><span class="glyphicon glyphicon-earphone"></span></a></li>
                  <li><a data-toggle="tab" href="#menu4"><span class="glyphicon glyphicon-send"></span></a></li>
                </ul>


问:
Error in initializing ST-Link Device - Failed to connect to device
I am currently using the ST-Link debugger to program my STM32F3 Discovery Board. The IDE that I am using is Atollic TrueStudio 5.5.2. Now I am facing a very weird problem which is I keep on getting the message

Error in initializing ST-Link Device. Reason : (-1) Failed to connect to device . Please check power and cabling to target.

whenever I want to download the program into my STM32. I have tried some solutions that I found from internet but the problem still exists. Has anyone faced this problems before? Any suggestions will help.

Here is the solution I found, but I doesn't work for me.
http://www.kerrywong.com/2012/08/02/the-dreaded-cannot-connect-to-st-link-error-message/

答: In the debugger tab, make sure to select SWD, not JTAG.

ContentLicense: CC BY-SA 4.0


问:
Completely remove a div if screen width is less than 800 (mobile device)
So i've been looking around and i can't really find i good solution on this so i hope some of you could help me out...
I am trying to remove a div so it doesn't exist if my screen size is around the size of a mobile... I know there is display none which makes the div invisible but since i got a setInterval function on that div it stil load each 5 second... So my question is:

Can i remove a div completely if my screen is less than x pixels

or is it possible to only run my setinterval function when the width is more than x?

Thanks for your time!

```<code>    setInterval(function(){
$( ".chatMessages" ).load( "getMeddelanden.php" );
},5000);
</code>```

答:
you may not need a setInterval, you can base your test on a window.resize which is triggered also on page load on device mobiles
See here for an explanation of mobile viewports:

http://www.quirksmode.org/mobile/viewports2.html

```<code>window.onresize = function(){
 // set your business here

}
</code>```

Body:
So i've been looking around and i can't really find i good solution on this so i hope some of you could help me out...
I am trying to remove a div so it doesn't exist if my screen size is around the size of a mobile... I know there is display none which makes the div invisible but since i got a setInterval function on that div it stil load each 5 second... So my question is:

Can i remove a div completely if my screen is less than x pixels

or is it possible to only run my setinterval function when the width is more than x?

Thanks for your time!

    setInterval(function(){
$( ".chatMessages" ).load( "getMeddelanden.php" );
},5000);

Body:
you may not need a setInterval, you can base your test on a window.resize which is triggered also on page load on device mobiles
See here for an explanation of mobile viewports:

http://www.quirksmode.org/mobile/viewports2.html

window.onresize = function(){
 // set your business here

}


问:
Binding to Component Property inside ngFor
I have a filter component that is completely separated from the views that contain the data I am iterating over. I can get the filter pipe to work in the following scenario when I pass the value into the pipe using the input element reference:

```<code><div class="card-subject">
  <input type="text" #filter (keyup)="0">
  <div *ngFor="let team of teams | filterData: filter.value">
    <h2>{{ team.name }}</h2>
    <h2>{{ team.num }}</h2>
  </div>
</div>
</code>```

In the above case the input element lives within the component and is simple. However what I am trying to do is have the input live inside its own component as it will be reused for various different types of cards.

```<code><card-directory-search-bar></card-directory-search-bar>
<div class="card-subject">
  <div *ngFor="let team of teams | filterData: filter.value">
    <h2>{{ team.name }}</h2>
    <h2>{{ team.num }}</h2>
  </div>
</div>
</code>```

I have subscribed to an observable inside the card and am able to get the values typed into the filter input field. I cannot figure out how to get those values passed into the pipe.

Inside the component I have the values being stored in a property as follows:

```<code>ngOnInit() {
  this.sub = this.search.getChangeEvent()
    .subscribe((value) => {
      this.value = value;
    }
  );
}
</code>```

I cannot figure out how to pass the value into the pipe. I have tried to bind the property inside the ngFor as follows but it does not work

```<code><div *ngFor="let team of teams | filterData: {value}">
</code>```

When I update the code as follows I get the error below:

```<code><card-directory-search-bar></card-directory-search-bar>
<div class="card-subject">
  <div *ngFor="let team of teams | filterData: {value}">
    <h2>{{ team.name }}</h2>
    <h2>{{ team.num }}</h2>
  </div>
</div>
</code>```

And the subscription works well:

How can I get the updated value into the pipe?

Thanks,

答:
You should remove the brackets and use the pipe parameter like this:</p>

```<code><div *ngFor="let team of teams | filterData: value">
</code>```

Body:
I have a filter component that is completely separated from the views that contain the data I am iterating over. I can get the filter pipe to work in the following scenario when I pass the value into the pipe using the input element reference:

  <input type="text" #filter (keyup)="0">

{{ team.name }}

{{ team.num }}

In the above case the input element lives within the component and is simple. However what I am trying to do is have the input live inside its own component as it will be reused for various different types of cards.

<card-directory-search-bar></card-directory-search-bar>

{{ team.name }}

{{ team.num }}

I have subscribed to an observable inside the card and am able to get the values typed into the filter input field. I cannot figure out how to get those values passed into the pipe.

Inside the component I have the values being stored in a property as follows:

ngOnInit() {
  this.sub = this.search.getChangeEvent()
    .subscribe((value) => {
      this.value = value;
    }
  );
}

I cannot figure out how to pass the value into the pipe. I have tried to bind the property inside the ngFor as follows but it does not work

When I update the code as follows I get the error below:

<card-directory-search-bar></card-directory-search-bar>

{{ team.name }}

{{ team.num }}

And the subscription works well:

How can I get the updated value into the pipe?

Thanks,

Body:
You should remove the brackets and use the pipe parameter like this:

<div *ngFor="let team of teams | filterData: value">


问:
Windows batch: sleep
How do I get a Windows batch script to wait a few seconds?

sleep and wait don't seem to work (unrecognized command).

答:
```<code>timeout /t 10 /nobreak > NUL
</code>```

/t specifies the time to wait in seconds

/nobreak won't interrupt the timeout if you press a key (except CTRL-C)

> NUL will suppress the output of the command

Title: Windows batch: sleep

Body:
timeout /t 10 /nobreak > NUL

/t specifies the time to wait in seconds

/nobreak won't interrupt the timeout if you press a key (except CTRL-C)

> NUL will suppress the output of the command


问:
ruby uniq on the first two columns of two dimensional array
I have a two dimensional array with three fields in the second dimension.

Is it possible to use uniq on the first two fields of the second dimension?

I have seen array.uniq! {|c| c.first}. When I am correct, this apply uniq on the first field of the array.

Is it possible to use something like array.uniq! {|c| c.first c.second}?

@array = Array.new()

@array << Array.new([journal.from_account_number, journal.from_account,
                                journal.buchungsart])
There are several entries in @array.

The question was how to get unique values from array not considering journal.buchungsart.

The answer was: @array = @array.uniq! {|c| [c.first, c.second]}

答:
Array#first accepts a parameter :

```<code>%w(a b c d e f).first(2)
# => ["a", "b"]
</code>```

so you could just use :

```<code>array.uniq!{ |c| c.first(2) }
</code>```

Body:
Array#first accepts a parameter :

%w(a b c d e f).first(2)
# => ["a", "b"]

so you could just use :

array.uniq!{ |c| c.first(2) }


问:
Downloading data from Adwords and using Pandas to read the file
I am using Python to download some reports from Adwords and then pandas to reformat the data.

```<code>import pandas as pd
from googleads import adwords

    stream_data = downloader.DownloadReportWithAwql(
        products_query,
        'CSV', output_file,
        client_customer_id='xxxxx',
        skip_report_header=True,
        skip_report_summary=True,
        skip_column_header=False)

    data = pd.read_csv(output_file,
                       sep=',',
                       encoding='utf-8-sig',
                       header=1,
                       error_bad_lines=False,
                       warn_bad_lines=False)
    print(data)
</code>```

The file that is produced looks like this:

```<code>647972293,695588-4,enabled,enabled,1,0.00,2017-04-01,2,50.00%,0.00%,0.00,350000,0.00
647972293,794745-4,enabled,enabled,0,0.00,2017-04-01,5,0.00%,0.00%,0.00,0,0.00
647972293,695882-4,enabled,enabled,0,0.00,2017-04-01,1,0.00%,0.00%,0.00,0,0.00
647972293,798115-4,enabled,enabled,0,0.00,2017-04-01,6,0.00%,0.00%,0.00,0,0.00
647972293,649265-4,enabled,enabled,0,0.00,2017-04-01,4,0.00%,0.00%,0.00,0,0.00
647972293,265195-4,enabled,enabled,0,0.00,2017-04-01,17,0.00%,0.00%,0.00,0,0.00
647972293,115024-4,enabled,enabled,0,0.00,2017-04-01,3,0.00%,0.00%,0.00,0,0.00
647972293,660673-4,enabled,enabled,0,0.00,2017-04-01,1,0.00%,0.00%,0.00,0,0.00
</code>```

However, I am getting this error for some reason:

```<code>Traceback (most recent call last):
  File "/Users/nasiantalla/PycharmProjects/adwords_test.py", line 95, in <module>
    error_bad_lines=False)
  File "/Users/nasiantalla/Library/Python/3.6/lib/python/site-packages/pandas/io/parsers.py", line 646, in parser_f
    return _read(filepath_or_buffer, kwds)
  File "/Users/nasiantalla/Library/Python/3.6/lib/python/site-packages/pandas/io/parsers.py", line 389, in _read
    parser = TextFileReader(filepath_or_buffer, **kwds)
  File "/Users/nasiantalla/Library/Python/3.6/lib/python/site-packages/pandas/io/parsers.py", line 730, in __init__
    self._make_engine(self.engine)
  File "/Users/nasiantalla/Library/Python/3.6/lib/python/site-packages/pandas/io/parsers.py", line 923, in _make_engine
    self._engine = CParserWrapper(self.f, **self.options)
  File "/Users/nasiantalla/Library/Python/3.6/lib/python/site-packages/pandas/io/parsers.py", line 1390, in __init__
    self._reader = _parser.TextReader(src, **kwds)
  File "pandas/parser.pyx", line 535, in pandas.parser.TextReader.__cinit__ (pandas/parser.c:6086)
  File "pandas/parser.pyx", line 710, in pandas.parser.TextReader._get_header (pandas/parser.c:8843)
  File "pandas/parser.pyx", line 911, in pandas.parser.TextReader._tokenize_rows (pandas/parser.c:11308)
  File "pandas/parser.pyx", line 2014, in pandas.parser.raise_parser_error (pandas/parser.c:26862)
TypeError: raise: exception class must be a subclass of BaseException
</code>```

I tried with some different eroding types, but still the same.. any ideas?

答:
Check out:

https://github.com/pandas-dev/pandas/issues/6035

and try casting the separator as a string?

```<code>sep = str(‘,’)
</code>```

Body:
I am using Python to download some reports from Adwords and then pandas to reformat the data.

import pandas as pd
from googleads import adwords

    stream_data = downloader.DownloadReportWithAwql(
        products_query,
        'CSV', output_file,
        client_customer_id='xxxxx',
        skip_report_header=True,
        skip_report_summary=True,
        skip_column_header=False)

    data = pd.read_csv(output_file,
                       sep=',',
                       encoding='utf-8-sig',
                       header=1,
                       error_bad_lines=False,
                       warn_bad_lines=False)
    print(data)

The file that is produced looks like this:

647972293,695588-4,enabled,enabled,1,0.00,2017-04-01,2,50.00%,0.00%,0.00,350000,0.00
647972293,794745-4,enabled,enabled,0,0.00,2017-04-01,5,0.00%,0.00%,0.00,0,0.00
647972293,695882-4,enabled,enabled,0,0.00,2017-04-01,1,0.00%,0.00%,0.00,0,0.00
647972293,798115-4,enabled,enabled,0,0.00,2017-04-01,6,0.00%,0.00%,0.00,0,0.00
647972293,649265-4,enabled,enabled,0,0.00,2017-04-01,4,0.00%,0.00%,0.00,0,0.00
647972293,265195-4,enabled,enabled,0,0.00,2017-04-01,17,0.00%,0.00%,0.00,0,0.00
647972293,115024-4,enabled,enabled,0,0.00,2017-04-01,3,0.00%,0.00%,0.00,0,0.00
647972293,660673-4,enabled,enabled,0,0.00,2017-04-01,1,0.00%,0.00%,0.00,0,0.00

However, I am getting this error for some reason:

Traceback (most recent call last):
  File "/Users/nasiantalla/PycharmProjects/adwords_test.py", line 95, in <module>
    error_bad_lines=False)
  File "/Users/nasiantalla/Library/Python/3.6/lib/python/site-packages/pandas/io/parsers.py", line 646, in parser_f
    return _read(filepath_or_buffer, kwds)
  File "/Users/nasiantalla/Library/Python/3.6/lib/python/site-packages/pandas/io/parsers.py", line 389, in _read
    parser = TextFileReader(filepath_or_buffer, **kwds)
  File "/Users/nasiantalla/Library/Python/3.6/lib/python/site-packages/pandas/io/parsers.py", line 730, in __init__
    self._make_engine(self.engine)
  File "/Users/nasiantalla/Library/Python/3.6/lib/python/site-packages/pandas/io/parsers.py", line 923, in _make_engine
    self._engine = CParserWrapper(self.f, **self.options)
  File "/Users/nasiantalla/Library/Python/3.6/lib/python/site-packages/pandas/io/parsers.py", line 1390, in __init__
    self._reader = _parser.TextReader(src, **kwds)
  File "pandas/parser.pyx", line 535, in pandas.parser.TextReader.__cinit__ (pandas/parser.c:6086)
  File "pandas/parser.pyx", line 710, in pandas.parser.TextReader._get_header (pandas/parser.c:8843)
  File "pandas/parser.pyx", line 911, in pandas.parser.TextReader._tokenize_rows (pandas/parser.c:11308)
  File "pandas/parser.pyx", line 2014, in pandas.parser.raise_parser_error (pandas/parser.c:26862)
TypeError: raise: exception class must be a subclass of BaseException

I tried with some different eroding types, but still the same.. any ideas?

Body:
Check out:

https://github.com/pandas-dev/pandas/issues/6035

and try casting the separator as a string?

sep = str(‘,’)


问:
Javascript: How to get/select all object with same keys?
I have object like this:

```<code>[
  {
    "id": 1,
    "name": "App 1",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app1",
    "kat": "tkj"
  },
  {
    "id": 2,
    "name": "App 2",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app2",
    "kat": "tkj"
  },
  {
    "id": 3,
    "name": "App 3",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app3",
    "kat": "tei"
  },
  {
    "id": 4,
    "name": "App 4",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app4",
    "kat": "tei"
  },
  {
    "id": 5,
    "name": "App 5",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app5",
    "kat": "tei"
  }
]
</code>```

How i get/select all object with same keys (kat) in javascript?

example i want to get all object with kat=tkj will return:

```<code>[{
    "id": 1,
    "name": "App 1",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app1",
    "kat": "tkj"
  },
  {
    "id": 2,
    "name": "App 2",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app2",
    "kat": "tkj"
  }]
</code>```

Thanks for your help ^_^

答:
You can do this using filter function, like this:

```<code>var yourOriginalArray = [...];

var result = yourOriginalArray.filter(function(item) {
    return item.kat === "tkj";
})
</code>```

@edit

For more explanation:

Array has a built in function called filter. As a parameter you pass a function that will be called for every item (object) in your array. When the function returns true, the item is added to the result array, if it returns false, then the item is skipped.

Body:
I have object like this:

[
  {
    "id": 1,
    "name": "App 1",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app1",
    "kat": "tkj"
  },
  {
    "id": 2,
    "name": "App 2",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app2",
    "kat": "tkj"
  },
  {
    "id": 3,
    "name": "App 3",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app3",
    "kat": "tei"
  },
  {
    "id": 4,
    "name": "App 4",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app4",
    "kat": "tei"
  },
  {
    "id": 5,
    "name": "App 5",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app5",
    "kat": "tei"
  }
]

How i get/select all object with same keys (kat) in javascript?

example i want to get all object with kat=tkj will return:

[{
    "id": 1,
    "name": "App 1",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app1",
    "kat": "tkj"
  },
  {
    "id": 2,
    "name": "App 2",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app2",
    "kat": "tkj"
  }]

Thanks for your help ^_^

Body:
You can do this using filter function, like this:

var yourOriginalArray = [...];

var result = yourOriginalArray.filter(function(item) {
    return item.kat === "tkj";
})

@edit

For more explanation:

Array has a built in function called filter. As a parameter you pass a function that will be called for every item (object) in your array. When the function returns true, the item is added to the result array, if it returns false, then the item is skipped.


问:
Android: all elements displayed on top of the screen
I am new in mobile development and I am trying to run my activity and view the result of my layout with my phone/emulator.
On the design mode it looks good but when I run it on the emulator/phone all the elements are ordered one on top of another.

I have these files:

activity_item_page.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
                                             xmlns:app="http://schemas.android.com/apk/res-auto"
                                             xmlns:tools="http://schemas.android.com/tools"
                                             android:layout_width="match_parent"
                                             android:layout_height="match_parent"
                                             android:weightSum="1"
                                             android:baselineAligned="false"
                                             android:orientation="vertical"
                                             tools:layout_editor_absoluteY="81dp"
                                             tools:layout_editor_absoluteX="0dp">

    <TextView
        android:id="@+id/product_name"
        android:layout_width="343dp"
        android:layout_height="29dp"
        android:text="@string/nike_show"
        android:textSize="18sp"
        tools:ignore="MissingConstraints"
        tools:layout_editor_absoluteX="9dp"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="8dp"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/item_data_info"
        android:layout_width="344dp"
        android:layout_height="199dp"
        tools:layout_editor_absoluteX="8dp"
        tools:ignore="MissingConstraints,NotSibling"
        android:layout_marginTop="8dp"
        app:layout_constraintTop_toBottomOf="@+id/item_tab"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="8dp"/>

        <android.support.constraint.ConstraintLayout
            android:layout_width="165dp"
            android:layout_height="134dp"
            android:layout_gravity="center_vertical"
            android:scrollbars="none"
            tools:ignore="MissingConstraints,RtlHardcoded"
            android:id="@+id/constraintLayout2"
            tools:layout_editor_absoluteX="98dp"
            android:layout_marginTop="8dp"
            app:layout_constraintTop_toBottomOf="@+id/product_name"
            android:layout_marginBottom="8dp"
            app:layout_constraintBottom_toTopOf="@+id/item_tab">

            <LinearLayout
                android:id="@+id/id_gallery"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                tools:layout_editor_absoluteX="50dp"
                tools:layout_editor_absoluteY="677dp"
                android:layout_below="@id/product_name"
                tools:ignore="NotSibling,UnknownId">
            </LinearLayout>

        </android.support.constraint.ConstraintLayout>

    <android.support.constraint.ConstraintLayout
        android:layout_width="344dp"
        android:layout_height="54dp"
        android:layout_weight="0.1"
        tools:ignore="MissingConstraints,NotSibling"
        android:id="@+id/item_tab"
        android:layout_below="@+id/id_gallery"
        tools:layout_editor_absoluteY="238dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent">

        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/description"
            tools:layout_editor_absoluteX="31dp"
            tools:layout_editor_absoluteY="856dp"/>

        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/history"
            tools:layout_editor_absoluteX="165dp"
            tools:layout_editor_absoluteY="856dp"/>

        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/alerts"
            tools:layout_editor_absoluteX="288dp"
            tools:layout_editor_absoluteY="856dp"/>
    </android.support.constraint.ConstraintLayout>

</android.support.constraint.ConstraintLayout>
</code>```

ItemPageActivity.java

```<code>package com.goldbergtom.cricket;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ItemPageActivity extends AppCompatActivity {
    private LinearLayout mGallery;
    private int[] mImgIds;
    private LayoutInflater mInflater;
    private HorizontalScrollView horizontalScrollView;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_item_page);
        mInflater = LayoutInflater.from(this);
        initData();
        initView();
    }

    private void initData()
    {
        mImgIds = new int[] { R.drawable.ic_1, R.drawable.ic_2, R.drawable.ic_3,R.drawable.ic_4
        };
    }

    private void initView()
    {
        mGallery = (LinearLayout) findViewById(R.id.id_gallery);

        for (int i = 0; i < mImgIds.length; i++)
        {

            View view = mInflater.inflate(R.layout.activity_gallery_item,
                    mGallery, false);
            ImageView img = (ImageView) view
                    .findViewById(R.id.id_index_gallery_item_image);
            img.setImageResource(mImgIds[i]);
            TextView txt = (TextView) view
                    .findViewById(R.id.id_index_gallery_item_text);
            txt.setText("info "+i);
            mGallery.addView(view);
        }
    }
}
</code>```

I am also attaching images of the design and emulator.

答: I was needed to set the objects exactly to constraints rules.</p>

Body:
I am new in mobile development and I am trying to run my activity and view the result of my layout with my phone/emulator.
On the design mode it looks good but when I run it on the emulator/phone all the elements are ordered one on top of another.

I have these files:

activity_item_page.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
                                             xmlns:app="http://schemas.android.com/apk/res-auto"
                                             xmlns:tools="http://schemas.android.com/tools"
                                             android:layout_width="match_parent"
                                             android:layout_height="match_parent"
                                             android:weightSum="1"
                                             android:baselineAligned="false"
                                             android:orientation="vertical"
                                             tools:layout_editor_absoluteY="81dp"
                                             tools:layout_editor_absoluteX="0dp">

    <TextView
        android:id="@+id/product_name"
        android:layout_width="343dp"
        android:layout_height="29dp"
        android:text="@string/nike_show"
        android:textSize="18sp"
        tools:ignore="MissingConstraints"
        tools:layout_editor_absoluteX="9dp"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="8dp"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/item_data_info"
        android:layout_width="344dp"
        android:layout_height="199dp"
        tools:layout_editor_absoluteX="8dp"
        tools:ignore="MissingConstraints,NotSibling"
        android:layout_marginTop="8dp"
        app:layout_constraintTop_toBottomOf="@+id/item_tab"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="8dp"/>

        <android.support.constraint.ConstraintLayout
            android:layout_width="165dp"
            android:layout_height="134dp"
            android:layout_gravity="center_vertical"
            android:scrollbars="none"
            tools:ignore="MissingConstraints,RtlHardcoded"
            android:id="@+id/constraintLayout2"
            tools:layout_editor_absoluteX="98dp"
            android:layout_marginTop="8dp"
            app:layout_constraintTop_toBottomOf="@+id/product_name"
            android:layout_marginBottom="8dp"
            app:layout_constraintBottom_toTopOf="@+id/item_tab">

            <LinearLayout
                android:id="@+id/id_gallery"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                tools:layout_editor_absoluteX="50dp"
                tools:layout_editor_absoluteY="677dp"
                android:layout_below="@id/product_name"
                tools:ignore="NotSibling,UnknownId">
            </LinearLayout>

        </android.support.constraint.ConstraintLayout>

    <android.support.constraint.ConstraintLayout
        android:layout_width="344dp"
        android:layout_height="54dp"
        android:layout_weight="0.1"
        tools:ignore="MissingConstraints,NotSibling"
        android:id="@+id/item_tab"
        android:layout_below="@+id/id_gallery"
        tools:layout_editor_absoluteY="238dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent">

        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/description"
            tools:layout_editor_absoluteX="31dp"
            tools:layout_editor_absoluteY="856dp"/>

        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/history"
            tools:layout_editor_absoluteX="165dp"
            tools:layout_editor_absoluteY="856dp"/>

        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/alerts"
            tools:layout_editor_absoluteX="288dp"
            tools:layout_editor_absoluteY="856dp"/>
    </android.support.constraint.ConstraintLayout>

</android.support.constraint.ConstraintLayout>

ItemPageActivity.java

package com.goldbergtom.cricket;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ItemPageActivity extends AppCompatActivity {
    private LinearLayout mGallery;
    private int[] mImgIds;
    private LayoutInflater mInflater;
    private HorizontalScrollView horizontalScrollView;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_item_page);
        mInflater = LayoutInflater.from(this);
        initData();
        initView();
    }

    private void initData()
    {
        mImgIds = new int[] { R.drawable.ic_1, R.drawable.ic_2, R.drawable.ic_3,R.drawable.ic_4
        };
    }

    private void initView()
    {
        mGallery = (LinearLayout) findViewById(R.id.id_gallery);

        for (int i = 0; i < mImgIds.length; i++)
        {

            View view = mInflater.inflate(R.layout.activity_gallery_item,
                    mGallery, false);
            ImageView img = (ImageView) view
                    .findViewById(R.id.id_index_gallery_item_image);
            img.setImageResource(mImgIds[i]);
            TextView txt = (TextView) view
                    .findViewById(R.id.id_index_gallery_item_text);
            txt.setText("info "+i);
            mGallery.addView(view);
        }
    }
}

I am also attaching images of the design and emulator.


问:
Why is my PIC not blinking its leds?
I am trying to get started with pic24's, specifically the PIC24FJ64GA002, and I have looked in the datasheet at the registers and whatnot, but I still cannot get it to blink the leds. When I run it via debug it runs correctly, but when I try to actually run it on the pic it seems to not run at all.

I am using an external Oscillator, a 8MHZ Oscillator specifically, connected to pins 9(OSCI) and 10 (OSCO). Compiler is C30 in Mplab.

Datasheet link is: http://ww1.microchip.com/downloads/en/DeviceDoc/39881D.pdf

The code is below

```<code>//include basic header definition
#include <p24FJ64GA002.h>

//config
_CONFIG2(0x0200);
_CONFIG1(0x0800);

int i;

//main loop
int main(void)
{

   OSCCON = 0x2280;  //select external OSC, no PLL
   AD1PCFG      = 0xFFFF;  //set to all digital I/O
   TRISA = 0x0000;  //configure all PortA as output

   while(1)    //Loop forever
   {
  LATAbits.LATA0 = 1; //RA0 = 1
  Wait();
  LATAbits.LATA0 = 1; //RA0 = 1
  Wait();
   }

}

int Wait(void) // gives me a nice delay of 1/3rd a second or so
{
for (int i = 0; i < 30000; i++)
 {
  for (int i = 0; i < 30; i++);
    }

}
</code>```

答: What optimization level are you compiling with?  If it's only working in debug, it's possible the optimizer is reducing the whole Wait() function to a no-op.   Try declaring `volatile int i'.

ContentLicense: CC BY-SA 2.5

Title: Why is my PIC not blinking its leds?

Body:
I am trying to get started with pic24's, specifically the PIC24FJ64GA002, and I have looked in the datasheet at the registers and whatnot, but I still cannot get it to blink the leds. When I run it via debug it runs correctly, but when I try to actually run it on the pic it seems to not run at all.

I am using an external Oscillator, a 8MHZ Oscillator specifically, connected to pins 9(OSCI) and 10 (OSCO). Compiler is C30 in Mplab.

Datasheet link is: http://ww1.microchip.com/downloads/en/DeviceDoc/39881D.pdf

The code is below

//include basic header definition
#include <p24FJ64GA002.h>

//config
_CONFIG2(0x0200);
_CONFIG1(0x0800);

int i;

//main loop
int main(void)
{

   OSCCON = 0x2280;  //select external OSC, no PLL
   AD1PCFG      = 0xFFFF;  //set to all digital I/O
   TRISA = 0x0000;  //configure all PortA as output

   while(1)    //Loop forever
   {
  LATAbits.LATA0 = 1; //RA0 = 1
  Wait();
  LATAbits.LATA0 = 1; //RA0 = 1
  Wait();
   }

}

int Wait(void) // gives me a nice delay of 1/3rd a second or so
{
for (int i = 0; i < 30000; i++)
 {
  for (int i = 0; i < 30; i++);
    }

}


问:
How to return a struct with a generic type that implements the `Read` and `Write` traits?
I am trying to wrap a TcpStream and TlsStream in one object so that I can interface with either of them using one struct. I am trying to delegate the io methods to one or the other based on a config value but can't figure out how to return a struct with a generic type that implements the Read and Write traits

My code is as follows

```<code>pub struct TcpStream<T: Read + Write> {
    io_delegate: T,
    config: Config,
}

impl<T> TcpStream<T>
    where T: Read + Write
{
    pub fn connect<A: ToSocketAddrs>(config: Config, addr: A) -> io::Result<TcpStream<T>> {
        let tcp_stream = net::TcpStream::connect(addr).unwrap();
        if config.ssl {
            let tls_stream = TlsConnector::builder()
                .unwrap()
                .build()
                .unwrap()
                .connect("rem", tcp_stream)
                .unwrap();
            return Ok(TcpStream {
                          config: config,
                          io_delegate: tls_stream,
                      });
        }
        return Ok(TcpStream {
                      config: config,
                      io_delegate: tcp_stream,
                  });
    }
}
</code>```

When I try to compile I get the following errors

error[E0308]: mismatched types
  --> src/rem/tcp_stream.rs:19:23
   |
19 |               return Ok(TcpStream {
   |  _______________________^ starting here...
20 | |                 config: config,
21 | |                 io_delegate: tls_stream
22 | |             });
   | |_____________^ ...ending here: expected type parameter, found struct `native_tls::TlsStream`
   |
   = note: expected type `rem::tcp_stream::TcpStream<T>`
              found type `rem::tcp_stream::TcpStream<native_tls::TlsStream<std::net::TcpStream>>`

error[E0308]: mismatched types
  --> src/rem/tcp_stream.rs:24:19
   |
24 |           return Ok(TcpStream{
   |  ___________________^ starting here...
25 | |                 config: config,
26 | |                 io_delegate: tcp_stream
27 | |         });
   | |_________^ ...ending here: expected type parameter, found struct `std::net::TcpStream`
   |
   = note: expected type `rem::tcp_stream::TcpStream<T>`
              found type `rem::tcp_stream::TcpStream<std::net::TcpStream>`
```

Is there a way to achieve this sort of thing?

答:
I'm not sure if this is the best solution but it does seem to work.

I created a new trait which is a combination of Read + Write then just stored it as a Box in my struct

```<code>trait ReadWrite : Read + Write {}

impl<T: Read + Write> ReadWrite for T {}

pub struct TcpStream{
    io_delegate : Box<ReadWrite>,
    config: Config
}

impl TcpStream {

    pub fn connect<A: ToSocketAddrs>(config: Config, addr: A) -> TcpStream {
        let tcp_stream = net::TcpStream::connect(addr).unwrap();
        if config.ssl {
            let tls_stream = TlsConnector::builder().unwrap().build().unwrap().connect("rem", tcp_stream).unwrap();
            return TcpStream {
                config: config,
                io_delegate: Box::new(tls_stream)
            };
        }
        return TcpStream{
                config: config,
                io_delegate:Box::new(tcp_stream)
        };
    }
}
</code>```

Body:
I am trying to wrap a TcpStream and TlsStream in one object so that I can interface with either of them using one struct. I am trying to delegate the io methods to one or the other based on a config value but can't figure out how to return a struct with a generic type that implements the Read and Write traits

My code is as follows

pub struct TcpStream<T: Read + Write> {
    io_delegate: T,
    config: Config,
}

impl<T> TcpStream<T>
    where T: Read + Write
{
    pub fn connect(config: Config, addr: A) -> io::Result<TcpStream<T>> {
        let tcp_stream = net::TcpStream::connect(addr).unwrap();
        if config.ssl {
            let tls_stream = TlsConnector::builder()
                .unwrap()
                .build()
                .unwrap()
                .connect("rem", tcp_stream)
                .unwrap();
            return Ok(TcpStream {
                          config: config,
                          io_delegate: tls_stream,
                      });
        }
        return Ok(TcpStream {
                      config: config,
                      io_delegate: tcp_stream,
                  });
    }
}

When I try to compile I get the following errors

error[E0308]: mismatched types
  --> src/rem/tcp_stream.rs:19:23
   |
19 |               return Ok(TcpStream {
   |  _______________________^ starting here...
20 | |                 config: config,
21 | |                 io_delegate: tls_stream
22 | |             });
   | |_____________^ ...ending here: expected type parameter, found struct `native_tls::TlsStream`
   |
   = note: expected type `rem::tcp_stream::TcpStream<T>`
              found type `rem::tcp_stream::TcpStream<native_tls::TlsStream<std::net::TcpStream>>`

error[E0308]: mismatched types
  --> src/rem/tcp_stream.rs:24:19
   |
24 |           return Ok(TcpStream{
   |  ___________________^ starting here...
25 | |                 config: config,
26 | |                 io_delegate: tcp_stream
27 | |         });
   | |_________^ ...ending here: expected type parameter, found struct `std::net::TcpStream`
   |
   = note: expected type `rem::tcp_stream::TcpStream<T>`
              found type `rem::tcp_stream::TcpStream<std::net::TcpStream>`

Is there a way to achieve this sort of thing?

Body:
I'm not sure if this is the best solution but it does seem to work.

I created a new trait which is a combination of Read + Write then just stored it as a Box in my struct

trait ReadWrite : Read + Write {}

impl<T: Read + Write> ReadWrite for T {}

pub struct TcpStream{
    io_delegate : Box<ReadWrite>,
    config: Config
}

impl TcpStream {

    pub fn connect<A: ToSocketAddrs>(config: Config, addr: A) -> TcpStream {
        let tcp_stream = net::TcpStream::connect(addr).unwrap();
        if config.ssl {
            let tls_stream = TlsConnector::builder().unwrap().build().unwrap().connect("rem", tcp_stream).unwrap();
            return TcpStream {
                config: config,
                io_delegate: Box::new(tls_stream)
            };
        }
        return TcpStream{
                config: config,
                io_delegate:Box::new(tcp_stream)
        };
    }
}


问:
Plotting mean as dashed line on histogram with matplotlib
I have a histogram created from a pandas dataframe that I would like to plot a vertical dashed line representing the mean of the dataset. I have reviewed this thread, which is exactly the style I am looking for, however, I cannot figure out how to make it work with my code (below):

```<code>import pandas as pd
import matplotlib.pyplot as plt

#import csv file into pandas dataframe
df = pd.read_csv('/path/to/my/file')

#calculating mean
m = df.mean()
#print(m)

#plotting histogram
df.plot(kind='hist')
#plt.axvline(m, color = 'r', linestyle = 'dashed', linewidth = 2)
</code>```

I end up receiving this error:

```<code> ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
</code>```

Not sure what that means, any help would be appreciated.

EDIT: My datafile is a csv with one column, first row is a header (string) and all subsequent 107 rows are values ranging from app. 1.0E+11 to 4.0E+11

Fake data (Python 2.7)

```<code>import io
import numpy as np
a = np.linspace(1, 4, num = 20)
s = 'E11\n'.join(map(str, a))
s += 'E11'
#print(s)
df = pd.read_csv(io.BytesIO(s))
</code>```

答:
m is a Pandas Series, it has an index and a value - Matplotlib must not know how to handle it.

```<code>>>> print m
1.0E11    2.578947e+11
dtype: float64
>>> type(m)
<class 'pandas.core.series.Series'>
>>>
</code>```

The value of the mean is m[0] or m.values, so:

```<code>plt.axvline(m[0], color = 'r', linestyle = 'dashed', linewidth = 2)
#or
plt.axvline(m.values, color = 'r', linestyle = 'dashed', linewidth = 4)
</code>```

Body:
I have a histogram created from a pandas dataframe that I would like to plot a vertical dashed line representing the mean of the dataset. I have reviewed this thread, which is exactly the style I am looking for, however, I cannot figure out how to make it work with my code (below):

import pandas as pd
import matplotlib.pyplot as plt

#import csv file into pandas dataframe
df = pd.read_csv('/path/to/my/file')

#calculating mean
m = df.mean()
#print(m)

#plotting histogram
df.plot(kind='hist')
#plt.axvline(m, color = 'r', linestyle = 'dashed', linewidth = 2)

I end up receiving this error:

 ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Not sure what that means, any help would be appreciated.

EDIT: My datafile is a csv with one column, first row is a header (string) and all subsequent 107 rows are values ranging from app. 1.0E+11 to 4.0E+11

Fake data (Python 2.7)

import io
import numpy as np
a = np.linspace(1, 4, num = 20)
s = 'E11\n'.join(map(str, a))
s += 'E11'
#print(s)
df = pd.read_csv(io.BytesIO(s))

Body:
m is a Pandas Series, it has an index and a value - Matplotlib must not know how to handle it.

>>> print m
1.0E11    2.578947e+11
dtype: float64
>>> type(m)
<class 'pandas.core.series.Series'>
>>>

The value of the mean is m[0] or m.values, so:

plt.axvline(m[0], color = 'r', linestyle = 'dashed', linewidth = 2)
#or
plt.axvline(m.values, color = 'r', linestyle = 'dashed', linewidth = 4)


问:
unhighlight the row background when another row is clicked
I am using jQuery-contextMenu. I am trying to highlight the row background on left or right click.

```<code>$('body').on('mousedown', 'tr', function() {
   $(this).css('backgroundColor', '#000');
});
</code>```

Somehow the contextMenu is making it unstable. Could you please suggest me how can I triger the background Color before contextMenu?
PLease see the jsfiddle below to have a better idea. I also need to unhighlight the previous row background when another row is clicked.

http://jsfiddle.net/0f9Ljfjr/904/

答:
Basically normal mouse events are triggered on both left and right click but if you're looking for the right click event.

```<code>$("body").on("contextmenu", "tr", function(event){
 .
 .
 .
});
</code>```

In your case mousedown is enough to listen to both left and right clicks

```<code>$("body").on("mousedown", "tr", function(event){
  $(this).siblings(".active").removeClass("active");
  $(this).addClass("active");
});
</code>```

And a little bit of CSS

```<code>table.dataTable tbody tr.active {
  background-color: #000;
}
</code>```

Body:
I am using jQuery-contextMenu. I am trying to highlight the row background on left or right click.

$('body').on('mousedown', 'tr', function() {
   $(this).css('backgroundColor', '#000');
});

Somehow the contextMenu is making it unstable. Could you please suggest me how can I triger the background Color before contextMenu?
PLease see the jsfiddle below to have a better idea. I also need to unhighlight the previous row background when another row is clicked.

http://jsfiddle.net/0f9Ljfjr/904/

Body:
Basically normal mouse events are triggered on both left and right click but if you're looking for the right click event.

$("body").on("contextmenu", "tr", function(event){
 .
 .
 .
});

In your case mousedown is enough to listen to both left and right clicks

$("body").on("mousedown", "tr", function(event){
  $(this).siblings(".active").removeClass("active");
  $(this).addClass("active");
});

And a little bit of CSS

table.dataTable tbody tr.active {
  background-color: #000;
}


问:
Calculator on JavaScript(simple)
In the text field, you need to specify the values and count them by the button. I do not understand why not think so? You need to implement it in principle through a switch but I can not understand why operations are not counted: +, -, *, /</p>

```<code><p>
  <label for="text1">FirstNum</label>
  <input type="text" id="text1"><br>
  <label for="operation">Operation</label>
  <input type="text" id="operation"><br>
  <label for="text2">SecondNum</label>
  <input type="text" id="text2"><br>
  <label for="text3">Result</label>
  <input type="text" id="text3"><br><br>
  <input type="button" value="ClickResult" onclick="Calc()">
</p>

<script>

  function Calc(operation) {
    //var op;
    switch(operation) {
      case '+':
        text3.value = text1.value + text2.value;
        break;
      case '-':
        text3.value = text1.value - text2.value;
        break;
      case '/':
        text3.value = text1.value / text2.value;
        break;
      case '*':
        text3.value = text1.value * text2.value;
        break;
    }
 }

</script>
</code>```

答:
You need to get the values of textbox like so:

```<code>   var text1 = document.getElementById('text1').value;
</code>```

But the value you get is in string format, so you need to convert it into int or float so you have to typecast it into int or float like so:

```<code>   text1 = parseFloat(text1);
</code>```

and then give out the value in the result box like so:

```<code>document.getElementById('text3').value = result of the calculation
</code>```

or another way is:

```<code>var result = document.getElementById('text3');
result.value = result of computation
</code>```

  FirstNum
  <input type="text" id="text1">

  Operation
  <input type="text" id="operation">

  SecondNum
  <input type="text" id="text2">

  Result
  <input type="text" id="text3">

  <input type="button" value="ClickResult" onclick="Calc()">

```

Title: Calculator on JavaScript(simple)

Body:
In the text field, you need to specify the values and count them by the button. I do not understand why not think so? You need to implement it in principle through a switch but I can not understand why operations are not counted: +, -, *, /

  FirstNum
  <input type="text" id="text1">

  Operation
  <input type="text" id="operation">

  SecondNum
  <input type="text" id="text2">

  Result
  <input type="text" id="text3">

  <input type="button" value="ClickResult" onclick="Calc()">

Body:
You need to get the values of textbox like so:

   var text1 = document.getElementById('text1').value;

But the value you get is in string format, so you need to convert it into int or float so you have to typecast it into int or float like so:

   text1 = parseFloat(text1);

and then give out the value in the result box like so:

document.getElementById('text3').value = result of the calculation

or another way is:

var result = document.getElementById('text3');
result.value = result of computation

<p>
  <label for="text1">FirstNum</label>
  <input type="text" id="text1"><br>
  <label for="operation">Operation</label>
  <input type="text" id="operation"><br>
  <label for="text2">SecondNum</label>
  <input type="text" id="text2"><br>
  <label for="text3">Result</label>
  <input type="text" id="text3"><br><br>
  <input type="button" value="ClickResult" onclick="Calc()">
</p>

<script>

  function Calc() {
    var text1 = document.getElementById('text1').value;
    var text2 = document.getElementById('text2').value;
    var operation = document.getElementById('operation').value;
    var text3 = document.getElementById('text3');
    text1 = parseFloat(text1);
    text2 = parseFloat(text2);
    //var op;
    switch(operation) {
      case '+':
        text3.value = text1 + text2;
        break;
      case '-':
        text3.value = text1 - text2;
        break;
      case '/':
        text3.value = text1 / text2;
        break;
      case '*':
        text3.value = text1 * text2;
        break;
    }

  }

</script>


问:
What separates a content management system from just a bunch of web pages?
I have a website that has related pages.  They have links that point back and forth to one another but I have no integrated system, nor do I know what that would mean.

What is the minimum code that a group of web pages must have to be considered a Content Management System (CMS).  Is it that all the settings are in the database and the pages are generated somehow?  Is there some small snippet that all my pages could share that makes them a CMS, database or not?

Thanks.  I was also hoping not to have to study a giant CMS to see what makes it a CMS .  After maybe a basic understanding I would know what I was looking for.

edit:  here's why I ask about code.  Whenever I have looked at a CMS, and maybe they aren't all the same, I saw that to develop a module you always had to inherit from certain classes and had some necessary code.  I didn't know if there was some magic model that I just don't get that all cms makers understand.

edit:  perhaps my question is more about being extendable or pluggable.  What would a minimum look like?  Is it possible to show that here?

edit:  how about this?  Is something a CMS if it is not extendable and/or pluggable?

答:
I think this is really impossible to say.  We all manage content.  The "system" is just whatever mechanism you use to do so(dragging and dropping in Explorer or committing content changes via a SQL query).  To say there is a minimum amount of code needed really isn't indicative.  What is indicative is how often you find yourself making mistakes and how easy it is for a given user of a given skill level and knowledge to execute the functions in the designed system.  That tells you the quality/degree of what you have in place being worthy of being called a "CMS."

Simply put a CMS is an application that allows the user to publish and edit existing web content.

In response to the edit:

A "good" CMS allows of extensibility.  By using inheritence you can extend the functionality of a CMS outside of the core components provided.  That's the magic.

About Extensibility:

Depending on the language/framework you want to build your CMS with, you can load pages or controls(ASP.NET) using command built into the framework.  Typically what is being done is a parent class/interface is being defined that forces an module that is to be developed to follow some given standards:

```<code>Public MustInherit Class CMSModule

'Here you will define properties and functions that need to be global to all modules being developed to extend your CMS.

    public property ModuleName as string
End Class

public class PlugInFooCMSPage
   inherits CMSModule

end class
</code>```

Then it's just a matter of simply loading a module dynamically in whatever construct a given language/framework provides.

Body:
I think this is really impossible to say.  We all manage content.  The "system" is just whatever mechanism you use to do so(dragging and dropping in Explorer or committing content changes via a SQL query).  To say there is a minimum amount of code needed really isn't indicative.  What is indicative is how often you find yourself making mistakes and how easy it is for a given user of a given skill level and knowledge to execute the functions in the designed system.  That tells you the quality/degree of what you have in place being worthy of being called a "CMS."

Simply put a CMS is an application that allows the user to publish and edit existing web content.

In response to the edit:

A "good" CMS allows of extensibility.  By using inheritence you can extend the functionality of a CMS outside of the core components provided.  That's the magic.

About Extensibility:

Depending on the language/framework you want to build your CMS with, you can load pages or controls(ASP.NET) using command built into the framework.  Typically what is being done is a parent class/interface is being defined that forces an module that is to be developed to follow some given standards:

Public MustInherit Class CMSModule

'Here you will define properties and functions that need to be global to all modules being developed to extend your CMS.

    public property ModuleName as string
End Class

public class PlugInFooCMSPage
   inherits CMSModule

end class

Then it's just a matter of simply loading a module dynamically in whatever construct a given language/framework provides.


问:
read subprocess stdout line by line
My python script uses subprocess to call a linux utility that is very noisy.  I want to store all of the output to a log file and show some of it to the user.  I thought the following would work, but the output doesn't show up in my application until the utility has produced a significant amount of output.

```<code>#fake_utility.py, just generates lots of output over time
import time
i = 0
while True:
   print hex(i)*512
   i += 1
   time.sleep(0.5)

#filters output
import subprocess
proc = subprocess.Popen(['python','fake_utility.py'],stdout=subprocess.PIPE)
for line in proc.stdout:
   #the real code does filtering here
   print "test:", line.rstrip()
</code>```

The behavior I really want is for the filter script to print each line as it is received from the subprocess.  Sorta like what tee does but with python code.

What am I missing?  Is this even possible?

Update:

If a sys.stdout.flush() is added to fake_utility.py, the code has the desired behavior in python 3.1.  I'm using python 2.6.  You would think that using proc.stdout.xreadlines() would work the same as py3k, but it doesn't.

Update 2:

Here is the minimal working code.

```<code>#fake_utility.py, just generates lots of output over time
import sys, time
for i in range(10):
   print i
   sys.stdout.flush()
   time.sleep(0.5)

#display out put line by line
import subprocess
proc = subprocess.Popen(['python','fake_utility.py'],stdout=subprocess.PIPE)
#works in python 3.0+
#for line in proc.stdout:
for line in iter(proc.stdout.readline,''):
   print line.rstrip()
</code>```

答:
The following modification of Rômulo's answer works for me on Python 2 and 3 (2.7.12 and 3.6.1):

import os
import subprocess

process = subprocess.Popen(command, stdout=subprocess.PIPE)
while True:
  line = process.stdout.readline()
  if line != '':
    os.write(1, line)
  else:
    break
```

Title: read subprocess stdout line by line

Body:
My python script uses subprocess to call a linux utility that is very noisy.  I want to store all of the output to a log file and show some of it to the user.  I thought the following would work, but the output doesn't show up in my application until the utility has produced a significant amount of output.

#fake_utility.py, just generates lots of output over time
import time
i = 0
while True:
   print hex(i)*512
   i += 1
   time.sleep(0.5)

#filters output
import subprocess
proc = subprocess.Popen(['python','fake_utility.py'],stdout=subprocess.PIPE)
for line in proc.stdout:
   #the real code does filtering here
   print "test:", line.rstrip()

The behavior I really want is for the filter script to print each line as it is received from the subprocess.  Sorta like what tee does but with python code.

What am I missing?  Is this even possible?

Update:

If a sys.stdout.flush() is added to fake_utility.py, the code has the desired behavior in python 3.1.  I'm using python 2.6.  You would think that using proc.stdout.xreadlines() would work the same as py3k, but it doesn't.

Update 2:

Here is the minimal working code.

#fake_utility.py, just generates lots of output over time
import sys, time
for i in range(10):
   print i
   sys.stdout.flush()
   time.sleep(0.5)

#display out put line by line
import subprocess
proc = subprocess.Popen(['python','fake_utility.py'],stdout=subprocess.PIPE)
#works in python 3.0+
#for line in proc.stdout:
for line in iter(proc.stdout.readline,''):
   print line.rstrip()


问:
Why is the first argument of reduce() returning undefined?
I'm trying to write a function that takes in an array as an input. If the integer is positive, it counts it. If the integer is negative, it sums it.

I figured that that the reduce() helper in js would be the best way to go about this, but I keep returning undefined for my first argument when it runs.

Here's my code:

```<code>function countPositivesSumNegatives(input) {
    let countPositive = 0;
    let sumNegative = 0

    if (input === null || input === []){
      return [];
    } else {
      return input.reduce(function(prev,num){
      if (num > 0) {
      countPositive++;
      }else{
      sumNegative = prev + num};
      }, 0);
    }
    return [countPositive, sumNegative];
}
</code>```

It throws me a TypeError that says:

TypeError: Cannot read property '0' of undefined

When I log 'prev' to the console inside of the reduce function, it logs undefined for all inputs except the first one. The first one, as expected, is 0. But for each following input it logs undefined. Why is this happening?

Thanks in advance.

答:
The callback you pass to .reduce() needs to return the cumulative value (the value that will be passed as prev to the next iteration of the loop.  Since you are returning nothing, you get undefined for the next iteration of your loop.

This complicates what you're trying to do because you are trying to keep track of two values in your loop.  As such, you would either have to avoid using prev at all or you'd have to make it be a data structure that had both your values in it.  Your use is not a textbook example for .reduce().  Your code is probably simpler with an iteration using .forEach() or for/of.

```<code>function countPositivesSumNegatives(input) {
    let countPositive = 0;
    let sumNegative = 0

    if (!input || input.length === 0){
      return [];
    } else {
      input.forEach(function(num){
        if (num > 0) {
          ++countPositive;
        } else {
          sumNegative += num;
      });
    }
    return [countPositive, sumNegative];
}
</code>```

Body:
I'm trying to write a function that takes in an array as an input. If the integer is positive, it counts it. If the integer is negative, it sums it.

I figured that that the reduce() helper in js would be the best way to go about this, but I keep returning undefined for my first argument when it runs.

Here's my code:

function countPositivesSumNegatives(input) {
    let countPositive = 0;
    let sumNegative = 0

    if (input === null || input === []){
      return [];
    } else {
      return input.reduce(function(prev,num){
      if (num > 0) {
      countPositive++;
      }else{
      sumNegative = prev + num};
      }, 0);
    }
    return [countPositive, sumNegative];
}

It throws me a TypeError that says:

TypeError: Cannot read property '0' of undefined

When I log 'prev' to the console inside of the reduce function, it logs undefined for all inputs except the first one. The first one, as expected, is 0. But for each following input it logs undefined. Why is this happening?

Thanks in advance.

Body:
The callback you pass to .reduce() needs to return the cumulative value (the value that will be passed as prev to the next iteration of the loop.  Since you are returning nothing, you get undefined for the next iteration of your loop.

This complicates what you're trying to do because you are trying to keep track of two values in your loop.  As such, you would either have to avoid using prev at all or you'd have to make it be a data structure that had both your values in it.  Your use is not a textbook example for .reduce().  Your code is probably simpler with an iteration using .forEach() or for/of.

function countPositivesSumNegatives(input) {
    let countPositive = 0;
    let sumNegative = 0

    if (!input || input.length === 0){
      return [];
    } else {
      input.forEach(function(num){
        if (num > 0) {
          ++countPositive;
        } else {
          sumNegative += num;
      });
    }
    return [countPositive, sumNegative];
}


问:
Reading a file using Scanner
I'm having some trouble understanding how Java uses Scanner to read lines from a file and was hoping to get some clarification after days of confusion.

I have a .txt file with one line that contains a name and then 5 doubles. I'm trying to figure out how I can assign each of those to a variable inside a loop so I can work with the data. My goal is to actually take the data from these lines and pass them as parameters to another method for validation, so if there's an easier way to do that, I'm all ears. I feel like I can't find a way to just iterate over each thing inside the nextLine, just over the entire line itself. I'm trying to do this without using an array, here's the relevant code snippet I have right now.

```<code>Scanner inputFile = new Scanner(file);

while (inputFile.hasNext())
    {
        String line = "";
        accumulator++;
        Scanner split = new Scanner(inputFile.nextLine());

       while (split.hasNext())
       {

       }

        stockName = inputFile.next();
        shares = inputFile.nextDouble();
        purchasePrice = inputFile.nextDouble();
        purchaseCommission = inputFile.nextDouble();
        salesPrice = inputFile.nextDouble();
        salesCommission = inputFile.nextDouble();

        System.out.println(stockName);
        System.out.println(shares);
        System.out.println(purchasePrice);
        System.out.println(purchaseCommission);
        System.out.println(salesPrice);
        System.out.println(salesCommission);

        System.out.print(line);
        System.out.println("");
        // checkValidity(line);
    }
</code>```

I'm having a hard time asking and articulating what I don't know, so any and all help is greatly appreciated... I've literally been working on this for three days and I'm at a total wall.

EDIT:

The layout of the text file looks like this

```<code>DELL: Dell Inc
125 25.567  0.025   28.735  0.025
MSFT: Microsoft
34.1    -15.75  0.012   15.90   0.013
</code>```

答:
You are almost there. You need to just remove the line:

```<code>while (split.hasNext())
{

}
</code>```

This consumes all the elements given to split. You need to assign this to all the elements like stock, salesPrice etc.

So, the new snippet inside the outer while loop is

```<code>    stockName = inputFile.nextLine();
    Scanner split = new Scanner(inputFile.nextLine());

    shares = split.nextDouble();
    purchasePrice = split.nextDouble();
    purchaseCommission = split.nextDouble();
    salesPrice = split.nextDouble();
    salesCommission = split.nextDouble();
</code>```

Since, you are reading line by line, also make sure the outer while loop looks like:

```<code>while (inputFile.hasNextLine()) {

}
</code>```

Title: Reading a file using Scanner

Body:
I'm having some trouble understanding how Java uses Scanner to read lines from a file and was hoping to get some clarification after days of confusion.

I have a .txt file with one line that contains a name and then 5 doubles. I'm trying to figure out how I can assign each of those to a variable inside a loop so I can work with the data. My goal is to actually take the data from these lines and pass them as parameters to another method for validation, so if there's an easier way to do that, I'm all ears. I feel like I can't find a way to just iterate over each thing inside the nextLine, just over the entire line itself. I'm trying to do this without using an array, here's the relevant code snippet I have right now.

Scanner inputFile = new Scanner(file);

while (inputFile.hasNext())
    {
        String line = "";
        accumulator++;
        Scanner split = new Scanner(inputFile.nextLine());

       while (split.hasNext())
       {

       }

        stockName = inputFile.next();
        shares = inputFile.nextDouble();
        purchasePrice = inputFile.nextDouble();
        purchaseCommission = inputFile.nextDouble();
        salesPrice = inputFile.nextDouble();
        salesCommission = inputFile.nextDouble();

        System.out.println(stockName);
        System.out.println(shares);
        System.out.println(purchasePrice);
        System.out.println(purchaseCommission);
        System.out.println(salesPrice);
        System.out.println(salesCommission);

        System.out.print(line);
        System.out.println("");
        // checkValidity(line);
    }

I'm having a hard time asking and articulating what I don't know, so any and all help is greatly appreciated... I've literally been working on this for three days and I'm at a total wall.

EDIT:

The layout of the text file looks like this

DELL: Dell Inc
125 25.567  0.025   28.735  0.025
MSFT: Microsoft
34.1    -15.75  0.012   15.90   0.013

Body:
You are almost there. You need to just remove the line:

while (split.hasNext())
{

}

This consumes all the elements given to split. You need to assign this to all the elements like stock, salesPrice etc.

So, the new snippet inside the outer while loop is

    stockName = inputFile.nextLine();
    Scanner split = new Scanner(inputFile.nextLine());

    shares = split.nextDouble();
    purchasePrice = split.nextDouble();
    purchaseCommission = split.nextDouble();
    salesPrice = split.nextDouble();
    salesCommission = split.nextDouble();

Since, you are reading line by line, also make sure the outer while loop looks like:

while (inputFile.hasNextLine()) {

}


问:
Limiting scrolling to DIV
This has been an annoyance I've come across a few times so I thought it best to see if there is a good way around it.  I have many instances of "scrollable" DIV elements in various places which work almost exactly as intended, with the exception of when a Mouse wheel or track pad is what is controlling the scroll.

The main issue is that once the div reaches the bottom of its scroll bar the command is then transferred over to the main scroll bar, annoyingly changing the users page position.  I notice that the same thing happens with the "Questions that may already have your answer" box at the top of this page, so too does the box that I'm currently typing in which makes me think it is something that happens as standard, however I'm sure I have used web sites in the past that have required me to move my cursor outside of an element in order to scroll the main page.

Is there a way to overcome this?  I'm happy to use Javascript if that is the best solution, my initial thoughts were that some kind of onmouseover command could lock the screen until a onmouseout occurred but my JS is very limited and I couldn't find anything similar to adapt.

An example of a DIV element that I'm using is:

```<code><div id='bodytext'
style='width:300px; height:300px; z-index:4; visibility: visible; overflow: auto;'>
Data more than 300px high
</div>
</code>```

Thanks in advance for any help, and if it's not possible then clarification would still be very helpful!

答:
You can listen to wheel events on the scrollable target element and prevent the default behavior only if the 'end of the scroll' has been reached.

```<code>var el = document.getElementById("Element");
var wrapper = document.getElementById("Wrapper");
wrapper.addEventListener("wheel", wheelEvent);

function wheelEvent(e){
  var space = (wrapper.scrollHeight - wrapper.offsetHeight) - wrapper.scrollTop;
    if(e.deltaY < 0){
    if(wrapper.scrollTop == 0){
      e.preventDefault();
      e.stopPropagation();
    }
  }else if(space <= 0){
    e.preventDefault();
    e.stopPropagation();
  }
}
</code>```

Here is a working example:
https://jsfiddle.net/rivieremanuel/rcxa6csr/4/

Title: Limiting scrolling to DIV

Body:
This has been an annoyance I've come across a few times so I thought it best to see if there is a good way around it.  I have many instances of "scrollable" DIV elements in various places which work almost exactly as intended, with the exception of when a Mouse wheel or track pad is what is controlling the scroll.

The main issue is that once the div reaches the bottom of its scroll bar the command is then transferred over to the main scroll bar, annoyingly changing the users page position.  I notice that the same thing happens with the "Questions that may already have your answer" box at the top of this page, so too does the box that I'm currently typing in which makes me think it is something that happens as standard, however I'm sure I have used web sites in the past that have required me to move my cursor outside of an element in order to scroll the main page.

Is there a way to overcome this?  I'm happy to use Javascript if that is the best solution, my initial thoughts were that some kind of onmouseover command could lock the screen until a onmouseout occurred but my JS is very limited and I couldn't find anything similar to adapt.

An example of a DIV element that I'm using is:

Data more than 300px high

Thanks in advance for any help, and if it's not possible then clarification would still be very helpful!

Body:
You can listen to wheel events on the scrollable target element and prevent the default behavior only if the 'end of the scroll' has been reached.

var el = document.getElementById("Element");
var wrapper = document.getElementById("Wrapper");
wrapper.addEventListener("wheel", wheelEvent);

function wheelEvent(e){
  var space = (wrapper.scrollHeight - wrapper.offsetHeight) - wrapper.scrollTop;
    if(e.deltaY < 0){
    if(wrapper.scrollTop == 0){
      e.preventDefault();
      e.stopPropagation();
    }
  }else if(space <= 0){
    e.preventDefault();
    e.stopPropagation();
  }
}

Here is a working example:
https://jsfiddle.net/rivieremanuel/rcxa6csr/4/


问:
Regex not working with accented characters in Datatables plugin
I'm trying to implement Datatables search with regex.

It works fine if I search for "lu..a" (returns Lucia, Luzia, LUZIA, etc), but not works if I try for "concei..o" (looking for Conceição, conceicao, etc).

The problem is with accented characters such "ç" or "ã" (pt_BR) in database.

I already try the accent-neutralise plugin, but it makes the inverse effect  (https://datatables.net/plug-ins/filtering/type-based/accent-neutralise)

In the table initialization there is a lot of options that I'm omitting here (buttons, translate, etc), but one important detail is this tablet is retrieving data from server-side.

Here is the search code:

Source: https://datatables.net/examples/api/multi_filter.html

// Setup - add a text input to each footer cell
$('.exportTable tfoot th.select-filter').each(function() {
  var title = $(this).text();
  $(this).html('
' +
    '
' +
    '<input class="form-control" placeholder="' + title + '" title="Filtrar ' + title + '" type="text" style="width: 100%">' +
    '
' +
    '
');
});

table = $('.exportTable').DataTable();

// Apply the search
table.columns().every(function() {
  var that = this;
  $('input', this.footer()).on('keyup change', function() {
    if (that.search() !== this.value) {
      that
        .search(this.value, true, false, true)
        .draw();
    }
  });
});
```

答:
You just need a more complete table of diacritics. I do not claim the mentioned table is complete, but far the best I know. Include the script and

```<code>jQuery.fn.DataTable.ext.type.search.string = function (s) {
    return removeDiacritics(s)
};
</code>```

demo with Conceição -> https://jsfiddle.net/s2yo99de/

Update: The above solution is now included as part of the official DataTables plugins

Sorting -> https://datatables.net/plug-ins/sorting/diacritics-sort

Filtering -> https://datatables.net/plug-ins/filtering/type-based/diacritics-neutralise

Body:
You just need a more complete table of diacritics. I do not claim the mentioned table is complete, but far the best I know. Include the script and

jQuery.fn.DataTable.ext.type.search.string = function (s) {
    return removeDiacritics(s)
};

demo with Conceição -> https://jsfiddle.net/s2yo99de/

Update: The above solution is now included as part of the official DataTables plugins

Sorting -> https://datatables.net/plug-ins/sorting/diacritics-sort

Filtering -> https://datatables.net/plug-ins/filtering/type-based/diacritics-neutralise


问:
How do I find @types for my chrome extension code in typescript?
I am trying to migrate my Chrome extension to TypeScript and have a big number of errors related to lack of @types. I think if someone sheds light on how to solve one, most of them will get solved.

So I have this generic error handler:

```<code>export function fsErrorHandler(e) {
  var msg = '';

  switch (e.code) {
    case FileError.QUOTA_EXCEEDED_ERR:
      msg = 'QUOTA_EXCEEDED_ERR';
      break;
    case FileError.NOT_FOUND_ERR:
      msg = 'NOT_FOUND_ERR';
      break;
    case FileError.SECURITY_ERR:
      msg = 'SECURITY_ERR';
      break;
    case FileError.INVALID_MODIFICATION_ERR:
      msg = 'INVALID_MODIFICATION_ERR';
      break;
    case FileError.INVALID_STATE_ERR:
      msg = 'INVALID_STATE_ERR';
      break;
    default:
      msg = 'Unknown Error';
      break;
  }
}
</code>```

which of course complains about FileError.

These are my @types already in place:

```<code>chrome
filesystem
filewriter
jquery
</code>```

As much as I understood from the HTML5 FileSystem API book, the FileError is part of File API, so with @types/filesystem in place, it should be recognized by WebStorm... What am I missing?

Another missing type is navigator, but I found info that it has been merged to lib.d.ts so it should be recognized as well.

答:
According to this link https://developer.mozilla.org/en-US/docs/Web/API/FileError FileError is a obsolete feature. That is why you are not found this on types definitions.

Try change your code to use the new DOM4 DOMError interface: https://developer.mozilla.org/en-US/docs/Web/API/DOMError

Body:
I am trying to migrate my Chrome extension to TypeScript and have a big number of errors related to lack of @types. I think if someone sheds light on how to solve one, most of them will get solved.

So I have this generic error handler:

export function fsErrorHandler(e) {
  var msg = '';

  switch (e.code) {
    case FileError.QUOTA_EXCEEDED_ERR:
      msg = 'QUOTA_EXCEEDED_ERR';
      break;
    case FileError.NOT_FOUND_ERR:
      msg = 'NOT_FOUND_ERR';
      break;
    case FileError.SECURITY_ERR:
      msg = 'SECURITY_ERR';
      break;
    case FileError.INVALID_MODIFICATION_ERR:
      msg = 'INVALID_MODIFICATION_ERR';
      break;
    case FileError.INVALID_STATE_ERR:
      msg = 'INVALID_STATE_ERR';
      break;
    default:
      msg = 'Unknown Error';
      break;
  }
}

which of course complains about FileError.

These are my @types already in place:

chrome
filesystem
filewriter
jquery

As much as I understood from the HTML5 FileSystem API book, the FileError is part of File API, so with @types/filesystem in place, it should be recognized by WebStorm... What am I missing?

Another missing type is navigator, but I found info that it has been merged to lib.d.ts so it should be recognized as well.


问:
Animate div from bottom to top and back
I have a div element which represents a navigation bar and has the id #navbar. It is positioned absolutely and is set to bottom: 20px;. Now I want it to move to the top, while keeping a 20px distance to the top, on the click of a button. When clicking the button again it should move back to the bottom of the page (again keeping the 20px distance) even if the window has been resized. In general, the resizing of the window should have no effect on the navigation bar. Here is the JavaScript code I have.

```<code>var isUp = false;
function animate() {
    if(!isUp) {
        $("#navbar").animate({top: 20}, 2000);
    } else {
        $("#navbar").animate({bottom: 20}, 2000);
    }
}
</code>```

But it doesn't work and the bar always ends up in the middle of the page. Any help is greatly appreciated.

EDIT:
Here is an example: https://jsfiddle.net/6knLw3a3/

答: bottom and top will position an absolutely positioned element according to it's closest explicitly positioned ancestor. So make sure that you put position:relative on the container element.

Title: Animate div from bottom to top and back

Body:
I have a div element which represents a navigation bar and has the id #navbar. It is positioned absolutely and is set to bottom: 20px;. Now I want it to move to the top, while keeping a 20px distance to the top, on the click of a button. When clicking the button again it should move back to the bottom of the page (again keeping the 20px distance) even if the window has been resized. In general, the resizing of the window should have no effect on the navigation bar. Here is the JavaScript code I have.

var isUp = false;
function animate() {
    if(!isUp) {
        $("#navbar").animate({top: 20}, 2000);
    } else {
        $("#navbar").animate({bottom: 20}, 2000);
    }
}

But it doesn't work and the bar always ends up in the middle of the page. Any help is greatly appreciated.

EDIT:
Here is an example: https://jsfiddle.net/6knLw3a3/


问:
RemoteApps on Server 2012 and above in a workgroup environment
I was able to set up RemoteApps on Server 2008 R2 on AWS in a workgroup environment. I want to do the same on Server 2012 and above. I understand that Microsoft removed RemoteApp manager when a Server 2012 is in a workgroup environment and it seems the server must be joined to a domain before RemoteApp manager becomes available. Also, they removed old Powershell commands and the new ones only work in a domain environment. Is there another way I can still setup up RemoteApps on a Server 2012 and above in a workgroup environment ?  </p>

答:
My setup is Windows Server 2012 R2 + workgroup + Remote Desktop Services role (with 2 sub-roles: session host and rd licensing). Like you, I could not publish programs as RemoteApps, until I found this free little tool: http://www.kimknight.net/remoteapptool

As of now, it doesn't support Windows Server 2016 but this might change in the future. Also, I had no idea you can "remote-app" programs hosted in Windows XP SP3! :)


问:
Directly using a list saved in an auxiliary file
Is there a way to save a list in an auxiliary file and then manipulate it directly, without having to download it, manipulate it, and then rewriting the file?

Namely, I would like to be able to do e.g. something like this:

```<code>L = open('file')
L.append(0)
L.close()
</code>```

What is the correct way to do it? Is there a specific class for it?

I solved the problem using shelve (a pickle-based library) as follows:

```<code>import shelve

f = shelve.open('list.db',writeback=True)
f['0'] = the list I want
L = f['0']

Manipulate L however I want

f.close()
</code>```

答:
This may be tremendously insecure, but it works:

```<code>class Open(list):
    def __init__(self, fname):
        list.__init__(self, [])
        self.fname = fname
        with open(fname) as f:
            self.extend(eval(f.read()))

    def close(self):
        with open(self.fname, "w") as f:
            f.write(str(self))
</code>```

Usage:

```<code>L = Open("test.txt")
L.append(0)
L.close()
</code>```

Open behaves like an ordinary list and can save itself to a file and construct itself using one.

This will execute the contents of the file as if it was Python code, so if any malicious code is read, it'll do its thing, be aware of this. Anyway, reading data from untrusted sources is always dangerous.

Body:
Is there a way to save a list in an auxiliary file and then manipulate it directly, without having to download it, manipulate it, and then rewriting the file?

Namely, I would like to be able to do e.g. something like this:

L = open('file')
L.append(0)
L.close()

What is the correct way to do it? Is there a specific class for it?

I solved the problem using shelve (a pickle-based library) as follows:

import shelve

f = shelve.open('list.db',writeback=True)
f['0'] = the list I want
L = f['0']

Manipulate L however I want

f.close()

Body:
This may be tremendously insecure, but it works:

class Open(list):
    def __init__(self, fname):
        list.__init__(self, [])
        self.fname = fname
        with open(fname) as f:
            self.extend(eval(f.read()))

    def close(self):
        with open(self.fname, "w") as f:
            f.write(str(self))

Usage:

L = Open("test.txt")
L.append(0)
L.close()

Open behaves like an ordinary list and can save itself to a file and construct itself using one.

This will execute the contents of the file as if it was Python code, so if any malicious code is read, it'll do its thing, be aware of this. Anyway, reading data from untrusted sources is always dangerous.


问:
WSS 3.0 and CKEDITOR
I wonder if it is possible to integrate the CKEditor with sharepoint (WSS 3.0). Could it be possible with Visual Studio and deploying such as a Web Part??

Thanks.

答:
You could try it with CKEditor for SharePoint:
http://ckeditor.com/sharepoint

Title: WSS 3.0 and CKEDITOR


问:
How to use async method in DelegateCommand
I want to link async method to a delegate command in prism framework in Xamarin.Forms and my question is how to do it?

Is below solution correct? Is there exist any pitfall? (deadlock, UI slow or freezing, bad practices, ...)

```<code>{      // My view model constructor
       ...
       MyCommand = new DelegateCommand(async () => await MyJobAsync());
       ...
}

private async Task MyJobAsync()
{
       ... // Some await calls
       ... // Some UI element changed such as binded Observable collections
}
</code>```

答:
As has already been mentioned the way to handle async code with delegate command is to use async void. There has been a lot of discussion on this, far beyond just Prism or Xamarin Forms. The bottom line is that ICommand that both the Xamarin Forms Command and Prism DelegateCommand are limited by ICommand's void Execute(object obj). If you'd like to get more information on this I would encourage you to read the blog by Brian Lagunas explaining why DelegateCommand.FromAsync handler is obsolete.

Generally most concerns are handled very easily by updating the code. For example. I often hear complaints about Exceptions as "the reason" why FromAsync was necessary, only to see in their code they never had a try catch. Because async void is fire and forget, another complaint I've heard is that a command could execute twice. That also is easily fixed with DelegateCommands ObservesProperty and ObservesCanExecute.

Body:
I want to link async method to a delegate command in prism framework in Xamarin.Forms and my question is how to do it?

Is below solution correct? Is there exist any pitfall? (deadlock, UI slow or freezing, bad practices, ...)

{      // My view model constructor
       ...
       MyCommand = new DelegateCommand(async () => await MyJobAsync());
       ...
}

private async Task MyJobAsync()
{
       ... // Some await calls
       ... // Some UI element changed such as binded Observable collections
}


问:
Sublime Text 3 find and replace in multiple files
I want to find and replace code in multiple files.

Does anyone know if the feature "find and replace in multiple files" in Sublime Text 3 is gone?

It used to be a feature for ST2 (shift-command-F), see screenshots ST2 and ST3.

Or is there a other way to do this?

答:
The option is still there, but because you're using a custom theme the bar needs to be taller for you to see the entire contents of the panel.

You can grab the top of the panel and stretch it up so that everything is visible and then back down as far as it will go to make it compact again.

You only have to do this once; Sublime remembers the height of the panel and will use it next time (which is why it uses the incorrect height when you switch to a theme that makes everything in the panel taller).


问:
Global static variable initialised with a call to static class function in c++
Not sure how correctly formulate the question but here is the problem.

I have a static lib where I have the following class in a.h:

```<code>#pragma once
#include <vector>
class A{
public:
 void Run() {
  data_.push_back(10);
  std::cout << "size: " << data_.size() << std::endl;
 }
private:
 static std::vector<int> data_;
};
</code>```

a.cpp is as follows:

```<code>#include "a.h"
std::vector<int> A::data_;
</code>```

And I have another class in b.h:

```<code>#pragma once
#include <string>
class B
{
  public:
    static std::string Get();
};
</code>```

And b.cpp:

```<code>#include "b.h"
#include "a.h"
std::string B::Get()
{
  static A a;
  a.Run();
  return "foo";
}
</code>```

Now my main app which is using the above static lib is as follows:

```<code>#include <iostream>
#include "a.h"
#include "b.h"

static std::string var1= B::Get();

int main(int argc, char** argv)
{
  A a;
  a.Run();
}
</code>```

Trying to understand why the output is:

size: 1

size: 1

There should be a single instance of each static data member for the entire class, so there should be a single call to A::data_ constructor.
Am I hitting "static initialization order fiasco"? I.e. data_ is not initialised before I use it, but then I should be getting the crash?

And now lets imagine my data_ holds dynamically initialised items (something none POD). How will it be destructed if at the end data_ holds one item, although I've inserted 2?

And that's what actually is happening in my real life code (it sometimes crashes during destruction of data_).

Getting rid of global static ( static std::string var1= B::Get(); ) solves the problem, but I still want to understand the under the hood problem.

The described case can be reproduced in VS2015 (the real life case is reproducible in gcc 6.2 )

答:
Am I hitting "static initialization order fiasco"?

Most likely.

You can remove the problem by making the static data of a class available via a function call. E.g.

```<code>class A{
public:
 void Run() {
  getData().push_back(10);
  std::cout << "size: " << getData().size() << std::endl;
 }
private:
 static std::vector<int>& getData();
};

std::vector<int>& A::getData()
{
   static std::vector<int> data;
   return data;
}
</code>```

When you do that, data will be initialized when A::getData() is called the first time. It removes the static initialization order issue completely.

Body:
Not sure how correctly formulate the question but here is the problem.

I have a static lib where I have the following class in a.h:

#pragma once
#include <vector>
class A{
public:
 void Run() {
  data_.push_back(10);
  std::cout << "size: " << data_.size() << std::endl;
 }
private:
 static std::vector<int> data_;
};

a.cpp is as follows:

#include "a.h"
std::vector<int> A::data_;

And I have another class in b.h:

#pragma once
#include <string>
class B
{
  public:
    static std::string Get();
};

And b.cpp:

#include "b.h"
#include "a.h"
std::string B::Get()
{
  static A a;
  a.Run();
  return "foo";
}

Now my main app which is using the above static lib is as follows:

#include <iostream>
#include "a.h"
#include "b.h"

static std::string var1= B::Get();

int main(int argc, char** argv)
{
  A a;
  a.Run();
}

Trying to understand why the output is:

size: 1

size: 1

There should be a single instance of each static data member for the entire class, so there should be a single call to A::data_ constructor.
Am I hitting "static initialization order fiasco"? I.e. data_ is not initialised before I use it, but then I should be getting the crash?

And now lets imagine my data_ holds dynamically initialised items (something none POD). How will it be destructed if at the end data_ holds one item, although I've inserted 2?

And that's what actually is happening in my real life code (it sometimes crashes during destruction of data_).

Getting rid of global static ( static std::string var1= B::Get(); ) solves the problem, but I still want to understand the under the hood problem.

The described case can be reproduced in VS2015 (the real life case is reproducible in gcc 6.2 )

Body:
Am I hitting "static initialization order fiasco"?

Most likely.

You can remove the problem by making the static data of a class available via a function call. E.g.

class A{
public:
 void Run() {
  getData().push_back(10);
  std::cout << "size: " << getData().size() << std::endl;
 }
private:
 static std::vector<int>& getData();
};

std::vector<int>& A::getData()
{
   static std::vector<int> data;
   return data;
}

When you do that, data will be initialized when A::getData() is called the first time. It removes the static initialization order issue completely.