问:
How to get a hidden div to stay visible when hovered over with jQuery?
I have a confusing issue. When my first div "leftbox" is hovered over, "rightbox" (the hidden div) displays, but it eventually disappears when "leftbox" is not hovered over. But I need "rightbox" to stay visible when rightbox is hovered over, then when the user's mouse leaves rightbox, then it should disappear. How can I get this to work? I'd really appreciate the help.

答:
If you add a container class it works fine.

$(function(){
 $('.container').hover(function(){
  var boxId = $(this).find("[data-id]").attr('data-id');
  $('#'+boxId).stop().fadeToggle();
 });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.leftbox {
 width: 100px;
 height: 100px;
 border: 1px solid black;
 float: left;
}
.rightbox {
 width: 100px;
 height: 100px;
 border: 1px solid black;
 background: #99bf8f;
 margin-left: 110px;
 display: none;
}
.container {
  float:left;
}</code>```

<!doctype html>

<meta charset="UTF-8">

<link rel="stylesheet" href="test.css">

```

Body:
If you add a container class it works fine.

$(function(){
 $('.container').hover(function(){
  var boxId = $(this).find("[data-id]").attr('data-id');
  $('#'+boxId).stop().fadeToggle();
 });
});

.leftbox {
 width: 100px;
 height: 100px;
 border: 1px solid black;
 float: left;
}
.rightbox {
 width: 100px;
 height: 100px;
 border: 1px solid black;
 background: #99bf8f;
 margin-left: 110px;
 display: none;
}
.container {
  float:left;
}

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="test.css">
</head>

<body>

<div class="container">
  <div class="leftbox" data-id="functionbox1"></div>
  <div class="rightbox" id="functionbox1"></div>
</div>

<script src="test.js"></script>
</body>
</html>


来源: stackexchange

问:
C++ population of unordered map using multithreading
I was wondering if there was a way to speed up the population of an unordered map called (path_from_startend). The unordered map always has a unique key.</p>

```<code>#pragma omp parallel for
    for (int i=start_index;i<end_index;++i){
        for (int j=start_index;j<end_index;++j){
            string key= to_string(unique_locations[i])+to_string(unique_locations[j]);
            //dont compute path to itself
            if (i==j){
            }
            else {
                    vector <unsigned>  path = pathbot.FindPath(unique_locations[i],unique_locations[j],turn_penalty);
                    path_from_startend.insert(make_pair(key,path));

            }
        }

    }
</code>```

答:
You could try whether the following pattern gains you some speed.  You are basically populating partial maps which you then merge into the whole map.  The speedup depends very much on how long the construction and insertion of the elements take.  If your elements are cheap to construct and insert, then your speedup might even be negative, because for each partial map it has to go through the whole map searching for duplicates.</p>

```<code>#pragma omp parallel
{
  std::unordered_map < std::string, std::vector < unsigned > > partial;

  #pragma omp for
  for (int i = start_index; i < end_index; ++i)
  {
    for (int j = start_index; j < end_index; ++j)
    {
      std::string key = std::to_string(unique_locations[i])
                      + std::to_string(unique_locations[j]);

      //dont compute path to itself
      if (i != j)
      {
        std::vector<unsigned> path = pathbot.FindPath(unique_locations[i],
                                                      unique_locations[j],
                                                      turn_penalty);
        partial.insert(std::make_pair(key,path));
      }
    }
  }

  #pragma omp critical
  path_from_startend.insert(partial.begin(),partial.end());
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I was wondering if there was a way to speed up the population of an unordered map called (path_from_startend). The unordered map always has a unique key.

#pragma omp parallel for
    for (int i=start_index;i<end_index;++i){
        for (int j=start_index;j<end_index;++j){
            string key= to_string(unique_locations[i])+to_string(unique_locations[j]);
            //dont compute path to itself
            if (i==j){
            }
            else {
                    vector <unsigned>  path = pathbot.FindPath(unique_locations[i],unique_locations[j],turn_penalty);
                    path_from_startend.insert(make_pair(key,path));

            }
        }

    }

Body:
You could try whether the following pattern gains you some speed.  You are basically populating partial maps which you then merge into the whole map.  The speedup depends very much on how long the construction and insertion of the elements take.  If your elements are cheap to construct and insert, then your speedup might even be negative, because for each partial map it has to go through the whole map searching for duplicates.

#pragma omp parallel
{
  std::unordered_map < std::string, std::vector < unsigned > > partial;

  #pragma omp for
  for (int i = start_index; i < end_index; ++i)
  {
    for (int j = start_index; j < end_index; ++j)
    {
      std::string key = std::to_string(unique_locations[i])
                      + std::to_string(unique_locations[j]);

      //dont compute path to itself
      if (i != j)
      {
        std::vector<unsigned> path = pathbot.FindPath(unique_locations[i],
                                                      unique_locations[j],
                                                      turn_penalty);
        partial.insert(std::make_pair(key,path));
      }
    }
  }

  #pragma omp critical
  path_from_startend.insert(partial.begin(),partial.end());
}


问:
How to change Bootstrap's classic mobile menu?
I'm fairly new in Bootstrap. Can you guys give me some advice on how to edit a Bootstrap mobile menu like http://apple.com website when resize to its mobile breakpoint. It's really cool with animations. I want my Bootstrap site to look different. Thanks.</p>

答:
Bootstrap mobile menu icon is generated with:

```<code><button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
     <span class="icon-bar"></span>
     <span class="icon-bar"></span>
</button>
</code>```

Notice, the data-target to collapse:

```<code><ul class="nav navbar-nav" class="nav-collapse collapse" id="myNavbar">
</code>```

Now, Edit or Add animations of your choice.

Body:
Bootstrap mobile menu icon is generated with:

<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
     <span class="icon-bar"></span>
     <span class="icon-bar"></span>
</button>

Notice, the data-target to collapse:

<ul class="nav navbar-nav" class="nav-collapse collapse" id="myNavbar">

Now, Edit or Add animations of your choice.


问:
Hugo: Automatically Link Headers
With Hugo static site generator, is it possible to have it automatically put links around header elements? I see that it does fill in the ID attribute so it can be referenced but I would like to automatically create the link as well, like this:

```<code><a href="/post/cool-blog-post#some-interesting-title">
    <h2 id="some-interesting-title">Some Interesting Title</h2>
</a>
</code>```

I did not see anyway in the documentation to do this and I think it would be helpful for users linking to a particular point in a lengthy post.

答:
This doesn't seem to be possible out of the box. There are two ways of working around it that I can think of: using JavaScript, as revelt suggested, or using HTML in your markdown.

For example, consider the HTML you supplied above.

```<code><a href="/post/cool-blog-post#some-interesting-title">
    <h2 id="some-interesting-title">Some Interesting Title</h2>
</a>
</code>```

If you put this code directly into a Hugo markdown document, it will produce the kind of link you are looking for. However, this is a pain to type every time, so to reduce your work you can make a shortcode.

In layouts/shortcodes/link-heading.html:

```<code>{{ $id := .Get 0 | lower | replaceRE "[^0-9a-z]" "-" | replaceRE "-+" "-" -}}
<a href="#{{ $id }}">
  <h2 id="{{ $id }}">{{ .Get 0 }}</h2>
</a>
</code>```

In your markdown document:

```<code>{{< link-heading "Some Interesting Title" >}}
</code>```

I have left the base URL out here, but you can pass it as a parameter from your markdown document if you want. (Of course, then you have to know what the URL is without having Hugo do it for you, which is not ideal.)

This approach has the disadvantages that you can't use the normal markdown heading syntax, and that you don't get Hugo's built-in resolution of duplicate anchors. But it will get the job done.

Title: Hugo: Automatically Link Headers

Body:
With Hugo static site generator, is it possible to have it automatically put links around header elements? I see that it does fill in the ID attribute so it can be referenced but I would like to automatically create the link as well, like this:

Some Interesting Title

I did not see anyway in the documentation to do this and I think it would be helpful for users linking to a particular point in a lengthy post.

Body:
This doesn't seem to be possible out of the box. There are two ways of working around it that I can think of: using JavaScript, as revelt suggested, or using HTML in your markdown.

For example, consider the HTML you supplied above.

<a href="/post/cool-blog-post#some-interesting-title">
    <h2 id="some-interesting-title">Some Interesting Title</h2>
</a>

If you put this code directly into a Hugo markdown document, it will produce the kind of link you are looking for. However, this is a pain to type every time, so to reduce your work you can make a shortcode.

In layouts/shortcodes/link-heading.html:

{{ $id := .Get 0 | lower | replaceRE "[^0-9a-z]" "-" | replaceRE "-+" "-" -}}
<a href="#{{ $id }}">
  <h2 id="{{ $id }}">{{ .Get 0 }}</h2>
</a>

In your markdown document:

{{< link-heading "Some Interesting Title" >}}

I have left the base URL out here, but you can pass it as a parameter from your markdown document if you want. (Of course, then you have to know what the URL is without having Hugo do it for you, which is not ideal.)

This approach has the disadvantages that you can't use the normal markdown heading syntax, and that you don't get Hugo's built-in resolution of duplicate anchors. But it will get the job done.


答:
Replace the lines of the form

```<code>counts['A1']+=counts['A1']
</code>```

with lines of the form

```<code>counts['A1']+=1
</code>```

As it is, you never increment counts because you're adding its current value (0) to it each time.

Title: Getting wrong results from counting function

Body:
Here is my code, i know it isn't clean enough, but it cannot run as I thought, anyone can help me?

I fixed it, thank you for your helps

The general idea of this code is comparing each coordinate with a range, and calculate the amounts of points for each grid

the result is:
{'other': 862, 'B4': 2, 'D5': 1, 'A1': 0, 'D4': 2, 'A3': 2, 'A2': 2, 'A4': 0, 'B2': 36, 'B3': 8, 'C3': 15, 'C2': 50, 'C1': 1, 'C4': 7, 'D3': 4, 'C5': 1, 'B1': 7}

I don't know why 'other' get so much

 import json
    from pprint import pprint
    xa1_min = 144.700000
    xa1_max = 144.850000
    ya1_min = -37.650000
    ya1_max = -37.500000

    xa2_min = 144.850000
    xa2_max = 145.000000
    ya2_min = -37.650000
    ya2_max = -37.500000

    xa3_min = 145.000000
    xa3_max = 145.150000
    ya3_min = -37.650000
    ya3_max = -37.500000

    xa4_min =145.150000
    xa4_max =145.300000
    ya4_min =-37.650000
    ya4_max =-37.500000

    xb1_min =144.700000
    xb1_max =144.850000
    yb1_min =-37.800000
    yb1_max =-37.650000

    xb2_min =144.850000
    xb2_max =145.000000
    yb2_min =-37.800000
    yb2_max =-37.650000

    xb3_min =145.000000
    xb3_max =145.150000
    yb3_min =-37.800000
    yb3_max =-37.650000

    xb4_min =145.150000
    xb4_max =145.300000
    yb4_min =-37.800000
    yb4_max =-37.650000

    xc1_min =144.700000
    xc1_max =144.850000
    yc1_min =-37.950000
    yc1_max =-37.800000

    xc2_min =144.850000
    xc2_max =145.000000
    yc2_min =-37.950000
    yc2_max =-37.800000

    xc3_min =145.000000
    xc3_max =145.150000
    yc3_min =-37.950000
    yc3_max =-37.800000

    xc4_min =145.150000
    xc4_max =145.300000
    yc4_min = -37.950000
    yc4_max = -37.800000

    xc5_min =145.300000
    xc5_max =145.450000
    yc5_min =-37.950000
    yc5_max =-37.800000

    xd3_min =145.000000
    xd3_max =145.150000
    yd3_min =-38.100000
    yd3_max =-37.950000

    xd4_min =145.150000
    xd4_max =145.300000
    yd4_min =-38.100000
    yd4_max =-37.950000

    xd5_min =145.300000
    xd5_max =145.450000
    yd5_min =-38.100000
    yd5_max =-37.950000
    #["properties"]['ID']
    # Reading from grid
    with open('tinyTwitter.json') as load_f:
        info = json.load(load_f)

    coordinates = list()
    #print info

    for line in info:
        #print line['json']['coordinates']['coordinates']
        coordinates.append(line['json']['coordinates']['coordinates'])

    #print coordinates[0][1]
    #print coordinates[0][0]

    counts = {'A1':0,'A2':0,'A3':0,'A4':0,'B1':0,'B2':0,'B3':0,'B4':0,'C1':0,'C2':0,'C3':0,'C4':0,'C5':0,'D3':0,'D4':0,'D5':0,'other':0}
    #comparing
    def compare(x,y):

    if xa1_min <= x <= xa1_max and ya1_min <= y <= ya1_max:
        counts['A1'] +=1

    elif xa2_min <= x <= xa2_max and ya2_min <=y<= ya2_max:
        counts['A2'] +=1

    elif xa3_min <= x <= xa3_max and ya3_min <=y<= ya3_max:
        counts['A3'] +=1

    elif xa4_min <= x <= xa4_max and ya4_min <=y<= ya4_max:
        counts['A4'] += 1

    elif xb1_min <= x <= xb1_max and yb1_min <=y<= yb1_max:
        counts['B1'] += 1

    elif xb2_min <= x <= xb2_max and yb2_min <=y<= yb2_max:
        counts['B2'] += 1

    elif xb3_min <= x <= xb3_max and yb3_min <=y<= yb3_max:
        counts['B3'] += 1

    elif xb4_min <= x <= xb4_max and yb4_min <=y<= yb4_max:
        counts['B4'] += 1

    elif xc1_min <= x <= xc1_max and yc1_min <=y<= yc1_max:
        counts['C1'] += 1

    elif xc2_min <= x <= xc2_max and yc2_min <=y<= yc2_max:
        counts['C2'] += 1

    elif xc3_min <= x <= xc3_max and yc3_min <=y<= yc3_max:
        counts['C3'] += 1

    elif xc4_min <= x <= xc4_max and yc4_min <=y<= yc4_max:
        counts['C4'] += 1

    elif xc5_min <= x <= xc5_max and yc5_min <=y<= yc5_max:
        counts['C5'] += 1

    elif xd3_min <= x <= xd3_max and yd3_min <=y<= yd3_max:
        counts['D3'] += 1

    elif xd4_min <= x <= xd4_max and yd4_min <=y<= yd4_max:
        counts['D4'] += 1

    elif xd5_min <= x <= xd5_max and yd5_min <=y<= yd5_max:
        counts['D5'] += 1

    else:
        counts['other']+= 1

        #print counts

    for i,j in coordinates:
        #print i,j
        compare(i,j)
    print counts

Body:
Replace the lines of the form

counts['A1']+=counts['A1']

with lines of the form

counts['A1']+=1

As it is, you never increment counts because you're adding its current value (0) to it each time.


问:
Ideal cross-platform library
One has to create a new software library. This library has no system I/O routines and contains only Init(config), Run(some_data_inputs), and DeInit(config) functions and a few typedefs and defines. Run() function just processes given input data and generates output data, no interrupts, threads, locks, etc. However, it requires some RAM for its internal needs. The interface is described in a header file and a static library contains the implementation.

This library must be as much multi-plarform as possible. It must be matter of minutes to port this library to any new platform onto any new OS+CPU. Sometimes this lib can be used even on the platforms without operating systems.

So, before starting development, one has to decide:

Must this lib be written in ANSI-C or even in a sub-set of ANSI-C because some platforms may not support ANSI-C completely?

Whether to write an abstraction
layer, which encapsulates an
underlying OS+CPU?

Should this abstraction layer
include its own memory manager
(malloc/free routines) or all
platforms today provide it already?

答:
There are lots of different styles of system architecture, and writing something non-trivial that is easily portable to all of them is probably not possible.

I suggest, though, that you write your interfaces so that they take in a pointer to a structure that contains all of the system functions that are needed.  You could do this either in every call or just once in the init routine.

This way you will have limited the places where differences in the code for different architectures to code which generates the structure of function pointers.

This also makes it so that you can easily test the library for handling failure of one or more of these routines by altering just this structure, so that if you wanted to test for proper handling of malloc failure then you just replace the malloc pointer in the struct with one that fails.

You might also wrap the system functions on a particular system with functions that give you the interface your library expects as well as at least partially handling errors (like translating to/from errno).

ContentLicense: CC BY-SA 2.5

Title: Ideal cross-platform library


问:
Can pandas handle variable-length whitespace as column delimiters
I have a textfile where columns are separated by variable amounts of whitespace. Is it possible to load this file directly as a pandas dataframe without pre-processing the file? In the pandas documentation the delimiter section says that I can use a 's*' construct but I couldn't get this to work.

```<code>## sample data
head sample.txt

#                                                                            --- full sequence --- -------------- this domain -------------   hmm coord   ali coord   env coord
# target name        accession   tlen query name           accession   qlen   E-value  score  bias   #  of  c-Evalue  i-Evalue  score  bias  from    to  from    to  from    to  acc description of target
#------------------- ---------- ----- -------------------- ---------- ----- --------- ------ ----- --- --- --------- --------- ------ ----- ----- ----- ----- ----- ----- ----- ---- ---------------------
ABC_membrane         PF00664.18   275 AAF67494.2_AF170880  -            615     8e-29  100.7  11.4   1   1     3e-32     1e-28  100.4   7.9     3   273    42   313    40   315 0.95 ABC transporter transmembrane region
ABC_tran             PF00005.22   118 AAF67494.2_AF170880  -            615   2.6e-20   72.8   0.0   1   1   1.9e-23   6.4e-20   71.5   0.0     1   118   402   527   402   527 0.93 ABC transporter
SMC_N                PF02463.14   220 AAF67494.2_AF170880  -            615   3.8e-08   32.7   0.2   1   2    0.0036        12    4.9   0.0    27    40   391   404   383   408 0.86 RecF/RecN/SMC N terminal domain
SMC_N                PF02463.14   220 AAF67494.2_AF170880  -            615   3.8e-08   32.7   0.2   2   2   1.8e-09   6.1e-06   25.4   0.0   116   210   461   568   428   575 0.85 RecF/RecN/SMC N terminal domain
AAA_16               PF13191.1    166 AAF67494.2_AF170880  -            615   3.1e-06   27.5   0.3   1   1     2e-09     7e-06   26.4   0.2    20   158   386   544   376   556 0.72 AAA ATPase domain
YceG                 PF02618.11   297 AAF67495.1_AF170880  -            284   3.4e-64  216.6   0.0   1   1   2.9e-68     4e-64  216.3   0.0    68   296    53   274    29   275 0.85 YceG-like family
Pyr_redox_3          PF13738.1    203 AAF67496.2_AF170880  -            352   2.9e-28   99.1   0.0   1   2   2.8e-30   4.8e-27   95.2   0.0     1   201     4   198     4   200 0.85 Pyridine nucleotide-disulphide oxidoreductase

#load data
from pandas import *
data = read_table('sample.txt', skiprows=3, header=None, sep=" ")

ValueError: Expecting 83 columns, got 91 in row 4

#load data part 2
data = read_table('sample.txt', skiprows=3, header=None, sep="'s*' ")
#this mushes some of the columns into the first column and drops the rest.
    X.1
1    ABC_tran PF00005.22 118 AAF67494.2_
2    SMC_N PF02463.14 220 AAF67494.2_
3    SMC_N PF02463.14 220 AAF67494.2_
4    AAA_16 PF13191.1 166 AAF67494.2_
5    YceG PF02618.11 297 AAF67495.1_
6    Pyr_redox_3 PF13738.1 203 AAF67496.2_
7    Pyr_redox_3 PF13738.1 203 AAF67496.2_
8    FMO-like PF00743.14 532 AAF67496.2_
9    FMO-like PF00743.14 532 AAF67496.2_
</code>```

While I can preprocess the files to change the whitespace to commas/tabs it would be nice to load them directly.

(FYI this is the *.hmmdomtblout output from the hmmscan program)

答:
None of the given answers works in a case like this:

```<code>Block..Col.name.with.spaces..col3
...1..6.141754e+003..2.998903e+000
2048..6.154461e+003..6.010216e+000
</code>```

that is, two or more spaces are used as separators, but the column names can themselves contain one space.

In such a case, we need a regular expression for two or more spaces. This will work:

```<code>sep=r"[ ]{2,}"
</code>```

But again, the drawback is that it triggers the python parser.

Body:
I have a textfile where columns are separated by variable amounts of whitespace. Is it possible to load this file directly as a pandas dataframe without pre-processing the file? In the pandas documentation the delimiter section says that I can use a 's*' construct but I couldn't get this to work.

## sample data
head sample.txt

#                                                                            --- full sequence --- -------------- this domain -------------   hmm coord   ali coord   env coord
# target name        accession   tlen query name           accession   qlen   E-value  score  bias   #  of  c-Evalue  i-Evalue  score  bias  from    to  from    to  from    to  acc description of target
#------------------- ---------- ----- -------------------- ---------- ----- --------- ------ ----- --- --- --------- --------- ------ ----- ----- ----- ----- ----- ----- ----- ---- ---------------------
ABC_membrane         PF00664.18   275 AAF67494.2_AF170880  -            615     8e-29  100.7  11.4   1   1     3e-32     1e-28  100.4   7.9     3   273    42   313    40   315 0.95 ABC transporter transmembrane region
ABC_tran             PF00005.22   118 AAF67494.2_AF170880  -            615   2.6e-20   72.8   0.0   1   1   1.9e-23   6.4e-20   71.5   0.0     1   118   402   527   402   527 0.93 ABC transporter
SMC_N                PF02463.14   220 AAF67494.2_AF170880  -            615   3.8e-08   32.7   0.2   1   2    0.0036        12    4.9   0.0    27    40   391   404   383   408 0.86 RecF/RecN/SMC N terminal domain
SMC_N                PF02463.14   220 AAF67494.2_AF170880  -            615   3.8e-08   32.7   0.2   2   2   1.8e-09   6.1e-06   25.4   0.0   116   210   461   568   428   575 0.85 RecF/RecN/SMC N terminal domain
AAA_16               PF13191.1    166 AAF67494.2_AF170880  -            615   3.1e-06   27.5   0.3   1   1     2e-09     7e-06   26.4   0.2    20   158   386   544   376   556 0.72 AAA ATPase domain
YceG                 PF02618.11   297 AAF67495.1_AF170880  -            284   3.4e-64  216.6   0.0   1   1   2.9e-68     4e-64  216.3   0.0    68   296    53   274    29   275 0.85 YceG-like family
Pyr_redox_3          PF13738.1    203 AAF67496.2_AF170880  -            352   2.9e-28   99.1   0.0   1   2   2.8e-30   4.8e-27   95.2   0.0     1   201     4   198     4   200 0.85 Pyridine nucleotide-disulphide oxidoreductase

#load data
from pandas import *
data = read_table('sample.txt', skiprows=3, header=None, sep=" ")

ValueError: Expecting 83 columns, got 91 in row 4

#load data part 2
data = read_table('sample.txt', skiprows=3, header=None, sep="'s*' ")
#this mushes some of the columns into the first column and drops the rest.
    X.1
1    ABC_tran PF00005.22 118 AAF67494.2_
2    SMC_N PF02463.14 220 AAF67494.2_
3    SMC_N PF02463.14 220 AAF67494.2_
4    AAA_16 PF13191.1 166 AAF67494.2_
5    YceG PF02618.11 297 AAF67495.1_
6    Pyr_redox_3 PF13738.1 203 AAF67496.2_
7    Pyr_redox_3 PF13738.1 203 AAF67496.2_
8    FMO-like PF00743.14 532 AAF67496.2_
9    FMO-like PF00743.14 532 AAF67496.2_

While I can preprocess the files to change the whitespace to commas/tabs it would be nice to load them directly.

(FYI this is the *.hmmdomtblout output from the hmmscan program)

Body:
None of the given answers works in a case like this:

Block..Col.name.with.spaces..col3
...1..6.141754e+003..2.998903e+000
2048..6.154461e+003..6.010216e+000

that is, two or more spaces are used as separators, but the column names can themselves contain one space.

In such a case, we need a regular expression for two or more spaces. This will work:

sep=r"[ ]{2,}"

But again, the drawback is that it triggers the python parser.


问:
What's the difference between this function and the lambda?
```<code>#include<iostream>

using namespace std;

int* New()
{
    return new int(666);
}
int Foo()
{
    //method1:
    int* it = New();
    return *it;
    //method2:
    return []() { return *(new int(666)); };//Complier has a complain here
    /*Both New() and Lambda are callable object, are there any differences between method1 and method2?*/
}
int main()
{
    cout << Foo() << endl;
    return 0;
}
</code>```

I'm fresh in C++, I encounter a situation above, I had review the chapter 10.3.2 to 10.3.3 of C++ Primer, where introduces the lambda expression.But it doesn't work for me, I'm also confused about the last annotation I list.

答:
```<code>return []() { return *(new int(666)); };
</code>```

This line is trying to return the lambda itself.  You want to call the lambda and return the integer that it produces:

```<code>return []() { return *(new int(666)); }();  // Note the () at the end
</code>```

There's generally not much point in defining a lambda function only to immediately call it, though.  They're more commonly used when you need to actually return a function, or take one as an argument.  (This is a more advanced thing to do, though, so you probably shouldn't worry about it for now.)

On a separate note: your program allocates integers with new, but it never releases them with delete.  This is a memory leak, which is something you should avoid.

ContentLicense: CC BY-SA 4.0

Body:
#include<iostream>

using namespace std;

int* New()
{
    return new int(666);
}
int Foo()
{
    //method1:
    int* it = New();
    return *it;
    //method2:
    return []() { return *(new int(666)); };//Complier has a complain here
    /*Both New() and Lambda are callable object, are there any differences between method1 and method2?*/
}
int main()
{
    cout << Foo() << endl;
    return 0;
}

I'm fresh in C++, I encounter a situation above, I had review the chapter 10.3.2 to 10.3.3 of C++ Primer, where introduces the lambda expression.But it doesn't work for me, I'm also confused about the last annotation I list.

Body:
return []() { return *(new int(666)); };

This line is trying to return the lambda itself.  You want to call the lambda and return the integer that it produces:

return []() { return *(new int(666)); }();  // Note the () at the end

There's generally not much point in defining a lambda function only to immediately call it, though.  They're more commonly used when you need to actually return a function, or take one as an argument.  (This is a more advanced thing to do, though, so you probably shouldn't worry about it for now.)

On a separate note: your program allocates integers with new, but it never releases them with delete.  This is a memory leak, which is something you should avoid.


问:
Asking multiplication questions and computing the total of answers correct in Java
The code should output a table for Farenheit and Celsius</p>

```<code>public static void main(String[] args) {
    System.out.println("Fahrenheit\tCelsius");
    System.out.println("=======================");
     for(int temp = -45; temp <= 120; temp += 5) //for(int i = 0; i <= 100; i+= 10)
        {
            System.out.printf("%5d       |",          temp);
            double sum = (temp + (9.0/5.0)) * 32;
            System.out.printf("%5d", (int)sum );
            System.out.printl

n();
</code>```

答:
Looks like your braces are not opened and closed properly. Also the userScore and totalScore is reset in each iteration. So you will not have the proper score. Move it outside the loop.

```<code>import java.util.Scanner;

public class Multiplication {

    private static String question;
    private static Scanner input;
    private static Scanner scanner;
    private static int totalScore;
    private static int answer1;
    private static int userScore;

    public static void main(String[] args) {
        int number1;
        int number2;
        totalScore = 0;
        userScore = 0;
        input = new Scanner(System.in);
        do {
            number1 = (int)(Math.random() * 10);
            number2 = (int)(Math.random() * 10);

            System.out.print("What is " + number1 + " * " + number2 + "? ");
            int answer = input.nextInt();
            while (number1 * number2 != answer)
            {
                int answer1 = number1 * number2;
                System.out.println("Incorrect. The answer is " + answer1+".");
                System.out.print("Want more questions yes or no? ");
                scanner = new Scanner (System.in);
                question = scanner.next();
                totalScore++;
                break;
            }

            if (number1 * number2 == answer)
            {
                System.out.println("Correct. Nice work!");
                System.out.print("Want more questions yes or no? ");
                scanner = new Scanner (System.in);
                question = scanner.next();
                userScore++;
                totalScore++;
            }

        }while(question.equals("yes") || question.equals("y"));
        System.out.println("You have this many questions correct:" + userScore +" out of " + totalScore);
    }
}
</code>```

A Better Implementation

The code looks more readable here and few unnecessary lines of code are removed.

```<code>import java.util.Scanner;

public class Multiplication {

    private static final Scanner scanner = new Scanner (System.in);
    private static int totalScore = 0;
    private static int userScore = 0;
    private static int number1;
    private static int number2;
    private static int answer;

    public static boolean continueExe(){
        String question;
        System.out.print("Want more questions yes or no? ");
        question = scanner.next();
        return (question.equals("yes") || question.equals("y"));
    }

    public static void printOutput(){
        System.out.println("You have this many questions correct:" + userScore +" out of " + totalScore);
    }

    public static void askQuestion(){
        number1 = (int)(Math.random() * 10);
        number2 = (int)(Math.random() * 10);
        System.out.print("What is " + number1 + " * " + number2 + "? ");
    }

    public static void readAnswer(){
        answer = scanner.nextInt();
    }

    public static void isAnswerCorrect(){
        if (number1 * number2 != answer){
            System.out.println("Incorrect. The answer is " + number1 * number2 +".");
        }else{
            userScore++;
            System.out.println("Correct. Nice work!");
        }
        totalScore++;
    }

    public static void main(String[] args) {
        do{
            askQuestion();
            readAnswer();
            isAnswerCorrect();
        }while(continueExe());
        printOutput();
    }
}
</code>```

Body:
The code should output a table for Farenheit and Celsius

public static void main(String[] args) {
    System.out.println("Fahrenheit\tCelsius");
    System.out.println("=======================");
     for(int temp = -45; temp <= 120; temp += 5) //for(int i = 0; i <= 100; i+= 10)
        {
            System.out.printf("%5d       |",          temp);
            double sum = (temp + (9.0/5.0)) * 32;
            System.out.printf("%5d", (int)sum );
            System.out.printl

n();

Body:
Looks like your braces are not opened and closed properly. Also the userScore and totalScore is reset in each iteration. So you will not have the proper score. Move it outside the loop.

import java.util.Scanner;

public class Multiplication {

    private static String question;
    private static Scanner input;
    private static Scanner scanner;
    private static int totalScore;
    private static int answer1;
    private static int userScore;

    public static void main(String[] args) {
        int number1;
        int number2;
        totalScore = 0;
        userScore = 0;
        input = new Scanner(System.in);
        do {
            number1 = (int)(Math.random() * 10);
            number2 = (int)(Math.random() * 10);

            System.out.print("What is " + number1 + " * " + number2 + "? ");
            int answer = input.nextInt();
            while (number1 * number2 != answer)
            {
                int answer1 = number1 * number2;
                System.out.println("Incorrect. The answer is " + answer1+".");
                System.out.print("Want more questions yes or no? ");
                scanner = new Scanner (System.in);
                question = scanner.next();
                totalScore++;
                break;
            }

            if (number1 * number2 == answer)
            {
                System.out.println("Correct. Nice work!");
                System.out.print("Want more questions yes or no? ");
                scanner = new Scanner (System.in);
                question = scanner.next();
                userScore++;
                totalScore++;
            }

        }while(question.equals("yes") || question.equals("y"));
        System.out.println("You have this many questions correct:" + userScore +" out of " + totalScore);
    }
}

A Better Implementation

The code looks more readable here and few unnecessary lines of code are removed.

import java.util.Scanner;

public class Multiplication {

    private static final Scanner scanner = new Scanner (System.in);
    private static int totalScore = 0;
    private static int userScore = 0;
    private static int number1;
    private static int number2;
    private static int answer;

    public static boolean continueExe(){
        String question;
        System.out.print("Want more questions yes or no? ");
        question = scanner.next();
        return (question.equals("yes") || question.equals("y"));
    }

    public static void printOutput(){
        System.out.println("You have this many questions correct:" + userScore +" out of " + totalScore);
    }

    public static void askQuestion(){
        number1 = (int)(Math.random() * 10);
        number2 = (int)(Math.random() * 10);
        System.out.print("What is " + number1 + " * " + number2 + "? ");
    }

    public static void readAnswer(){
        answer = scanner.nextInt();
    }

    public static void isAnswerCorrect(){
        if (number1 * number2 != answer){
            System.out.println("Incorrect. The answer is " + number1 * number2 +".");
        }else{
            userScore++;
            System.out.println("Correct. Nice work!");
        }
        totalScore++;
    }

    public static void main(String[] args) {
        do{
            askQuestion();
            readAnswer();
            isAnswerCorrect();
        }while(continueExe());
        printOutput();
    }
}


答:
Mistake was you opened '{' two times for 'if'statement -

```<code>if (question.equals("no")||question.equals("n")&& (number1 * number2 == answer)){
{
</code>```

and forgot to close one bracket in last line.

Below code solves error due to brackets:

```<code>import java.util.Scanner;

public class Program3_3 {

private static String question;
private static Scanner input;
private static Scanner scanner;
private static int totalScore;
private static int answer1;
private static int userScore;

public static void main(String[] args) {
do {
    int number1 = (int)(Math.random() * 10);
    int number2 = (int)(Math.random() * 10);
    totalScore = 0;
    userScore = 0;
    input = new Scanner(System.in);
    System.out.print("What is " + number1 + " * " + number2 + "? ");
    int answer = input.nextInt();
    while (number1 * number2 != answer) {
        int answer1 = number1 * number2;
        System.out.println("Incorrect. The answer is " + answer1+".");
        System.out.print("Want more questions yes or no? ");
        scanner = new Scanner (System.in);
        question = scanner.next();
        break;
     }

    if (number1 * number2 == answer){
        System.out.println("Correct. Nice work!");
        System.out.print("Want more questions yes or no? ");
        scanner = new Scanner (System.in);
        question = scanner.next();
        }
    if (question.equals("no")||question.equals("n")&& (number1 * number2 == answer))
    {
        userScore++;
        totalScore++;
          System.out.println("You have this many questions correct:" + totalScore);
       }
}
   while(question.equals("yes") || question.equals("y"));
    }
 }
</code>```

Title: Asking multiplication questions and computing the total of answers correct in Java

Body:
Mistake was you opened '{' two times for 'if'statement -

if (question.equals("no")||question.equals("n")&& (number1 * number2 == answer)){
{

and forgot to close one bracket in last line.

Below code solves error due to brackets:

import java.util.Scanner;

public class Program3_3 {

private static String question;
private static Scanner input;
private static Scanner scanner;
private static int totalScore;
private static int answer1;
private static int userScore;

public static void main(String[] args) {
do {
    int number1 = (int)(Math.random() * 10);
    int number2 = (int)(Math.random() * 10);
    totalScore = 0;
    userScore = 0;
    input = new Scanner(System.in);
    System.out.print("What is " + number1 + " * " + number2 + "? ");
    int answer = input.nextInt();
    while (number1 * number2 != answer) {
        int answer1 = number1 * number2;
        System.out.println("Incorrect. The answer is " + answer1+".");
        System.out.print("Want more questions yes or no? ");
        scanner = new Scanner (System.in);
        question = scanner.next();
        break;
     }

    if (number1 * number2 == answer){
        System.out.println("Correct. Nice work!");
        System.out.print("Want more questions yes or no? ");
        scanner = new Scanner (System.in);
        question = scanner.next();
        }
    if (question.equals("no")||question.equals("n")&& (number1 * number2 == answer))
    {
        userScore++;
        totalScore++;
          System.out.println("You have this many questions correct:" + totalScore);
       }
}
   while(question.equals("yes") || question.equals("y"));
    }
 }


问:
Is there a way to ignore a test completely based on a condition (if a parameter does not exist in the test)
Below is my TestNG suite xml file.

```<code><test name="m_AggregatorTx">
            <parameter name="logFile" value="hadoopmslogs/${Domain_Name}/${NODENAME}/Hive_961/m_AggregatorTx.log"/>
            <classes>
                    <class name="executems.main.RunMS"></class>
            </classes>
    </test>

    <test name="m_alldt">
            <parameter name="logFile" value="hadoopmslogs/${Domain_Name}/${NODENAME}/Hive_961/m_alldt.log"/>
            <parameter name="enableUT" value="true"/>
            <classes>
                    <class name="executems.main.RunMS"></class>
            </classes>
    </test>

    <test name="m_alldt_cpx">
            <parameter name="logFile" value="hadoopmslogs/${Domain_Name}/${NODENAME}/Hive_961/m_alldt_cpx.log"/>
            <classes>
                    <class name="executems.main.RunMS"></class>
            </classes>
    </test>

<test name="m_alldt_custom_query_prop">
            <parameter name="logFile" value="hadoopmslogs/${Domain_Name}/${NODENAME}/Hive_961/m_alldt_custom_query_prop.log"/>
            <parameter name="enableUT" value="true"/>
            <classes>
                    <class name="executems.main.RunMS"></class>
            </classes>
    </test>
</code>```

In runtime, I want to ignore the tests which do not have enableUT parameter in it.
For example, in the above suite file m_AggregatorTx and m_alldt_cpx do not have enableUT parameter in them.

Note:
1. I do not want to add enabled=true/false to my suite xml. ( Because I have 30 different suite files which have 100 test cases each)
2. Currently during runtime, I am able to Skip these tests using throw new SkipException. But once a run finishes, the results comes as this:

===============================================
Hive_961

Total tests run: 4, Failures: 0, Skips: 2

I do not want the two cases to show up in the Skips section in the result. I want those cases to be ignored during run-time.
I want the result something like this:

===============================================
Hive_961

Total tests run: 2, Failures: 0, Skips: 0

```<code>if(enableBugB.equals("true"))
            {
                    System.out.println("enableBugB is set to true in this Test Case");
                    boolean result = Services.runMapping(applicationName, mappingName, database, runID);
                    if(runID != null && !runID.isEmpty())
                    {

                        VerifyMapping.compareResults(verifyXml, runID, logPath,result);
                    }
                    else
                    {

                        VerifyMapping.compareResults(verifyXml, mappingName, logPath,result);
                    }
                }
                else
                {
                    //System.out.println("enableBugB is not present for this Test. Hence skipping this Test Case..");
                    throw new SkipException("enableBugB is not enabled. Skipping this Test Case..");

                }
</code>```

Appreciate any help. Thanks.

答:
Yes, it is possible.

You will need to access test context.

Basically in testng.xml:

```<code><suite name="Parameter Checker">
    <listeners>
        <listener class-name="listeners.ParametrizedMethodInterceptor" />
    </listeners>

    <test name="Without Parameter">
        <classes>
            <class name="TestClass" />
        </classes>
    </test>

    <test name="With Parameter">
        <parameter name="Name of the Parameter" value="Value of the Parameter" />
        <classes>
            <class name="TestClass" />
        </classes>
    </test>
</suite>
</code>```

And then any listener that can catch the value of this parameter and runs before test. I have tried to do it with IAnnotationTransformer with reflection, but access to the value of parameter was not possible without method instantiation and there is no test context.

With IMethodInterceptor, however, it was simple:

```<code>public class ParametrizedMethodInterceptor implements IMethodInterceptor {

    @Override
    public List<IMethodInstance> intercept(List<IMethodInstance> list,
                                           ITestContext iTestContext) {
        String parameterValue = iTestContext
                .getCurrentXmlTest()
                .getParameter("Name of the Parameter");
        return (parameterValue != null)? list : new LinkedList<>();
    }
}
</code>```

Those intercepted methods have no dependents and do not depend on any other test methods.

Test class:

```<code>public class TestClass {

    @Test
    @Parameters("Name of the Parameter")
    public void testMethod(@Optional("unset") String parameter) {
        System.out.print("In testMethod. ");
        System.out.println("Parameter: " + parameter + ".");
    }
}
</code>```

Output:

```<code>In testMethod. Parameter: Value of the Parameter.

Test ignored.
</code>```

For the report generation try using two listeners:

```<code><listeners>
    <listener class-name="listeners.ParametrizedMethodInterceptor" />
    <listener class-name="listeners.ParametrizedReportListener" />
</listeners>
</code>```

and skip processing of test results without parameter:

```<code>public class ParametrizedReportListener implements IReporter {

    @Override
    public void generateReport(List<XmlSuite> xmlSuites,
                               List<ISuite> suites,
                               String outputDirectory) {
        for(ISuite suite : suites) {
            suite.getResults().values().stream()
                    .filter(result -> result
                            .getTestContext()
                            .getCurrentXmlTest()
                            .getParameter("Name of the Parameter") != null)
                    .forEach(result -> {
                        System.out.println("Parameter found!");
                        System.out.println("Output formatting here.");
                    });
        }
    }
}
</code>```

Body:
Below is my TestNG suite xml file.

<test name="m_AggregatorTx">
            <parameter name="logFile" value="hadoopmslogs/${Domain_Name}/${NODENAME}/Hive_961/m_AggregatorTx.log"/>
            <classes>
                    <class name="executems.main.RunMS"></class>
            </classes>
    </test>

    <test name="m_alldt">
            <parameter name="logFile" value="hadoopmslogs/${Domain_Name}/${NODENAME}/Hive_961/m_alldt.log"/>
            <parameter name="enableUT" value="true"/>
            <classes>
                    <class name="executems.main.RunMS"></class>
            </classes>
    </test>

    <test name="m_alldt_cpx">
            <parameter name="logFile" value="hadoopmslogs/${Domain_Name}/${NODENAME}/Hive_961/m_alldt_cpx.log"/>
            <classes>
                    <class name="executems.main.RunMS"></class>
            </classes>
    </test>

<test name="m_alldt_custom_query_prop">
            <parameter name="logFile" value="hadoopmslogs/${Domain_Name}/${NODENAME}/Hive_961/m_alldt_custom_query_prop.log"/>
            <parameter name="enableUT" value="true"/>
            <classes>
                    <class name="executems.main.RunMS"></class>
            </classes>
    </test>

In runtime, I want to ignore the tests which do not have enableUT parameter in it.
For example, in the above suite file m_AggregatorTx and m_alldt_cpx do not have enableUT parameter in them.

Note:
1. I do not want to add enabled=true/false to my suite xml. ( Because I have 30 different suite files which have 100 test cases each)
2. Currently during runtime, I am able to Skip these tests using throw new SkipException. But once a run finishes, the results comes as this:

===============================================
Hive_961

Total tests run: 4, Failures: 0, Skips: 2

I do not want the two cases to show up in the Skips section in the result. I want those cases to be ignored during run-time.
I want the result something like this:

===============================================
Hive_961

Total tests run: 2, Failures: 0, Skips: 0

if(enableBugB.equals("true"))
            {
                    System.out.println("enableBugB is set to true in this Test Case");
                    boolean result = Services.runMapping(applicationName, mappingName, database, runID);
                    if(runID != null && !runID.isEmpty())
                    {

                        VerifyMapping.compareResults(verifyXml, runID, logPath,result);
                    }
                    else
                    {

                        VerifyMapping.compareResults(verifyXml, mappingName, logPath,result);
                    }
                }
                else
                {
                    //System.out.println("enableBugB is not present for this Test. Hence skipping this Test Case..");
                    throw new SkipException("enableBugB is not enabled. Skipping this Test Case..");

                }

Appreciate any help. Thanks.

Body:
Yes, it is possible.

You will need to access test context.

Basically in testng.xml:

<suite name="Parameter Checker">
    <listeners>
        <listener class-name="listeners.ParametrizedMethodInterceptor" />
    </listeners>

    <test name="Without Parameter">
        <classes>
            <class name="TestClass" />
        </classes>
    </test>

    <test name="With Parameter">
        <parameter name="Name of the Parameter" value="Value of the Parameter" />
        <classes>
            <class name="TestClass" />
        </classes>
    </test>
</suite>

And then any listener that can catch the value of this parameter and runs before test. I have tried to do it with IAnnotationTransformer with reflection, but access to the value of parameter was not possible without method instantiation and there is no test context.

With IMethodInterceptor, however, it was simple:

public class ParametrizedMethodInterceptor implements IMethodInterceptor {

    @Override
    public List<IMethodInstance> intercept(List<IMethodInstance> list,
                                           ITestContext iTestContext) {
        String parameterValue = iTestContext
                .getCurrentXmlTest()
                .getParameter("Name of the Parameter");
        return (parameterValue != null)? list : new LinkedList<>();
    }
}

Those intercepted methods have no dependents and do not depend on any other test methods.

Test class:

public class TestClass {

    @Test
    @Parameters("Name of the Parameter")
    public void testMethod(@Optional("unset") String parameter) {
        System.out.print("In testMethod. ");
        System.out.println("Parameter: " + parameter + ".");
    }
}

Output:

In testMethod. Parameter: Value of the Parameter.

Test ignored.

For the report generation try using two listeners:

<listeners>
    <listener class-name="listeners.ParametrizedMethodInterceptor" />
    <listener class-name="listeners.ParametrizedReportListener" />
</listeners>

and skip processing of test results without parameter:

public class ParametrizedReportListener implements IReporter {

    @Override
    public void generateReport(List<XmlSuite> xmlSuites,
                               List<ISuite> suites,
                               String outputDirectory) {
        for(ISuite suite : suites) {
            suite.getResults().values().stream()
                    .filter(result -> result
                            .getTestContext()
                            .getCurrentXmlTest()
                            .getParameter("Name of the Parameter") != null)
                    .forEach(result -> {
                        System.out.println("Parameter found!");
                        System.out.println("Output formatting here.");
                    });
        }
    }
}


问:
Create script for test server
#!/usr/bin/env zsh
./client localhost 5000 Bryan (my command)

I would like to check if the parameter of my command is correct, in script zsh that means:

```<code>if
first argument = int
second argument = int
third argument = string
fi
</code>```

答:
Just to be clear, all of those conditions must be true for the script to continue, yes?  Also, note that "string" means pretty much any character (A-Z, 0-9, punctuation) -- anything other than control characters.  Assuming that is the case, how about something like this:

```<code>  re='^[0-9]+$'
  echo " "
  echo "Parm 1: $1"
  if ! [[ "$1" =~ $re ]]; then
     echo "The first parameter must be an integer."
     exit 1
  fi

  echo " "
  echo "Parm 2: $2"
  if ! [[ $2 =~ $re ]]; then
     echo "The second parameter must be an integer."
     exit 2
  fi

  re='^[[:graph:]]+$'
  echo " "
  echo "Parm 3: $3"
  if ! [[ $3 =~ $re ]]; then
     echo "The third parameter must be an string."
     exit 3
  fi
  echo " "
  echo "Congratulations -- your parms are valid\!"
  echo " "
</code>```

Edit: Here are some sample runs:

```<code>~/test1$
~/test1$./tmp 123 456 abdc

Parm 1: 123

Parm 2: 456

Parm 3: abdc

Congratulations -- your parms are valid\!

~/test1$./tmp abc 123 456

Parm 1: abc
The first parameter must be an integer.
~/test1$./tmp 12b 123 abc

Parm 1: 12b
The first parameter must be an integer.
~/test1$./tmp 123 4h5 abc

Parm 1: 123

Parm 2: 4h5
The second parameter must be an integer.
~/test1$./tmp 123 jkl asdf

Parm 1: 123

Parm 2: jkl
The second parameter must be an integer.
~/test1$
~/test1$
</code>```

Hope this helps!

Title: Create script for test server

Body:
#!/usr/bin/env zsh
./client localhost 5000 Bryan (my command)

I would like to check if the parameter of my command is correct, in script zsh that means:

if
first argument = int
second argument = int
third argument = string
fi

Body:
Just to be clear, all of those conditions must be true for the script to continue, yes?  Also, note that "string" means pretty much any character (A-Z, 0-9, punctuation) -- anything other than control characters.  Assuming that is the case, how about something like this:

  re='^[0-9]+$'
  echo " "
  echo "Parm 1: $1"
  if ! [[ "$1" =~ $re ]]; then
     echo "The first parameter must be an integer."
     exit 1
  fi

  echo " "
  echo "Parm 2: $2"
  if ! [[ $2 =~ $re ]]; then
     echo "The second parameter must be an integer."
     exit 2
  fi

  re='^[[:graph:]]+$'
  echo " "
  echo "Parm 3: $3"
  if ! [[ $3 =~ $re ]]; then
     echo "The third parameter must be an string."
     exit 3
  fi
  echo " "
  echo "Congratulations -- your parms are valid\!"
  echo " "

Edit: Here are some sample runs:

~/test1$
~/test1$./tmp 123 456 abdc

Parm 1: 123

Parm 2: 456

Parm 3: abdc

Congratulations -- your parms are valid\!

~/test1$./tmp abc 123 456

Parm 1: abc
The first parameter must be an integer.
~/test1$./tmp 12b 123 abc

Parm 1: 12b
The first parameter must be an integer.
~/test1$./tmp 123 4h5 abc

Parm 1: 123

Parm 2: 4h5
The second parameter must be an integer.
~/test1$./tmp 123 jkl asdf

Parm 1: 123

Parm 2: jkl
The second parameter must be an integer.
~/test1$
~/test1$

Hope this helps!


问:
Multiple button, multiple function, mutiple value flash as3
I want to make multiple button function with this function

```<code>for(var i=1; i <= 3; i++){this["btn"+i].addEventListener(MouseEvent.CLICK, someFunction);}
</code>```

then, every i clicked some button, i want it to trace some number that exactly same with [i]. Lets say i clicked 'btn1' then it trace '1'. What should i do? Thankyou. Beginner at flash.

答:
The key is knowing that event object, that is passed to subscribed methods also carries a reference to the source of the event.

```<code>function someFunction(e:Event):void
{
    // Get the reference to the button and access its name.
    var aButton:DisplayObject = e.currentTarget as DisplayObject;
    var aName:String = aButton.name;

    // If all the buttons are named in the way you put it:
    // Extract digits.
    var aDigits:String = aName.substr(3);

    // Convert them into number.
    var anIndex:int = int(aDigits);

    // Profit!
    trace(anIndex);
}
</code>```

UPD. As Vesper pointed out below, it needs some explanation.

There are two references in the event object: e.target and e.currentTarget, that might or might not be the same:

e.target is the original source of event

e.currentTarget is the object you subscribed the event handler to

Let us think how MouseEvent.CLICK occurs. You click a button. At the same time you click a MovieClip/Sprite that contains the button. All their parents. Finally, Stage. So the e:MouseEvent starts at the button so the button dispatches it, then it bubbles (this process is called bubbling, read this: Event Bubbling, and Stop Propagation) one level up, then button parent fires the event, and so on all the way up to stage.

There are also 2 properties that can change the result of event handling:

InteractiveObject.mouseEnabled allows or disallows the object to fire mouse events: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/InteractiveObject.html#mouseEnabled

DisplayObjectContainer.mouseChildren allows or disallows the mouse to interact with the container's display children: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/DisplayObjectContainer.html#mouseChildren

Body:
I want to make multiple button function with this function

for(var i=1; i <= 3; i++){this["btn"+i].addEventListener(MouseEvent.CLICK, someFunction);}

then, every i clicked some button, i want it to trace some number that exactly same with [i]. Lets say i clicked 'btn1' then it trace '1'. What should i do? Thankyou. Beginner at flash.

Body:
The key is knowing that event object, that is passed to subscribed methods also carries a reference to the source of the event.

function someFunction(e:Event):void
{
    // Get the reference to the button and access its name.
    var aButton:DisplayObject = e.currentTarget as DisplayObject;
    var aName:String = aButton.name;

    // If all the buttons are named in the way you put it:
    // Extract digits.
    var aDigits:String = aName.substr(3);

    // Convert them into number.
    var anIndex:int = int(aDigits);

    // Profit!
    trace(anIndex);
}

UPD. As Vesper pointed out below, it needs some explanation.

There are two references in the event object: e.target and e.currentTarget, that might or might not be the same:

e.target is the original source of event

e.currentTarget is the object you subscribed the event handler to

Let us think how MouseEvent.CLICK occurs. You click a button. At the same time you click a MovieClip/Sprite that contains the button. All their parents. Finally, Stage. So the e:MouseEvent starts at the button so the button dispatches it, then it bubbles (this process is called bubbling, read this: Event Bubbling, and Stop Propagation) one level up, then button parent fires the event, and so on all the way up to stage.

There are also 2 properties that can change the result of event handling:

InteractiveObject.mouseEnabled allows or disallows the object to fire mouse events: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/InteractiveObject.html#mouseEnabled

DisplayObjectContainer.mouseChildren allows or disallows the mouse to interact with the container's display children: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/DisplayObjectContainer.html#mouseChildren


问:
Populating a prototype cell with an array that's populated using Firebase
How would I fill the TableView Cell using Firebase? I'm trying to fill it using an array which would be filled by Firebase, but since the data is filled asynchronously, I don't know how to make the array filled with data outside of the getData() function. As of now the data is filled inside the completion handler, but outside of that it is nil.</p>

```<code>import UIKit
import Firebase

class ProxiesListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var ProxiesTableView: UITableView!

var proxyname:[String] = []
var proxyprice:[Int] = []
var proxycountry:[String] = []

var databaseRef : FIRDatabaseReference!

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return proxyname.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ProxiesTableViewCell
    cell.countryFlag.image = UIImage(named: proxycountry[indexPath.row])
    cell.NameLabel.text = proxyname[indexPath.row]
    cell.priceLabel.text = "$" + String(proxyprice[indexPath.row])
    return(cell)
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    //add code
}

override func viewDidLoad() {
    super.viewDidLoad()

    ProxiesTableView.delegate = self
    ProxiesTableView.dataSource = self

    getData()
}

func getData() {
    databaseRef = FIRDatabase.database().reference()

    /*
     proxyname = ["50 Proxies (24 Hours)", "100 Proxies", "10 Proxies", "60 Proxies (48 Hours)"]
     proxyprice = [600, 140, 60, 10]
     proxycountry = ["CA", "UK", "UK", "US"]
     */

    self.databaseRef.child("ProxiesItemsFeed").observe(.childAdded, with: { (snapshot) in

        if let proxynames = snapshot.key as String! {
            self.proxyname.append(proxynames)
                self.databaseRef.child("ProxiesItemsFeed").child(proxynames).observe(.childAdded, with: { (snapshot) in

                    if let country = snapshot.key as String! {
                        self.proxycountry.append(country)
                    }

                    if let price = snapshot.value as! Int! {
                        self.proxyprice.append(price)
                    }
                })
            }
        })
    }
}
</code>```

答:
You should add a tableView.reloadData() inside your completion handler (i.e., the one in your getData() method).

Method documentation:

Call this method to reload all the data that is used to construct the table, including cells, section headers and footers, index arrays, and so on.

Body:
How would I fill the TableView Cell using Firebase? I'm trying to fill it using an array which would be filled by Firebase, but since the data is filled asynchronously, I don't know how to make the array filled with data outside of the getData() function. As of now the data is filled inside the completion handler, but outside of that it is nil.

import UIKit
import Firebase

class ProxiesListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var ProxiesTableView: UITableView!

var proxyname:[String] = []
var proxyprice:[Int] = []
var proxycountry:[String] = []

var databaseRef : FIRDatabaseReference!

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return proxyname.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ProxiesTableViewCell
    cell.countryFlag.image = UIImage(named: proxycountry[indexPath.row])
    cell.NameLabel.text = proxyname[indexPath.row]
    cell.priceLabel.text = "$" + String(proxyprice[indexPath.row])
    return(cell)
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    //add code
}

override func viewDidLoad() {
    super.viewDidLoad()

    ProxiesTableView.delegate = self
    ProxiesTableView.dataSource = self

    getData()
}

func getData() {
    databaseRef = FIRDatabase.database().reference()

    /*
     proxyname = ["50 Proxies (24 Hours)", "100 Proxies", "10 Proxies", "60 Proxies (48 Hours)"]
     proxyprice = [600, 140, 60, 10]
     proxycountry = ["CA", "UK", "UK", "US"]
     */

    self.databaseRef.child("ProxiesItemsFeed").observe(.childAdded, with: { (snapshot) in

        if let proxynames = snapshot.key as String! {
            self.proxyname.append(proxynames)
                self.databaseRef.child("ProxiesItemsFeed").child(proxynames).observe(.childAdded, with: { (snapshot) in

                    if let country = snapshot.key as String! {
                        self.proxycountry.append(country)
                    }

                    if let price = snapshot.value as! Int! {
                        self.proxyprice.append(price)
                    }
                })
            }
        })
    }
}


问:
Middleware doesn't work as expected - Laravel
I want to make a middleware to protect admin routes in laravel 5.2 app.
user_type isn't a field in users table in my db, but in a separate table :

Admin's user_type_id is 4
I made this middleware :

```<code>class AdminMiddleware
{

    public function handle($request, Closure $next)
    {
        $authedUserID = Auth::id();

        $user = User::query()
                ->leftjoin('users_user_types as uut', 'uut.user_id', '=', 'users.id')
                ->where('uut.user_id',"=","$authedUserID")
                ->get(['users.*',
                        'uut.user_type_id as userType'])->first();

        if ($user['userType'] !=4)
        {

            return redirect('/home');
        }

        return $next($request);
    }
}
</code>```

and put this in $routeMiddleware array in kernel.php :

```<code>'admin' => \App\Http\Middleware\AdminMiddleware::class
</code>```

and this is one of admin routes I want to apply my middleware on :

```<code>Route::get('ptyadmin', 'AdminController@show')->middleware('admin');
</code>```

The Problem is that when I go to this route with admin user(user_type = 4) or normal user(user_type = 1) it redirects to /home in both cases !!

Why does this happen and how can I fix it ??

答:
first method returns object

```<code>if ($user->userType !=4)
</code>```

Also use selectinstead get

```<code>->select(['users.*','uut.user_type_id as userType'])->first();
</code>```

Body:
I want to make a middleware to protect admin routes in laravel 5.2 app.
user_type isn't a field in users table in my db, but in a separate table :

Admin's user_type_id is 4
I made this middleware :

class AdminMiddleware
{

    public function handle($request, Closure $next)
    {
        $authedUserID = Auth::id();

        $user = User::query()
                ->leftjoin('users_user_types as uut', 'uut.user_id', '=', 'users.id')
                ->where('uut.user_id',"=","$authedUserID")
                ->get(['users.*',
                        'uut.user_type_id as userType'])->first();

        if ($user['userType'] !=4)
        {

            return redirect('/home');
        }

        return $next($request);
    }
}

and put this in $routeMiddleware array in kernel.php :

'admin' => \App\Http\Middleware\AdminMiddleware::class

and this is one of admin routes I want to apply my middleware on :

Route::get('ptyadmin', 'AdminController@show')->middleware('admin');

The Problem is that when I go to this route with admin user(user_type = 4) or normal user(user_type = 1) it redirects to /home in both cases !!

Why does this happen and how can I fix it ??

Body:
first method returns object

if ($user->userType !=4)

Also use selectinstead get

->select(['users.*','uut.user_type_id as userType'])->first();


答:
Perhaps you are looking for:

```<code>len(counts.keys())
</code>```

If not, some more context surrounding your problem would help to find a solution. Also, it looks like you could save quite a bit of code repetition by storing those min/max data points in a list of dictionaries and condense those comparison statements into a single loop. Something along the lines of:

```<code>data = [{'x-min': 0, 'x-max': 1, 'y-min': 0, 'y-max': 1, 'count': 0}, ...]

def within_threshold(x1, y1, point):
    within_x = x >= point['x-min'] and x <= point['x-max']
    within_y = y >= point['y-min'] and y <= point['y-max']
    return within_x and within_y

def compare(x, y):
    for point in data:
        if within_threshold(x, y, point):
            point['count'] += 1
</code>```

Body:
Here is my code, i know it isn't clean enough, but it cannot run as I thought, anyone can help me?

I fixed it, thank you for your helps

The general idea of this code is comparing each coordinate with a range, and calculate the amounts of points for each grid

the result is:
{'other': 862, 'B4': 2, 'D5': 1, 'A1': 0, 'D4': 2, 'A3': 2, 'A2': 2, 'A4': 0, 'B2': 36, 'B3': 8, 'C3': 15, 'C2': 50, 'C1': 1, 'C4': 7, 'D3': 4, 'C5': 1, 'B1': 7}

I don't know why 'other' get so much

 import json
    from pprint import pprint
    xa1_min = 144.700000
    xa1_max = 144.850000
    ya1_min = -37.650000
    ya1_max = -37.500000

    xa2_min = 144.850000
    xa2_max = 145.000000
    ya2_min = -37.650000
    ya2_max = -37.500000

    xa3_min = 145.000000
    xa3_max = 145.150000
    ya3_min = -37.650000
    ya3_max = -37.500000

    xa4_min =145.150000
    xa4_max =145.300000
    ya4_min =-37.650000
    ya4_max =-37.500000

    xb1_min =144.700000
    xb1_max =144.850000
    yb1_min =-37.800000
    yb1_max =-37.650000

    xb2_min =144.850000
    xb2_max =145.000000
    yb2_min =-37.800000
    yb2_max =-37.650000

    xb3_min =145.000000
    xb3_max =145.150000
    yb3_min =-37.800000
    yb3_max =-37.650000

    xb4_min =145.150000
    xb4_max =145.300000
    yb4_min =-37.800000
    yb4_max =-37.650000

    xc1_min =144.700000
    xc1_max =144.850000
    yc1_min =-37.950000
    yc1_max =-37.800000

    xc2_min =144.850000
    xc2_max =145.000000
    yc2_min =-37.950000
    yc2_max =-37.800000

    xc3_min =145.000000
    xc3_max =145.150000
    yc3_min =-37.950000
    yc3_max =-37.800000

    xc4_min =145.150000
    xc4_max =145.300000
    yc4_min = -37.950000
    yc4_max = -37.800000

    xc5_min =145.300000
    xc5_max =145.450000
    yc5_min =-37.950000
    yc5_max =-37.800000

    xd3_min =145.000000
    xd3_max =145.150000
    yd3_min =-38.100000
    yd3_max =-37.950000

    xd4_min =145.150000
    xd4_max =145.300000
    yd4_min =-38.100000
    yd4_max =-37.950000

    xd5_min =145.300000
    xd5_max =145.450000
    yd5_min =-38.100000
    yd5_max =-37.950000
    #["properties"]['ID']
    # Reading from grid
    with open('tinyTwitter.json') as load_f:
        info = json.load(load_f)

    coordinates = list()
    #print info

    for line in info:
        #print line['json']['coordinates']['coordinates']
        coordinates.append(line['json']['coordinates']['coordinates'])

    #print coordinates[0][1]
    #print coordinates[0][0]

    counts = {'A1':0,'A2':0,'A3':0,'A4':0,'B1':0,'B2':0,'B3':0,'B4':0,'C1':0,'C2':0,'C3':0,'C4':0,'C5':0,'D3':0,'D4':0,'D5':0,'other':0}
    #comparing
    def compare(x,y):

    if xa1_min <= x <= xa1_max and ya1_min <= y <= ya1_max:
        counts['A1'] +=1

    elif xa2_min <= x <= xa2_max and ya2_min <=y<= ya2_max:
        counts['A2'] +=1

    elif xa3_min <= x <= xa3_max and ya3_min <=y<= ya3_max:
        counts['A3'] +=1

    elif xa4_min <= x <= xa4_max and ya4_min <=y<= ya4_max:
        counts['A4'] += 1

    elif xb1_min <= x <= xb1_max and yb1_min <=y<= yb1_max:
        counts['B1'] += 1

    elif xb2_min <= x <= xb2_max and yb2_min <=y<= yb2_max:
        counts['B2'] += 1

    elif xb3_min <= x <= xb3_max and yb3_min <=y<= yb3_max:
        counts['B3'] += 1

    elif xb4_min <= x <= xb4_max and yb4_min <=y<= yb4_max:
        counts['B4'] += 1

    elif xc1_min <= x <= xc1_max and yc1_min <=y<= yc1_max:
        counts['C1'] += 1

    elif xc2_min <= x <= xc2_max and yc2_min <=y<= yc2_max:
        counts['C2'] += 1

    elif xc3_min <= x <= xc3_max and yc3_min <=y<= yc3_max:
        counts['C3'] += 1

    elif xc4_min <= x <= xc4_max and yc4_min <=y<= yc4_max:
        counts['C4'] += 1

    elif xc5_min <= x <= xc5_max and yc5_min <=y<= yc5_max:
        counts['C5'] += 1

    elif xd3_min <= x <= xd3_max and yd3_min <=y<= yd3_max:
        counts['D3'] += 1

    elif xd4_min <= x <= xd4_max and yd4_min <=y<= yd4_max:
        counts['D4'] += 1

    elif xd5_min <= x <= xd5_max and yd5_min <=y<= yd5_max:
        counts['D5'] += 1

    else:
        counts['other']+= 1

        #print counts

    for i,j in coordinates:
        #print i,j
        compare(i,j)
    print counts

Body:
Perhaps you are looking for:

len(counts.keys())

If not, some more context surrounding your problem would help to find a solution. Also, it looks like you could save quite a bit of code repetition by storing those min/max data points in a list of dictionaries and condense those comparison statements into a single loop. Something along the lines of:

data = [{'x-min': 0, 'x-max': 1, 'y-min': 0, 'y-max': 1, 'count': 0}, ...]

def within_threshold(x1, y1, point):
    within_x = x >= point['x-min'] and x <= point['x-max']
    within_y = y >= point['y-min'] and y <= point['y-max']
    return within_x and within_y

def compare(x, y):
    for point in data:
        if within_threshold(x, y, point):
            point['count'] += 1


问:
ErrorAccessDenied on https://graph.microsoft.com/v1.0/me/messages
Trying to use the ms graph api and keep getting this error on selected endpoints including v1.0/me/messages.

Looks like a simple issue with privileges (unsure why user would not have privilege to access own emails??), but what is confusing me is that when I sign on with the same Office365 credentials and access the same endpoint on developer.microsoft.com/en-us/graph/graph-explorer it works OK.

Not an authentication token issue as exact same request to v1.0/me endpoint works fine.

Debugging using curl from server :

```<code>curl -H "Authorization: Bearer eyJ0e.....dRcgg"
https://graph.microsoft.com/v1.0/me
</code>```

I get a good result, same request to /v1.0/me/messages endpoint results in :

```<code>{
  "error": {
    "code": "ErrorAccessDenied",
    "message": "Access is denied. Check credentials and try again.",
    "innerError": {
      "request-id": "019d61ff-77fd-4e9f-a94e-38faf741ac33",
      "date": "2017-04-02T00:04:16"
    }
  }
}
</code>```

To repeat, the issue that is throwing me is that I am able to access this endpoint successfully with the same credentials from developer.microsoft.com/en-us/graph/graph-explorer

答:
OK, have resolved the issue so posting here for the benefit of anyone else with the same issue.

It is all about the scope requested on the authentication request.  Had copied a code sample and it was only requesting scope:-

scope: 'User.Read Mail.Send offline_access'

Hence the Access Denied when I went outside this scope.....rookie error!

Body:
Trying to use the ms graph api and keep getting this error on selected endpoints including v1.0/me/messages.

Looks like a simple issue with privileges (unsure why user would not have privilege to access own emails??), but what is confusing me is that when I sign on with the same Office365 credentials and access the same endpoint on developer.microsoft.com/en-us/graph/graph-explorer it works OK.

Not an authentication token issue as exact same request to v1.0/me endpoint works fine.

Debugging using curl from server :

curl -H "Authorization: Bearer eyJ0e.....dRcgg"
https://graph.microsoft.com/v1.0/me

I get a good result, same request to /v1.0/me/messages endpoint results in :

{
  "error": {
    "code": "ErrorAccessDenied",
    "message": "Access is denied. Check credentials and try again.",
    "innerError": {
      "request-id": "019d61ff-77fd-4e9f-a94e-38faf741ac33",
      "date": "2017-04-02T00:04:16"
    }
  }
}

To repeat, the issue that is throwing me is that I am able to access this endpoint successfully with the same credentials from developer.microsoft.com/en-us/graph/graph-explorer


问:
How to count vowels and consonants in Python?
I am trying to write a program that counts vowels and consonants in Python, then print the number of vowels and consonants in two statements. The vowels and consonants have to be in two different functions. I have most of it complete but I cannot figure out two errors.

1.) How to stop my script from printing a new line for each count of the vowels. I have tried numerous variations of accumulators and print statements but none seem to work.

2.) I cannot get my countConsonants function to run at all. I am assuming I would have similar problems to number one but I cannot get it to even run. I am assuming it has to do with the way I am calling the function from the main function but I am not sure.

Here is what I have:

```<code>def main():
   user_input = input("Enter a string of vowels and consonants: ")
   vowel_list = set(['a','e','i','o','u'])
   countVowels(user_input, vowel_list)
   countConsonants(user_input, vowel_list)

def countVowels(user_input, vowel_list):
    user_input.lower()
    index = 0
    vowels = 0

    while index < len(user_input):
        if user_input[index] in vowel_list:
            vowels += 1
            index += 1
            print ('Your input has', vowels , 'vowels.')

def countConsonants(user_input, vowel_list):
    user_input.lower()
    index = 0
    consonants = 0

    while index < len(user_input):
        if user_input[index] not in vowel_list:
            consonants += 1
            index += 1
            print ('Your input has' , consonants , 'consonants.')

main()
</code>```

Here is an IO:

```<code>Enter a string of vowels and consonants: aaeioulkjj
Your input has 1 vowels.
Your input has 2 vowels.
Your input has 3 vowels.
Your input has 4 vowels.
Your input has 5 vowels.
Your input has 6 vowels.
</code>```

答:
I read through your code and found a couple issues. You seem to not be calling .lower in the right spot.  It doesn't modify the string, it simply returns a lowercase version of the string.  And i combined your vowels and consonants with a little math. Additionally, I added a conditional for loop that will scan through the letters and pick all the vowels out, then it will take the length of the vowel list found.  Finally, I also just combined vowel_list into a string to make it look prettier.

```<code>  def main():
     user_input = input("Enter a string of vowels and consonants: ").lower()
     vowel_list = 'aeiou'
     countVowelsAndConsoants(user_input, vowel_list)

  def countVowelsAndConsoants(user_input, vowel_list):
      vowels = len([char for char in user_input if char in vowel_list])
      print ('Your input has', vowels , 'vowels.')
      print ('Your input has', len(user_input)-vowels, 'consonants.')

  main()
</code>```

If you need them both separate:

```<code>  def main():
     user_input = input("Enter a string of vowels and consonants: ").lower()
     vowel_list = 'aeiou'
     countVowels(user_input, vowel_list)
     countConsonants(user_input, vowel_list)

  def countVowels(user_input, vowel_list):
     vowels = len([char for char in user_input if char in vowel_list])
     print ('Your input has', vowels , 'vowels.')

  def countConsonants(user_input, vowel_list):
     vowels = len([char for char in user_input if char in vowel_list])
     print ('Your input has', len(user_input)-vowels, 'consonants.')

  main()
</code>```

Body:
I am trying to write a program that counts vowels and consonants in Python, then print the number of vowels and consonants in two statements. The vowels and consonants have to be in two different functions. I have most of it complete but I cannot figure out two errors.

1.) How to stop my script from printing a new line for each count of the vowels. I have tried numerous variations of accumulators and print statements but none seem to work.

2.) I cannot get my countConsonants function to run at all. I am assuming I would have similar problems to number one but I cannot get it to even run. I am assuming it has to do with the way I am calling the function from the main function but I am not sure.

Here is what I have:

def main():
   user_input = input("Enter a string of vowels and consonants: ")
   vowel_list = set(['a','e','i','o','u'])
   countVowels(user_input, vowel_list)
   countConsonants(user_input, vowel_list)

def countVowels(user_input, vowel_list):
    user_input.lower()
    index = 0
    vowels = 0

    while index < len(user_input):
        if user_input[index] in vowel_list:
            vowels += 1
            index += 1
            print ('Your input has', vowels , 'vowels.')

def countConsonants(user_input, vowel_list):
    user_input.lower()
    index = 0
    consonants = 0

    while index < len(user_input):
        if user_input[index] not in vowel_list:
            consonants += 1
            index += 1
            print ('Your input has' , consonants , 'consonants.')

main()

Here is an IO:

Enter a string of vowels and consonants: aaeioulkjj
Your input has 1 vowels.
Your input has 2 vowels.
Your input has 3 vowels.
Your input has 4 vowels.
Your input has 5 vowels.
Your input has 6 vowels.

Body:
I read through your code and found a couple issues. You seem to not be calling .lower in the right spot.  It doesn't modify the string, it simply returns a lowercase version of the string.  And i combined your vowels and consonants with a little math. Additionally, I added a conditional for loop that will scan through the letters and pick all the vowels out, then it will take the length of the vowel list found.  Finally, I also just combined vowel_list into a string to make it look prettier.

  def main():
     user_input = input("Enter a string of vowels and consonants: ").lower()
     vowel_list = 'aeiou'
     countVowelsAndConsoants(user_input, vowel_list)

  def countVowelsAndConsoants(user_input, vowel_list):
      vowels = len([char for char in user_input if char in vowel_list])
      print ('Your input has', vowels , 'vowels.')
      print ('Your input has', len(user_input)-vowels, 'consonants.')

  main()

If you need them both separate:

  def main():
     user_input = input("Enter a string of vowels and consonants: ").lower()
     vowel_list = 'aeiou'
     countVowels(user_input, vowel_list)
     countConsonants(user_input, vowel_list)

  def countVowels(user_input, vowel_list):
     vowels = len([char for char in user_input if char in vowel_list])
     print ('Your input has', vowels , 'vowels.')

  def countConsonants(user_input, vowel_list):
     vowels = len([char for char in user_input if char in vowel_list])
     print ('Your input has', len(user_input)-vowels, 'consonants.')

  main()


问:
Text classification. TFIDF and Naive Bayes?
I'm attempting a text classification task, where I have training data of around 500 restaurant reviews that are labelled across 12 categories. I spent longer than I should have implementing TF.IDF and cosine similarity for the classification of test data, only to get some very poor results (0.4 F-measure). With time not on my side now, I need to implement something significantly more effective that doesn't have a steep learning curve. I am considering using the TF.IDF values in conjunction with Naive Bayes. Does this sound sensible? I know if I can get my data in the right format, I can do this with Scikit learn. Is there anything else you recommend I consider?

Thank you.

答:
You should try to use fasttext: https://pypi.python.org/pypi/fasttext . It can be used to classify text like this:

(don't forget to download a pretrained model here https://s3-us-west-1.amazonaws.com/fasttext-vectors/wiki.en.zip by changing the language if it's not english)

```<code>import fasttext

model = fasttext.load_model('wiki.en.bin')  # the name of the pretrained model

classifier = fasttext.supervised('train.txt', 'model', label_prefix='__label__')

result = classifier.test('test.txt')
print ('P@1:', result.precision)
print ('R@1:', result.recall)
print ('Number of examples:', result.nexamples)
</code>```

Every line in your training and test sets should be like this:

__label__classname Your restaurant review blah blah blah

Body:
You should try to use fasttext: https://pypi.python.org/pypi/fasttext . It can be used to classify text like this:

(don't forget to download a pretrained model here https://s3-us-west-1.amazonaws.com/fasttext-vectors/wiki.en.zip by changing the language if it's not english)

import fasttext

model = fasttext.load_model('wiki.en.bin')  # the name of the pretrained model

classifier = fasttext.supervised('train.txt', 'model', label_prefix='__label__')

result = classifier.test('test.txt')
print ('P@1:', result.precision)
print ('R@1:', result.recall)
print ('Number of examples:', result.nexamples)

Every line in your training and test sets should be like this:

__label__classname Your restaurant review blah blah blah


问:
Time format weird behavior
This is a part of a bigger code. I am little confused that if I use any other digit in the below format it results in wrong values.

so instead of

```<code>fmt.Println(time.Now().Format("2006-01-02 15:04:05-07:00"))
</code>```

if I try to use

```<code> fmt.Println(time.Now().Format("2006-01-02 12:04:05-04:00"))
</code>```

Result is wrong. Even when it is same format, just digit change

```<code>package main

import (
    "fmt"
    "time"
)

func main() {

    fmt.Println(time.Now().Format("2006-01-02 15:04:05-07:00"))

}
</code>```

So my question is why is it so. Digits inside format have no meaning. They are just for representation of the format.

答:
From https://golang.org/pkg/time/:

func (Time) Format

func (t Time) Format(layout string) string

Format returns a textual representation of the time value formatted
  according to layout, which defines the format by showing how the
  reference time, defined to be

Mon Jan 2 15:04:05 -0700 MST 2006

would be displayed if it were the value;

So you must use the reference time. You should not change it to another time.

Title: Time format weird behavior

Body:
This is a part of a bigger code. I am little confused that if I use any other digit in the below format it results in wrong values.

so instead of

fmt.Println(time.Now().Format("2006-01-02 15:04:05-07:00"))

if I try to use

 fmt.Println(time.Now().Format("2006-01-02 12:04:05-04:00"))

Result is wrong. Even when it is same format, just digit change

package main

import (
    "fmt"
    "time"
)

func main() {

    fmt.Println(time.Now().Format("2006-01-02 15:04:05-07:00"))

}

So my question is why is it so. Digits inside format have no meaning. They are just for representation of the format.


问:
How do I paste multi-line bash codes into terminal and run it all at once?
I need to paste a multi-line bash code into terminal, but whenever I do, each line gets run as a separate command as soon as it gets pasted.</p>

答:
I'm really surprised this answer isn't offered here, I was in search of a solution to this question and I think this is the easiest approach, and more flexible/forgiving...

If you'd like to paste multiple lines from a website/text editor/etc., into bash, regardless of whether it's commands per line or a function or entire script... simply start with a ( and end with a ) and Enter, like in the following example:

If I had the following blob

```<code>function hello {
    echo Hello!
}
hello
</code>```

You can paste and verify in a terminal using bash by:

Starting with (

Pasting your text, and pressing Enter (to make it pretty)... or not

Ending with a ) and pressing Enter

Example:

```<code>imac:~ home$ ( function hello {
>     echo Hello!
> }
> hello
> )
Hello!
imac:~ home$
</code>```

The pasted text automatically gets continued with a prepending > for each line. I've tested with multiple lines with commands per line, functions and entire scripts. Hope this helps others save some time!

Body:
I'm really surprised this answer isn't offered here, I was in search of a solution to this question and I think this is the easiest approach, and more flexible/forgiving...

If you'd like to paste multiple lines from a website/text editor/etc., into bash, regardless of whether it's commands per line or a function or entire script... simply start with a ( and end with a ) and Enter, like in the following example:

If I had the following blob

function hello {
    echo Hello!
}
hello

You can paste and verify in a terminal using bash by:

Starting with (

Pasting your text, and pressing Enter (to make it pretty)... or not

Ending with a ) and pressing Enter

Example:

imac:~ home$ ( function hello {
>     echo Hello!
> }
> hello
> )
Hello!
imac:~ home$

The pasted text automatically gets continued with a prepending > for each line. I've tested with multiple lines with commands per line, functions and entire scripts. Hope this helps others save some time!


答:
Indentation is key.

The print should only happen after the while loop is done, so it must be indented the same as the while. The increment of the index is in the wrong spot as well: this must happen each time regardless of whether or not the if condition evaluates to True. (With your alignment, the index only increases past vowels and may never get far enough to allow the while loop to end; this is why you never got to countConsonants.)

Your countVowels function then becomes:

```<code>def countVowels(user_input, vowel_list):
    index = 0
    vowels = 0

    while index < len(user_input):
        if user_input[index] in vowel_list:
            vowels += 1
        index += 1
    print ('Your input has', vowels , 'vowels.')
</code>```

By the way, consider using a for loop here over the characters in user_input instead of while and indexing; i.e. use something like:

```<code>for char in user_input:
    if char in vowel_list:
        vowels += 1
</code>```

Title: How to count vowels and consonants in Python?

Body:
Indentation is key.

The print should only happen after the while loop is done, so it must be indented the same as the while. The increment of the index is in the wrong spot as well: this must happen each time regardless of whether or not the if condition evaluates to True. (With your alignment, the index only increases past vowels and may never get far enough to allow the while loop to end; this is why you never got to countConsonants.)

Your countVowels function then becomes:

def countVowels(user_input, vowel_list):
    index = 0
    vowels = 0

    while index < len(user_input):
        if user_input[index] in vowel_list:
            vowels += 1
        index += 1
    print ('Your input has', vowels , 'vowels.')

By the way, consider using a for loop here over the characters in user_input instead of while and indexing; i.e. use something like:

for char in user_input:
    if char in vowel_list:
        vowels += 1