问:
RewriteRule not matching?
I have this in my .htaccess:

```<code>RewriteEngine On
RewriteBase /
RewriteRule ^url/(.*)$ url.php?url=$1 [L]
RewriteRule ^(.*)$ index.php?url=$1 [L,QSA]
</code>```

Why does http://mydomain.ext/url/http://www.google.com/ not match the first rule, but the second???

Edit: it seems to work when I comment out the last line, but of course i cannot do that. What's going on?

Edit2: If i change it to this it works:

```<code>RewriteEngine On
RewriteBase /
RewriteRule ^url/(.*)$ url.php?url=$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1 [L,QSA]
</code>```

Can anyone explain why the previous version didn't work as expected?

答:
The request is probably getting rewritten twice: /url/http://… → /url.php → /index.php. Exclude that path from the second rule and it should work:

```<code>RewriteCond $1 !=url.php
RewriteRule ^(.*)$ index.php?url=$1 [L,QSA]
</code>```

Title: RewriteRule not matching?

Body:
I have this in my .htaccess:

RewriteEngine On
RewriteBase /
RewriteRule ^url/(.*)$ url.php?url=$1 [L]
RewriteRule ^(.*)$ index.php?url=$1 [L,QSA]

Why does http://mydomain.ext/url/http://www.google.com/ not match the first rule, but the second???

Edit: it seems to work when I comment out the last line, but of course i cannot do that. What's going on?

Edit2: If i change it to this it works:

RewriteEngine On
RewriteBase /
RewriteRule ^url/(.*)$ url.php?url=$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1 [L,QSA]

Can anyone explain why the previous version didn't work as expected?

Body:
The request is probably getting rewritten twice: /url/http://… → /url.php → /index.php. Exclude that path from the second rule and it should work:

RewriteCond $1 !=url.php
RewriteRule ^(.*)$ index.php?url=$1 [L,QSA]


来源: stackexchange

问:
DAX TOPN Filter Not Returning Enough Rows
I'm trying to apply a TOPN() visual filter to a Power BI sheet based on an Average Loan Amount measure. I want to see the top 5 employees with the highest average loan amount, ignoring employees who have disbursed 4 or fewer loans.

The problem I'm running into is that I don't get 5 rows returned, even though I've selected the top 5. I have to adjust the "TOPN" parameter (in the visuals) to include more than 5, just to get 5 rows.

This seems to be because when I have both the TOP5 average AND the loan count > 4 filters working, neither updates the other; that is, I can find the top 5 rows based on the average parameter, but once I include the "loan count > 4" condition, a few of the top 5 disappear, and they're not replaced by the runners-up to the original 5.

In the past, when I placed a top 5 filter for average and nothing came up, it was because all the top 5 entries all had a loan count of under 5. Once I relaxed the "TOPN" condition to be "TOP 52," I got 5 entries visible.

Does anyone know why this happens & how to fix it so I always get 5 rows returned?

EDITED TO ADD: For an example of the data, please click here. Please note that any employee with a loan count of 4 or less should be filtered out. I created the filter in PowerBI because the data sets are dynamic, and so are the filter results.

答:
The fundamental problem is that you're applying 2 filters to the same visualization:

You only want to include employee's with a loan count of 5 or more

Of those, you want the 5 employees with the highest average loan amount

Power BI is applying both filters independently. So, it is taking the 5 employees with the highest average loan amount, and then removing 3 of them because their loan count is less than 5. I can imagine this is a common problem for people working with a Top N filter plus another filter.

One way to work around this (and I don't claim this is the only or even the best way), is to take into account the loan count before calculating the average.

For example, assuming you have the following two measures and the following data:

```<code>Loan Count = DISTINCTCOUNT(Employee[Loan Number])
Avg Loan Amt = AVERAGE(Employee[Loan Amount])
</code>```

It's clear from the picture that Liz, Montgomery and Oscar are in the top 5 but have only 3 loans to their name.

Next, we can create a new measure that checks the Loan Count before calculating the average loan amount. If the loan count doesn't meet the threshold, you don't care about their average.

```<code>*Filtered Avg Loan Amt =  IF([Loan Count] < 5, BLANK(), [Avg Loan Amt])
</code>```

This creates the following result. Notice that Liz, Montgomery & Oscar now all have no average calculated because they don't have enough loans.

Now, you don't necessarily have to display the Filtered Avg Loan Amt measure on your table, but you can now use that measure in your Top N visual filter and that, by itself, will filter your table to the top 5 employees with a high enough loan count.

Notice that in my filters, I only have 1 filter (on Filtered Avg Loan Amt). I don't also need to filter to a loan count of 5 or greater. This results in the following top 5 employees:

I hope this solves the problem you're having!

Unrelated sidenote: if you're using this threshold of 5 in a few places, I would recommend sourcing the number from an external source (including possibly a disconnected table) rather than hard-coding 5 in the measure itself. That way, if someone decides that 5 isn't the right threshold, you only have to update it one place, rather than hunting through all your measures looking for the number 5. There's an article here on using a disconnected table so that end-users can pick the threshold themselves (though it could definitely be overkill for your situation): https://powerpivotpro.com/2013/08/moving-averages-controlled-by-slicer/

ContentLicense: CC BY-SA 3.0

Body:
The fundamental problem is that you're applying 2 filters to the same visualization:

You only want to include employee's with a loan count of 5 or more

Of those, you want the 5 employees with the highest average loan amount

Power BI is applying both filters independently. So, it is taking the 5 employees with the highest average loan amount, and then removing 3 of them because their loan count is less than 5. I can imagine this is a common problem for people working with a Top N filter plus another filter.

One way to work around this (and I don't claim this is the only or even the best way), is to take into account the loan count before calculating the average.

For example, assuming you have the following two measures and the following data:

Loan Count = DISTINCTCOUNT(Employee[Loan Number])
Avg Loan Amt = AVERAGE(Employee[Loan Amount])

It's clear from the picture that Liz, Montgomery and Oscar are in the top 5 but have only 3 loans to their name.

Next, we can create a new measure that checks the Loan Count before calculating the average loan amount. If the loan count doesn't meet the threshold, you don't care about their average.

*Filtered Avg Loan Amt =  IF([Loan Count] < 5, BLANK(), [Avg Loan Amt])

This creates the following result. Notice that Liz, Montgomery & Oscar now all have no average calculated because they don't have enough loans.

Now, you don't necessarily have to display the Filtered Avg Loan Amt measure on your table, but you can now use that measure in your Top N visual filter and that, by itself, will filter your table to the top 5 employees with a high enough loan count.

Notice that in my filters, I only have 1 filter (on Filtered Avg Loan Amt). I don't also need to filter to a loan count of 5 or greater. This results in the following top 5 employees:

I hope this solves the problem you're having!

Unrelated sidenote: if you're using this threshold of 5 in a few places, I would recommend sourcing the number from an external source (including possibly a disconnected table) rather than hard-coding 5 in the measure itself. That way, if someone decides that 5 isn't the right threshold, you only have to update it one place, rather than hunting through all your measures looking for the number 5. There's an article here on using a disconnected table so that end-users can pick the threshold themselves (though it could definitely be overkill for your situation): https://powerpivotpro.com/2013/08/moving-averages-controlled-by-slicer/


问:
How to change JSON format to expected format in PHP
How to change JSON format to expected format

JSON

```<code>[{
    "storenm": "S1",
    "FA_SOH": "20964",
    "FA_CY_QTY": "15",
    "FA_CT_QTY": "44497"
},
{
    "storenm": "S2",
    "FA_SOH": "1096",
    "FA_CY_QTY": "2",
    "FA_CT_QTY": "7501"
}];
</code>```

Expected

```<code>[['S1',
'20964',
'15',
'44497'],
['S2',
'1096',
'2',
'7501']];
</code>```

答: You can use json_decode($json,true) to get an an array, then use array_values() to remove the keys and then transform it back to json with json_encode($newarray)</p>

Body:
How to change JSON format to expected format

JSON

[{
    "storenm": "S1",
    "FA_SOH": "20964",
    "FA_CY_QTY": "15",
    "FA_CT_QTY": "44497"
},
{
    "storenm": "S2",
    "FA_SOH": "1096",
    "FA_CY_QTY": "2",
    "FA_CT_QTY": "7501"
}];

Expected

[['S1',
'20964',
'15',
'44497'],
['S2',
'1096',
'2',
'7501']];


问:
Why is this Python function not working?
Keeps returning "You are older than some hills" even if i input less than 30</p>

```<code>age = raw_input("What age are you?")
def old(n):
  if n >= 30:
    print "You are older than some hills"
  else:
    print "Youth"

old(age)
</code>```

答:
As others have said, you need to convert the input to an integer. However, if the user inputs a letter, the program will throw an error. To make sure this doesn't happen, I would recommend getting the input using try and except, this can be done as follows:</p>

```<code>age = raw_input("What age are you?")
try:
    int(age)
except ValueError:
    print('That is not a number')
</code>```

Body:
Keeps returning "You are older than some hills" even if i input less than 30

age = raw_input("What age are you?")
def old(n):
  if n >= 30:
    print "You are older than some hills"
  else:
    print "Youth"

old(age)

Body:
As others have said, you need to convert the input to an integer. However, if the user inputs a letter, the program will throw an error. To make sure this doesn't happen, I would recommend getting the input using try and except, this can be done as follows:

age = raw_input("What age are you?")
try:
    int(age)
except ValueError:
    print('That is not a number')


问:
Ruby on Rails: Array to Hash with (key, array of values)
Lets say I have an Array of content_categories (content_categories = user.content_categories)

I now want to add every element belonging to a certain categorie to content_categories with the category as a key and the the content-item IDs as elements of a set

In PHP something like this is possible:

```<code>foreach ($content_categories as $key => $category) {
  $contentsByCategoryIDArray = Category.getContents($category[id])
  $content_categories[$key][$contentsByCategoryIDArray]
}
</code>```

Is there an easy way in rails to do this?

Greets,

Nico

答:
```<code>content_categories.each do |k,v|
  content_categories[k] = Category.getContents(v)
end
</code>```

I suppose it's works

ContentLicense: CC BY-SA 2.5

Body:
Lets say I have an Array of content_categories (content_categories = user.content_categories)

I now want to add every element belonging to a certain categorie to content_categories with the category as a key and the the content-item IDs as elements of a set

In PHP something like this is possible:

foreach ($content_categories as $key => $category) {
  $contentsByCategoryIDArray = Category.getContents($category[id])
  $content_categories[$key][$contentsByCategoryIDArray]
}

Is there an easy way in rails to do this?

Greets,

Nico

Body:
content_categories.each do |k,v|
  content_categories[k] = Category.getContents(v)
end

I suppose it's works


问:
How to read nextline of textfile in Java?
```<code>import java.io.*;
import java.util.*;
public class stringstore
{
    public static void main(String[] args)
    {
        File file = new File("C:\\a.txt");
        try
        {
            String strIP="";
            Scanner sc = new Scanner(file);
            while(sc.hasNext())
            {
                String line = sc.nextLine();
                String str[] = line.split(", ");
                strIP = str[0];
            }
            System.out.println(strIP);
        }
        catch(IOException e)
        {
        // work with the errors here
        }
    }
}
</code>```

How do I read a nextline from a textfile and display it.

答:
You can read file line by line:</p>

```<code>        BufferedReader bufferedReader = new BufferedReader(new FileReader(new File("filename")));
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }
</code>```

Body:
import java.io.*;
import java.util.*;
public class stringstore
{
    public static void main(String[] args)
    {
        File file = new File("C:\\a.txt");
        try
        {
            String strIP="";
            Scanner sc = new Scanner(file);
            while(sc.hasNext())
            {
                String line = sc.nextLine();
                String str[] = line.split(", ");
                strIP = str[0];
            }
            System.out.println(strIP);
        }
        catch(IOException e)
        {
        // work with the errors here
        }
    }
}

How do I read a nextline from a textfile and display it.

Body:
You can read file line by line:

        BufferedReader bufferedReader = new BufferedReader(new FileReader(new File("filename")));
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }


问:
Git Bash is slow on startup and commands
Startup and commands is very very slow in windows 8.1 embedded.

When I start git bash, it is turn on 1~2minutes.

I input a command like 'ls', it delay 1~2 minutes.

And ten shell prompt is delayed 1~2minutes,too.

Changing Environment path doesn't work.

答:
The question seems inactive and answered but I've found some other issue with git bash starting slow, so sharing just in case it's useful for anyone.

In my case the delay of a few seconds was caused by the git-prompt.sh script which was started through bash.bashrc by default. I commented out the last line in the default %GIT_HOME%\etc\bash.bashrc:

```<code>shopt -q login_shell || . /etc/profile.d/git-prompt.sh
</code>```

The benefit: bash starts in less than a second.

The downside: the prompt does not show which branch I'm in.

Body:
The question seems inactive and answered but I've found some other issue with git bash starting slow, so sharing just in case it's useful for anyone.

In my case the delay of a few seconds was caused by the git-prompt.sh script which was started through bash.bashrc by default. I commented out the last line in the default %GIT_HOME%\etc\bash.bashrc:

shopt -q login_shell || . /etc/profile.d/git-prompt.sh

The benefit: bash starts in less than a second.

The downside: the prompt does not show which branch I'm in.


问:
Error when installing Nokigori with Chef recipe
I'm trying to install and use Nokigoro for XML parsing (if there is an alternative parser that doesn't result in mindless head hitting of wall - I'm happy to check it out)

I'm running this via a recipe on the chef client,  in my recipe I have:

```<code>    # include_recipe 'ohai'
chef_gem 'nokogiri'
require 'nokogiri'
</code>```

which is as far as it gets really.

Running this as my run list results in the following error:

```<code>    Starting Chef Client, version 12.12.15
[2017-03-31T14:07:36+00:00] WARN: Run List override has been provided.
[2017-03-31T14:07:36+00:00] WARN: Original Run List: []
[2017-03-31T14:07:36+00:00] WARN: Overridden Run List: [recipe[steve-solr]]
resolving cookbooks for run list: ["steve-solr"]
Synchronizing Cookbooks:
  - steve-solr (0.1.0)
Installing Cookbook Gems:
Compiling Cookbooks...
Recipe: steve-solr::default
  * chef_gem[nokogiri] action install

    ================================================================================
    Error executing action `install` on resource 'chef_gem[nokogiri]'
    ================================================================================

    Mixlib::ShellOut::ShellCommandFailed
    ------------------------------------
    Expected process to exit with [0], but received '1'
    ---- Begin output of /opt/chef/embedded/bin/gem install nokogiri -q --no-rdoc --no-ri -v "1.7.1" ----
    STDOUT: Building native extensions.  This could take a while...
    STDERR: ERROR:  Error installing nokogiri:
        ERROR: Failed to build gem native extension.

        current directory: /opt/chef/embedded/lib/ruby/gems/2.1.0/gems/nokogiri-1.7.1/ext/nokogiri
    /opt/chef/embedded/bin/ruby -r ./siteconf20170331-19864-1d63c49.rb extconf.rb
    checking if the C compiler accepts ... *** extconf.rb failed ***
    Could not create Makefile due to some reason, probably lack of necessary
    libraries and/or headers.  Check the mkmf.log file for more details.  You may
    need configuration options.

    Provided configuration options:
        --with-opt-dir
        --with-opt-include
        --without-opt-include=${opt-dir}/include
        --with-opt-lib
        --without-opt-lib=${opt-dir}/lib
        --with-make-prog
        --without-make-prog
        --srcdir=.
        --curdir
        --ruby=/opt/chef/embedded/bin/ruby
        --help
        --clean
    /opt/chef/embedded/lib/ruby/2.1.0/mkmf.rb:467:in `try_do': The compiler failed to generate an executable file. (RuntimeError)
    You have to install development tools first.
        from /opt/chef/embedded/lib/ruby/2.1.0/mkmf.rb:582:in `block in try_compile'
        from /opt/chef/embedded/lib/ruby/2.1.0/mkmf.rb:533:in `with_werror'
        from /opt/chef/embedded/lib/ruby/2.1.0/mkmf.rb:582:in `try_compile'
        from extconf.rb:138:in `nokogiri_try_compile'
        from extconf.rb:162:in `block in add_cflags'
        from /opt/chef/embedded/lib/ruby/2.1.0/mkmf.rb:630:in `with_cflags'
        from extconf.rb:161:in `add_cflags'
        from extconf.rb:406:in `<main>'

    To see why this extension failed to compile, please check the mkmf.log which can be found here:

      /opt/chef/embedded/lib/ruby/gems/2.1.0/extensions/x86_64-linux/2.1.0/nokogiri-1.7.1/mkmf.log

    extconf failed, exit code 1

    Gem files will remain installed in /opt/chef/embedded/lib/ruby/gems/2.1.0/gems/nokogiri-1.7.1 for inspection.
    Results logged to /opt/chef/embedded/lib/ruby/gems/2.1.0/extensions/x86_64-linux/2.1.0/nokogiri-1.7.1/gem_make.out
    ---- End output of /opt/chef/embedded/bin/gem install nokogiri -q --no-rdoc --no-ri -v "1.7.1" ----
    Ran /opt/chef/embedded/bin/gem install nokogiri -q --no-rdoc --no-ri -v "1.7.1" returned 1

    Cookbook Trace:
    ---------------
    /var/chef/cache/cookbooks/steve-solr/recipes/default.rb:8:in `from_file'

    Resource Declaration:
    ---------------------
    # In /var/chef/cache/cookbooks/steve-solr/recipes/default.rb

      8: chef_gem 'nokogiri'
      9: require 'nokogiri'

    Compiled Resource:
    ------------------
    # Declared in /var/chef/cache/cookbooks/steve-solr/recipes/default.rb:8:in `from_file'

    chef_gem("nokogiri") do
      package_name "nokogiri"
      action [:install]
      retries 0
      retry_delay 2
      default_guard_interpreter :default
      declared_type :chef_gem
      cookbook_name "steve-solr"
      recipe_name "default"
      gem_binary "/opt/chef/embedded/bin/gem"
    end

    Platform:
    ---------
    x86_64-linux

  ================================================================================
  Recipe Compile Error in /var/chef/cache/cookbooks/steve-solr/recipes/default.rb
  ================================================================================

  Mixlib::ShellOut::ShellCommandFailed
  ------------------------------------
  chef_gem[nokogiri] (steve-solr::default line 8) had an error: Mixlib::ShellOut::ShellCommandFailed: Expected process to exit with [0], but received '1'
  ---- Begin output of /opt/chef/embedded/bin/gem install nokogiri -q --no-rdoc --no-ri -v "1.7.1" ----
  STDOUT: Building native extensions.  This could take a while...
  STDERR: ERROR:  Error installing nokogiri:
    ERROR: Failed to build gem native extension.

      current directory: /opt/chef/embedded/lib/ruby/gems/2.1.0/gems/nokogiri-1.7.1/ext/nokogiri
  /opt/chef/embedded/bin/ruby -r ./siteconf20170331-19864-1d63c49.rb extconf.rb
  checking if the C compiler accepts ... *** extconf.rb failed ***
  Could not create Makefile due to some reason, probably lack of necessary
  libraries and/or headers.  Check the mkmf.log file for more details.  You may
  need configuration options.

  Provided configuration options:
    --with-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=/opt/chef/embedded/bin/ruby
    --help
    --clean
  /opt/chef/embedded/lib/ruby/2.1.0/mkmf.rb:467:in `try_do': The compiler failed to generate an executable file. (RuntimeError)
  You have to install development tools first.
    from /opt/chef/embedded/lib/ruby/2.1.0/mkmf.rb:582:in `block in try_compile'
    from /opt/chef/embedded/lib/ruby/2.1.0/mkmf.rb:533:in `with_werror'
    from /opt/chef/embedded/lib/ruby/2.1.0/mkmf.rb:582:in `try_compile'
    from extconf.rb:138:in `nokogiri_try_compile'
    from extconf.rb:162:in `block in add_cflags'
    from /opt/chef/embedded/lib/ruby/2.1.0/mkmf.rb:630:in `with_cflags'
    from extconf.rb:161:in `add_cflags'
    from extconf.rb:406:in `<main>'

  To see why this extension failed to compile, please check the mkmf.log which can be found here:

    /opt/chef/embedded/lib/ruby/gems/2.1.0/extensions/x86_64-linux/2.1.0/nokogiri-1.7.1/mkmf.log

  extconf failed, exit code 1

  Gem files will remain installed in /opt/chef/embedded/lib/ruby/gems/2.1.0/gems/nokogiri-1.7.1 for inspection.
  Results logged to /opt/chef/embedded/lib/ruby/gems/2.1.0/extensions/x86_64-linux/2.1.0/nokogiri-1.7.1/gem_make.out
  ---- End output of /opt/chef/embedded/bin/gem install nokogiri -q --no-rdoc --no-ri -v "1.7.1" ----
  Ran /opt/chef/embedded/bin/gem install nokogiri -q --no-rdoc --no-ri -v "1.7.1" returned 1

  Cookbook Trace:
  ---------------
    /var/chef/cache/cookbooks/steve-solr/recipes/default.rb:8:in `from_file'

  Relevant File Content:
  ----------------------
  /var/chef/cache/cookbooks/steve-solr/recipes/default.rb:

    1:  #
    2:  # Cookbook Name:: steve-solr
    3:  # Recipe:: default
    4:  #
    5:  # Copyright (c) 2017 The Authors, All Rights Reserved.
    6:  # include_recipe 'aws'
    7:  # include_recipe 'ohai'
    8>> chef_gem 'nokogiri'
    9:  require 'nokogiri'
   10:
   11:  class SolrObject
   12:      attr_reader :coreName
   13:      def initialize(name)
   14:          @coreName = name
   15:      end
   16:
   17:      def coreName

  Platform:
  ---------
  x86_64-linux

  Running handlers:
[2017-03-31T14:07:38+00:00] ERROR: Running exception handlers
  Running handlers complete
[2017-03-31T14:07:38+00:00] ERROR: Exception handlers complete
  Chef Client failed. 0 resources updated in 02 seconds
[2017-03-31T14:07:38+00:00] FATAL: Stacktrace dumped to /var/chef/cache/chef-stacktrace.out
[2017-03-31T14:07:38+00:00] FATAL: Please provide the contents of the stacktrace.out file if you file a bug report
[2017-03-31T14:07:38+00:00] ERROR: chef_gem[nokogiri] (steve-solr::default line 8) had an error: Mixlib::ShellOut::ShellCommandFailed: Expected process to exit with [0], but received '1'
---- Begin output of /opt/chef/embedded/bin/gem install nokogiri -q --no-rdoc --no-ri -v "1.7.1" ----
STDOUT: Building native extensions.  This could take a while...
STDERR: ERROR:  Error installing nokogiri:
    ERROR: Failed to build gem native extension.

    current directory: /opt/chef/embedded/lib/ruby/gems/2.1.0/gems/nokogiri-1.7.1/ext/nokogiri
/opt/chef/embedded/bin/ruby -r ./siteconf20170331-19864-1d63c49.rb extconf.rb
checking if the C compiler accepts ... *** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
    --with-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=/opt/chef/embedded/bin/ruby
    --help
    --clean
/opt/chef/embedded/lib/ruby/2.1.0/mkmf.rb:467:in `try_do': The compiler failed to generate an executable file. (RuntimeError)
You have to install development tools first.
    from /opt/chef/embedded/lib/ruby/2.1.0/mkmf.rb:582:in `block in try_compile'
    from /opt/chef/embedded/lib/ruby/2.1.0/mkmf.rb:533:in `with_werror'
    from /opt/chef/embedded/lib/ruby/2.1.0/mkmf.rb:582:in `try_compile'
    from extconf.rb:138:in `nokogiri_try_compile'
    from extconf.rb:162:in `block in add_cflags'
    from /opt/chef/embedded/lib/ruby/2.1.0/mkmf.rb:630:in `with_cflags'
    from extconf.rb:161:in `add_cflags'
    from extconf.rb:406:in `<main>'

To see why this extension failed to compile, please check the mkmf.log which can be found here:

  /opt/chef/embedded/lib/ruby/gems/2.1.0/extensions/x86_64-linux/2.1.0/nokogiri-1.7.1/mkmf.log

extconf failed, exit code 1

Gem files will remain installed in /opt/chef/embedded/lib/ruby/gems/2.1.0/gems/nokogiri-1.7.1 for inspection.
Results logged to /opt/chef/embedded/lib/ruby/gems/2.1.0/extensions/x86_64-linux/2.1.0/nokogiri-1.7.1/gem_make.out
---- End output of /opt/chef/embedded/bin/gem install nokogiri -q --no-rdoc --no-ri -v "1.7.1" ----
Ran /opt/chef/embedded/bin/gem install nokogiri -q --no-rdoc --no-ri -v "1.7.1" returned 1
[2017-03-31T14:07:38+00:00] FATAL: Chef::Exceptions::ChildConvergeError: Chef run process exited unsuccessfully (exit code 1)
</code>```

with this being in my error file:

```<code>"gcc -o conftest -I/opt/chef/embedded/include/ruby-2.1.0/x86_64-linux -I/opt/chef/embedded/include/ruby-2.1.0/$
checked program was:
/* begin */
1: #include "ruby.h"
2:
3: int main(int argc, char **argv)
4: {
5:   return 0;
6: }
/* end */
</code>```

any help or suggestions on fixing would be fantastic, thanks.

答: Just remove the chef_gem entirely. We bundle nokogiri with the Chef installer so you don't have to install or compile it unless you specifically need the latest version for some reason.

Body:
I'm trying to install and use Nokigoro for XML parsing (if there is an alternative parser that doesn't result in mindless head hitting of wall - I'm happy to check it out)

I'm running this via a recipe on the chef client,  in my recipe I have:

    # include_recipe 'ohai'
chef_gem 'nokogiri'
require 'nokogiri'

which is as far as it gets really.

Running this as my run list results in the following error:

    Starting Chef Client, version 12.12.15
[2017-03-31T14:07:36+00:00] WARN: Run List override has been provided.
[2017-03-31T14:07:36+00:00] WARN: Original Run List: []
[2017-03-31T14:07:36+00:00] WARN: Overridden Run List: [recipe[steve-solr]]
resolving cookbooks for run list: ["steve-solr"]
Synchronizing Cookbooks:
  - steve-solr (0.1.0)
Installing Cookbook Gems:
Compiling Cookbooks...
Recipe: steve-solr::default
  * chef_gem[nokogiri] action install

    ================================================================================
    Error executing action `install` on resource 'chef_gem[nokogiri]'
    ================================================================================

    Mixlib::ShellOut::ShellCommandFailed
    ------------------------------------
    Expected process to exit with [0], but received '1'
    ---- Begin output of /opt/chef/embedded/bin/gem install nokogiri -q --no-rdoc --no-ri -v "1.7.1" ----
    STDOUT: Building native extensions.  This could take a while...
    STDERR: ERROR:  Error installing nokogiri:
        ERROR: Failed to build gem native extension.

        current directory: /opt/chef/embedded/lib/ruby/gems/2.1.0/gems/nokogiri-1.7.1/ext/nokogiri
    /opt/chef/embedded/bin/ruby -r ./siteconf20170331-19864-1d63c49.rb extconf.rb
    checking if the C compiler accepts ... *** extconf.rb failed ***
    Could not create Makefile due to some reason, probably lack of necessary
    libraries and/or headers.  Check the mkmf.log file for more details.  You may
    need configuration options.

    Provided configuration options:
        --with-opt-dir
        --with-opt-include
        --without-opt-include=${opt-dir}/include
        --with-opt-lib
        --without-opt-lib=${opt-dir}/lib
        --with-make-prog
        --without-make-prog
        --srcdir=.
        --curdir
        --ruby=/opt/chef/embedded/bin/ruby
        --help
        --clean
    /opt/chef/embedded/lib/ruby/2.1.0/mkmf.rb:467:in `try_do': The compiler failed to generate an executable file. (RuntimeError)
    You have to install development tools first.
        from /opt/chef/embedded/lib/ruby/2.1.0/mkmf.rb:582:in `block in try_compile'
        from /opt/chef/embedded/lib/ruby/2.1.0/mkmf.rb:533:in `with_werror'
        from /opt/chef/embedded/lib/ruby/2.1.0/mkmf.rb:582:in `try_compile'
        from extconf.rb:138:in `nokogiri_try_compile'
        from extconf.rb:162:in `block in add_cflags'
        from /opt/chef/embedded/lib/ruby/2.1.0/mkmf.rb:630:in `with_cflags'
        from extconf.rb:161:in `add_cflags'
        from extconf.rb:406:in `'

    To see why this extension failed to compile, please check the mkmf.log which can be found here:

      /opt/chef/embedded/lib/ruby/gems/2.1.0/extensions/x86_64-linux/2.1.0/nokogiri-1.7.1/mkmf.log

    extconf failed, exit code 1

    Gem files will remain installed in /opt/chef/embedded/lib/ruby/gems/2.1.0/gems/nokogiri-1.7.1 for inspection.
    Results logged to /opt/chef/embedded/lib/ruby/gems/2.1.0/extensions/x86_64-linux/2.1.0/nokogiri-1.7.1/gem_make.out
    ---- End output of /opt/chef/embedded/bin/gem install nokogiri -q --no-rdoc --no-ri -v "1.7.1" ----
    Ran /opt/chef/embedded/bin/gem install nokogiri -q --no-rdoc --no-ri -v "1.7.1" returned 1

    Cookbook Trace:
    ---------------
    /var/chef/cache/cookbooks/steve-solr/recipes/default.rb:8:in `from_file'

    Resource Declaration:
    ---------------------
    # In /var/chef/cache/cookbooks/steve-solr/recipes/default.rb

      8: chef_gem 'nokogiri'
      9: require 'nokogiri'

    Compiled Resource:
    ------------------
    # Declared in /var/chef/cache/cookbooks/steve-solr/recipes/default.rb:8:in `from_file'

    chef_gem("nokogiri") do
      package_name "nokogiri"
      action [:install]
      retries 0
      retry_delay 2
      default_guard_interpreter :default
      declared_type :chef_gem
      cookbook_name "steve-solr"
      recipe_name "default"
      gem_binary "/opt/chef/embedded/bin/gem"
    end

    Platform:
    ---------
    x86_64-linux

  ================================================================================
  Recipe Compile Error in /var/chef/cache/cookbooks/steve-solr/recipes/default.rb
  ================================================================================

  Mixlib::ShellOut::ShellCommandFailed
  ------------------------------------
  chef_gem[nokogiri] (steve-solr::default line 8) had an error: Mixlib::ShellOut::ShellCommandFailed: Expected process to exit with [0], but received '1'
  ---- Begin output of /opt/chef/embedded/bin/gem install nokogiri -q --no-rdoc --no-ri -v "1.7.1" ----
  STDOUT: Building native extensions.  This could take a while...
  STDERR: ERROR:  Error installing nokogiri:
    ERROR: Failed to build gem native extension.

      current directory: /opt/chef/embedded/lib/ruby/gems/2.1.0/gems/nokogiri-1.7.1/ext/nokogiri
  /opt/chef/embedded/bin/ruby -r ./siteconf20170331-19864-1d63c49.rb extconf.rb
  checking if the C compiler accepts ... *** extconf.rb failed ***
  Could not create Makefile due to some reason, probably lack of necessary
  libraries and/or headers.  Check the mkmf.log file for more details.  You may
  need configuration options.

  Provided configuration options:
    --with-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=/opt/chef/embedded/bin/ruby
    --help
    --clean
  /opt/chef/embedded/lib/ruby/2.1.0/mkmf.rb:467:in `try_do': The compiler failed to generate an executable file. (RuntimeError)
  You have to install development tools first.
    from /opt/chef/embedded/lib/ruby/2.1.0/mkmf.rb:582:in `block in try_compile'
    from /opt/chef/embedded/lib/ruby/2.1.0/mkmf.rb:533:in `with_werror'
    from /opt/chef/embedded/lib/ruby/2.1.0/mkmf.rb:582:in `try_compile'
    from extconf.rb:138:in `nokogiri_try_compile'
    from extconf.rb:162:in `block in add_cflags'
    from /opt/chef/embedded/lib/ruby/2.1.0/mkmf.rb:630:in `with_cflags'
    from extconf.rb:161:in `add_cflags'
    from extconf.rb:406:in `'

  To see why this extension failed to compile, please check the mkmf.log which can be found here:

    /opt/chef/embedded/lib/ruby/gems/2.1.0/extensions/x86_64-linux/2.1.0/nokogiri-1.7.1/mkmf.log

  extconf failed, exit code 1

  Gem files will remain installed in /opt/chef/embedded/lib/ruby/gems/2.1.0/gems/nokogiri-1.7.1 for inspection.
  Results logged to /opt/chef/embedded/lib/ruby/gems/2.1.0/extensions/x86_64-linux/2.1.0/nokogiri-1.7.1/gem_make.out
  ---- End output of /opt/chef/embedded/bin/gem install nokogiri -q --no-rdoc --no-ri -v "1.7.1" ----
  Ran /opt/chef/embedded/bin/gem install nokogiri -q --no-rdoc --no-ri -v "1.7.1" returned 1

  Cookbook Trace:
  ---------------
    /var/chef/cache/cookbooks/steve-solr/recipes/default.rb:8:in `from_file'

  Relevant File Content:
  ----------------------
  /var/chef/cache/cookbooks/steve-solr/recipes/default.rb:

    1:  #
    2:  # Cookbook Name:: steve-solr
    3:  # Recipe:: default
    4:  #
    5:  # Copyright (c) 2017 The Authors, All Rights Reserved.
    6:  # include_recipe 'aws'
    7:  # include_recipe 'ohai'
    8>> chef_gem 'nokogiri'
    9:  require 'nokogiri'
   10:
   11:  class SolrObject
   12:      attr_reader :coreName
   13:      def initialize(name)
   14:          @coreName = name
   15:      end
   16:
   17:      def coreName

  Platform:
  ---------
  x86_64-linux

  Running handlers:
[2017-03-31T14:07:38+00:00] ERROR: Running exception handlers
  Running handlers complete
[2017-03-31T14:07:38+00:00] ERROR: Exception handlers complete
  Chef Client failed. 0 resources updated in 02 seconds
[2017-03-31T14:07:38+00:00] FATAL: Stacktrace dumped to /var/chef/cache/chef-stacktrace.out
[2017-03-31T14:07:38+00:00] FATAL: Please provide the contents of the stacktrace.out file if you file a bug report
[2017-03-31T14:07:38+00:00] ERROR: chef_gem[nokogiri] (steve-solr::default line 8) had an error: Mixlib::ShellOut::ShellCommandFailed: Expected process to exit with [0], but received '1'
---- Begin output of /opt/chef/embedded/bin/gem install nokogiri -q --no-rdoc --no-ri -v "1.7.1" ----
STDOUT: Building native extensions.  This could take a while...
STDERR: ERROR:  Error installing nokogiri:
    ERROR: Failed to build gem native extension.

    current directory: /opt/chef/embedded/lib/ruby/gems/2.1.0/gems/nokogiri-1.7.1/ext/nokogiri
/opt/chef/embedded/bin/ruby -r ./siteconf20170331-19864-1d63c49.rb extconf.rb
checking if the C compiler accepts ... *** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
    --with-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=/opt/chef/embedded/bin/ruby
    --help
    --clean
/opt/chef/embedded/lib/ruby/2.1.0/mkmf.rb:467:in `try_do': The compiler failed to generate an executable file. (RuntimeError)
You have to install development tools first.
    from /opt/chef/embedded/lib/ruby/2.1.0/mkmf.rb:582:in `block in try_compile'
    from /opt/chef/embedded/lib/ruby/2.1.0/mkmf.rb:533:in `with_werror'
    from /opt/chef/embedded/lib/ruby/2.1.0/mkmf.rb:582:in `try_compile'
    from extconf.rb:138:in `nokogiri_try_compile'
    from extconf.rb:162:in `block in add_cflags'
    from /opt/chef/embedded/lib/ruby/2.1.0/mkmf.rb:630:in `with_cflags'
    from extconf.rb:161:in `add_cflags'
    from extconf.rb:406:in `'

To see why this extension failed to compile, please check the mkmf.log which can be found here:

  /opt/chef/embedded/lib/ruby/gems/2.1.0/extensions/x86_64-linux/2.1.0/nokogiri-1.7.1/mkmf.log

extconf failed, exit code 1

Gem files will remain installed in /opt/chef/embedded/lib/ruby/gems/2.1.0/gems/nokogiri-1.7.1 for inspection.
Results logged to /opt/chef/embedded/lib/ruby/gems/2.1.0/extensions/x86_64-linux/2.1.0/nokogiri-1.7.1/gem_make.out
---- End output of /opt/chef/embedded/bin/gem install nokogiri -q --no-rdoc --no-ri -v "1.7.1" ----
Ran /opt/chef/embedded/bin/gem install nokogiri -q --no-rdoc --no-ri -v "1.7.1" returned 1
[2017-03-31T14:07:38+00:00] FATAL: Chef::Exceptions::ChildConvergeError: Chef run process exited unsuccessfully (exit code 1)

with this being in my error file:

"gcc -o conftest -I/opt/chef/embedded/include/ruby-2.1.0/x86_64-linux -I/opt/chef/embedded/include/ruby-2.1.0/$
checked program was:
/* begin */
1: #include "ruby.h"
2:
3: int main(int argc, char **argv)
4: {
5:   return 0;
6: }
/* end */

any help or suggestions on fixing would be fantastic, thanks.


问:
Still getting error empty array
I'm still getting an error in tableView and I can't figure out why:

```<code>@objc class MyViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

var productsToDisplay: [SKProduct]!

override func viewWillAppear(_ animated: Bool) {
    // an assync call to load products to the productsToDisplay
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "PurchaseItemTableViewCell", for: indexPath) as? PurchaseItemTableViewCell else {
        fatalError("Coulnd't parse table cell!")
    }

    // here the app always show an error without any specification
    if(!(self.productsToDisplay != nil && self.productsToDisplay!.count > 0))     {
        return cell
    }

    cell.nameLabel.text = "my text"

   return cell

}

}
</code>```

What I'm doing wrong? Or how to fix the error / not load content of the table until data are loaded?

Thank you very much

答:
Basically never never never declare a data source array as (implicit unwrapped) optional. Declare it as non-optional empty array:

```<code>var productsToDisplay = [SKProduct]()
</code>```

The benefit is a non-optional type cannot crash.

In numbersOfRows return the number of items:

```<code> func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return productsToDisplay.count
  }
</code>```

If the array is empty cellForRow is never called.

In cellForRow first set the label then return the cell and checking for 0 and nil is not needed:

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "PurchaseItemTableViewCell", for: indexPath) as! PurchaseItemTableViewCell
    let product = productsToDisplay[indexPath.row]
    cell.nameLabel.text = product.name // change that to the real property in SKProduct
    return cell

}
</code>```

Title: Still getting error empty array

Body:
I'm still getting an error in tableView and I can't figure out why:

@objc class MyViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

var productsToDisplay: [SKProduct]!

override func viewWillAppear(_ animated: Bool) {
    // an assync call to load products to the productsToDisplay
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "PurchaseItemTableViewCell", for: indexPath) as? PurchaseItemTableViewCell else {
        fatalError("Coulnd't parse table cell!")
    }

    // here the app always show an error without any specification
    if(!(self.productsToDisplay != nil && self.productsToDisplay!.count > 0))     {
        return cell
    }

    cell.nameLabel.text = "my text"

   return cell

}

}

What I'm doing wrong? Or how to fix the error / not load content of the table until data are loaded?

Thank you very much

Body:
Basically never never never declare a data source array as (implicit unwrapped) optional. Declare it as non-optional empty array:

var productsToDisplay = [SKProduct]()

The benefit is a non-optional type cannot crash.

In numbersOfRows return the number of items:

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

If the array is empty cellForRow is never called.

In cellForRow first set the label then return the cell and checking for 0 and nil is not needed:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "PurchaseItemTableViewCell", for: indexPath) as! PurchaseItemTableViewCell
    let product = productsToDisplay[indexPath.row]
    cell.nameLabel.text = product.name // change that to the real property in SKProduct
    return cell

}


问:
How to make sure my while loop does not break my condition?
I'm practicing a simple while loop. Buy a phone for the cost of 200 only until my bank account hits 500, but because it buys the phone first it only knows you dropped below 500 after it buys the phone.

In my code, it's buying until it takes the bankaccountmoney variable to 400:

var bankaccountmoney = 2000;
var phonesbought = 0;
var phonecost = 200;

while (bankaccountmoney > 500) {
  phonesbought = phonesbought + 1;
  bankaccountmoney = bankaccountmoney - phonecost;
  console.log("money: " + bankaccountmoney + " phonesbought: " + phonesbought);
}```

答:
```<code>while (bankaccountmoney - phonecost >= 500) {
...
}
</code>```


问:
How to divide different divs on the same line along the width of a device in different resolutions?
I have a list of projects consists of multiples lines.Each line consists of 3 divs:

The first contain a logo.

The second contains the title, state and the date of the project.

The third contains some more infos.

I want to put the 3 divs on the same line and take in consideration the width of different resolutions of device into the display of the page.
index.html:

As a result I got the logo in a line and the two other divs in another line.How can I fix that?

#list_project {
  position: relative;
  top: 120px;
  z-index: 1;
}

.project_logo {
  display: block;
  height: 60px;
}

.project_title {
  font-size: 18px;
  font-family: "Arial";
  color: #000000;
  font-weight: bold;
  line-height: 1.2;
}

.project_status {
  font-size: 18px;
  font-family: "Arial Round MT Bold";
  color: #8e8e8e;
  line-height: 1.2;
}

.project_date {
  font-size: 18px;
  font-family: "Arial";
  color: #8e8e8e;
  line-height: 1.2;
}

.project_info_1 {
  border-radius: 10px;
  background-color: #e6e1e1;
  height: 63px;
}

.project_cost {
  font-size: 16px;
  font-family: "Arial";
  color: #000000;
  font-weight: bold;
  line-height: 1.2;
}

.project_cost_1 {
  font-size: 16px;
  font-family: "Arial";
  color: #8e8e8e;
  font-weight: bold;
  line-height: 1.2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="list_project">
  <div class="container-fluid">
    <div class="row">
      <div class="col col-sm-4 col-md-4 col-lg-4 col-xl-4">
        <img class="project_logo" src="./logos/logo.png" />
      </div>
      <div class="col col-sm-4 col-md-4 col-lg-4 col-xl-4">
        <table>
          <tbody>
            <tr>
              <td class="project_title"> Project 1 </td>
            </tr>
            <tr>
              <td class="project_status">Active</td>
            </tr>
            <tr>
              <td class="project_date">03/2017-05/2018</td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="col col-sm-4 col-md-4 col-lg-4 col-xl-4">
        <table class="project_info_1">
          <tbody>
            <tr>
              <td class="project_cost" name="project_cost">Cost:</td>
              <td class="project_cost_1" name="project_cost_1">140.000k$.</td>
            </tr>
            <tr>
              <td class="project_cost" name="project_delay">Delay:</td>
              <td class="project_cost_1" name="project_delay_1">350 days.</td>
            </tr>
            <tr>
              <td class="project_cost" name="project_load">Load:</td>
              <td class="project_cost_1" name="project_load_1">125 days.</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div></code>```

答:
```<code><div class="row">

   <div class="col-md-6">
      //FIRST DIV HERE
   </div>
   <div class="col-md-6">
     //SECOND DIV HERE
   </div>

</div>
</code>```

Body:
I have a list of projects consists of multiples lines.Each line consists of 3 divs:

The first contain a logo.

The second contains the title, state and the date of the project.

The third contains some more infos.

I want to put the 3 divs on the same line and take in consideration the width of different resolutions of device into the display of the page.
index.html:

As a result I got the logo in a line and the two other divs in another line.How can I fix that?

#list_project {
  position: relative;
  top: 120px;
  z-index: 1;
}

.project_logo {
  display: block;
  height: 60px;
}

.project_title {
  font-size: 18px;
  font-family: "Arial";
  color: #000000;
  font-weight: bold;
  line-height: 1.2;
}

.project_status {
  font-size: 18px;
  font-family: "Arial Round MT Bold";
  color: #8e8e8e;
  line-height: 1.2;
}

.project_date {
  font-size: 18px;
  font-family: "Arial";
  color: #8e8e8e;
  line-height: 1.2;
}

.project_info_1 {
  border-radius: 10px;
  background-color: #e6e1e1;
  height: 63px;
}

.project_cost {
  font-size: 16px;
  font-family: "Arial";
  color: #000000;
  font-weight: bold;
  line-height: 1.2;
}

.project_cost_1 {
  font-size: 16px;
  font-family: "Arial";
  color: #8e8e8e;
  font-weight: bold;
  line-height: 1.2;
}

               Project 1

              Active

              03/2017-05/2018

              Cost:
              140.000k$.

              Delay:
              350 days.

              Load:
              125 days.


问:
Need a simple explanation of the inject method
```<code>[1, 2, 3, 4].inject(0) { |result, element| result + element } # => 10
</code>```

I'm looking at this code but my brain is not registering how the number 10 can become the result. Would someone mind explaining what's happening here?

答:
There is another form of .inject() method That is very helpful
[4,5].inject(&:+)  That will add up all the element of the area</p>

OwnerDisplayName: hightide

Body:
[1, 2, 3, 4].inject(0) { |result, element| result + element } # => 10

I'm looking at this code but my brain is not registering how the number 10 can become the result. Would someone mind explaining what's happening here?


问:
What can be defined outside any class in C#?
I heard that

in Java, everything is defined in classes, except classes themselves.

C# and Java are very similar languages.

So i thought that it is the same case for C#, until I saw two examples, where a enum type and a delegate type are not defined within any class:

```<code>using System;
enum Color
{
  Red,
   Green,
   Blue
}
class Test
{
  static void PrintColor(Color color) {
    switch (color) {
      case Color.Red:
        Console.WriteLine("Red");
        break;
      case Color.Green:
        Console.WriteLine("Green");
        break;
      case Color.Blue:
        Console.WriteLine("Blue");
        break;
      default:
        Console.WriteLine("Unknown color");
        break;
    }
  }
  static void Main() {
    Color c = Color.Red;
    PrintColor(c);
    PrintColor(Color.Blue);
  }
}
</code>```

and

```<code>using System;
delegate double Function(double x);
class Multiplier
{
  double factor;
  public Multiplier(double factor) {
    this.factor = factor;
  }
  public double Multiply(double x) {
    return x * factor;
  }
}
class Test
{
  static double Square(double x) {
    return x * x;
  }
  static double[] Apply(double[] a, Function f) {
    double[] result = new double[a.Length];
    for (int i = 0; i < a.Length; i++) result[i] = f(a[i]);
    return result;
  }
  static void Main() {
    double[] a = {0.0, 0.5, 1.0};
    double[] squares = Apply(a, Square);
    double[] sines = Apply(a, Math.Sin);
    Multiplier m = new Multiplier(2.0);
    double[] doubles =  Apply(a, m.Multiply);
  }
}
</code>```

So what can be defined outside any class in C#?

Based on the above examples, can the definition of  any type be defined outside any class?

Thanks.

答:
According to the C# specification, in B2.6 Namespaces,

compilation-unit:

  extern-alias-directivesopt   using-directivesopt  global-attributesopt

      namespace-member-declarationsopt

namespace-declaration:

  namespace   qualified-identifier   namespace-body   ;opt

qualified-identifier:

  identifier

  qualified-identifier   .   identifier

namespace-body:

  {   extern-alias-directivesopt   using-directivesopt   namespace-member-declarationsopt   }

extern-alias-directives:

  extern-alias-directive

  extern-alias-directives   extern-alias-directive

extern-alias-directive:

  extern   alias   identifier   ;

using-directives:

  using-directive

  using-directives   using-directive

using-directive:

  using-alias-directive

  using-namespace-directive

using-alias-directive:

  using   identifier   =   namespace-or-type-name   ;

using-namespace-directive:

  using   namespace-name   ;

namespace-member-declarations:

  namespace-member-declaration

  namespace-member-declarations   namespace-member-declaration

namespace-member-declaration:

  namespace-declaration

  type-declaration

type-declaration:

  class-declaration

  struct-declaration

  interface-declaration

  enum-declaration

  delegate-declaration

qualified-alias-member:

  identifier   ::   identifier   type-argument-listopt

According to rule namespace-member-declaration, those can be placed outside any class in C# is

namespace-declaration

    type-declaration

Namely, namespace and type.

And type contains:

type-declaration:

    class-declaration

    struct-declaration

    interface-declaration

    enum-declaration

    delegate-declaration

So the answer is namespace, class, struct, interface, enum, delegate declaration. Note I don't regard directives, like using-alias-directive, as definitions here.

You can find the spec file in C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC#\Specifications\1033 if you are using VS2017.

Body:
I heard that

in Java, everything is defined in classes, except classes themselves.

C# and Java are very similar languages.

So i thought that it is the same case for C#, until I saw two examples, where a enum type and a delegate type are not defined within any class:

using System;
enum Color
{
  Red,
   Green,
   Blue
}
class Test
{
  static void PrintColor(Color color) {
    switch (color) {
      case Color.Red:
        Console.WriteLine("Red");
        break;
      case Color.Green:
        Console.WriteLine("Green");
        break;
      case Color.Blue:
        Console.WriteLine("Blue");
        break;
      default:
        Console.WriteLine("Unknown color");
        break;
    }
  }
  static void Main() {
    Color c = Color.Red;
    PrintColor(c);
    PrintColor(Color.Blue);
  }
}

and

using System;
delegate double Function(double x);
class Multiplier
{
  double factor;
  public Multiplier(double factor) {
    this.factor = factor;
  }
  public double Multiply(double x) {
    return x * factor;
  }
}
class Test
{
  static double Square(double x) {
    return x * x;
  }
  static double[] Apply(double[] a, Function f) {
    double[] result = new double[a.Length];
    for (int i = 0; i < a.Length; i++) result[i] = f(a[i]);
    return result;
  }
  static void Main() {
    double[] a = {0.0, 0.5, 1.0};
    double[] squares = Apply(a, Square);
    double[] sines = Apply(a, Math.Sin);
    Multiplier m = new Multiplier(2.0);
    double[] doubles =  Apply(a, m.Multiply);
  }
}

So what can be defined outside any class in C#?

Based on the above examples, can the definition of  any type be defined outside any class?

Thanks.


问:
How does a broadcast receiver work among activities?
I have multiple activities suppose A , B , C , D and all are register to same BroadCastReceiver. While sending the broadcast message in which order activities will receive the broadcast intents. Is it in order like A , B , C , D or random.

Please let me know, give me some suggestions.

答: There are three way to send Broadcast in android. Namely 1. sendBroadcast 2. sendOrderedBroadcast, and 3. sendStickyBroadcast. Here you are talking about sendBroadcast so it will simply dispatch the broadcast to registered broadcast receiver regardless in which order broadcast has been registered.


问:
Can someone help me with onclick events created programmatically?
I have a script that generates a set of divs programmatically, but I can't figure out how to get the onclick events to work for each div independently.

sample code snippet

```<code>for (i = 0;i < allEntries.length;i++) {
    //Build a div for this entry
    var containerID = "dayTimeMinutesContainer-" + allEntries[i][10] + "-" + allEntries[i][6];
    var contSubj = allEntries[i][4];
    var divid = allEntries[i][12];

    dojo.query(dojo.create("div",{id:divid},containerID))
        .onclick(function(){alert(contSubj);  //returns the last subject for all entries  ???
        });
}
</code>```

As shown in the code snippet, the onclick event fires for each div created - but it ALWAYS returns the Subject (contSubj) from the last entry processed in the loop, regardless of the entry clicked.

I'm a dojo rookie, so I apologize if this seems to be a simple oversight.  I've spent hours seeking a solution, but haven't found anything similar.  Can someone point me in the right direction?  How can I create onclick events to work for each individual divid processed?

答:
SOLUTION... Thank you for the responses... always good to get additional insight.  I used the callback suggestion and solved this dilemma as shown.</p>

```<code>for (i = 0;i < allEntries.length;i++) {
    //Build a div for this entry
    var containerID = "dayTimeMinutesContainer-" + allEntries[i][10] + "-" + allEntries[i][6];
    var contSubj = allEntries[i][4];
    var divid = allEntries[i][12];

    dojo.query(dojo.create("div",{id:divid},containerID))
        .onclick(createCallback(contSubj));
}

function createCallback( subj ){
  return function(){
      alert(subj);
  }
}
</code>```

Body:
I have a script that generates a set of divs programmatically, but I can't figure out how to get the onclick events to work for each div independently.

sample code snippet

for (i = 0;i < allEntries.length;i++) {
    //Build a div for this entry
    var containerID = "dayTimeMinutesContainer-" + allEntries[i][10] + "-" + allEntries[i][6];
    var contSubj = allEntries[i][4];
    var divid = allEntries[i][12];

    dojo.query(dojo.create("div",{id:divid},containerID))
        .onclick(function(){alert(contSubj);  //returns the last subject for all entries  ???
        });
}

As shown in the code snippet, the onclick event fires for each div created - but it ALWAYS returns the Subject (contSubj) from the last entry processed in the loop, regardless of the entry clicked.

I'm a dojo rookie, so I apologize if this seems to be a simple oversight.  I've spent hours seeking a solution, but haven't found anything similar.  Can someone point me in the right direction?  How can I create onclick events to work for each individual divid processed?

Body:
SOLUTION... Thank you for the responses... always good to get additional insight.  I used the callback suggestion and solved this dilemma as shown.

for (i = 0;i < allEntries.length;i++) {
    //Build a div for this entry
    var containerID = "dayTimeMinutesContainer-" + allEntries[i][10] + "-" + allEntries[i][6];
    var contSubj = allEntries[i][4];
    var divid = allEntries[i][12];

    dojo.query(dojo.create("div",{id:divid},containerID))
        .onclick(createCallback(contSubj));
}

function createCallback( subj ){
  return function(){
      alert(subj);
  }
}


问:
Webpack loader test for files without certain part of filename
I keep my tests in the same folder as my components, and I'm trying to apply a webpack loader (istanbul-instrumenter-loader) to all files except the ones called exactly spec.js or that end with *Spec.js (so both components/SupportPage/spec.js and actions/SupportActionsSpec.js won't get included. I've tried getting a correct RegEx on regextester.com but I can't get it to work. Am I missing something?

答:
I got here trying to solve a similar problem relating to Angular 2 component styles imported via styleUrls. I thought I would add my solution as an extension to the accepted answer for posterity.

This solution distinguishes between component styles needing to be loaded with to-string-loader as opposed to the rest of the styles which can be loaded with style-loader instead.

If you configure components as follows:

```<code>@Component({
    selector: 'admin',
    styleUrls: ['./admin.component.scss'],
    templateUrl: './admin.component.html'
})
</code>```

You can use these rules:

```<code>// For components `to-string-loader`
{
    test: /\.css$/,
    use: ['to-string-loader', 'css-loader'],
    include: /\.component\.css$/
},

// For non-components `style-loader`
{
    test: /\.css$/,
    use: ['style-loader', 'css-loader'],
    exclude: /\.component\.css$/
}
</code>```

Body:
I got here trying to solve a similar problem relating to Angular 2 component styles imported via styleUrls. I thought I would add my solution as an extension to the accepted answer for posterity.

This solution distinguishes between component styles needing to be loaded with to-string-loader as opposed to the rest of the styles which can be loaded with style-loader instead.

If you configure components as follows:

@Component({
    selector: 'admin',
    styleUrls: ['./admin.component.scss'],
    templateUrl: './admin.component.html'
})

You can use these rules:

// For components `to-string-loader`
{
    test: /\.css$/,
    use: ['to-string-loader', 'css-loader'],
    include: /\.component\.css$/
},

// For non-components `style-loader`
{
    test: /\.css$/,
    use: ['style-loader', 'css-loader'],
    exclude: /\.component\.css$/
}


问:
Extend Django User model (make it work in request.user), Django 1.2.3
I'd like to extend the User model, so I can put in some extra fields and functions (not only fields, keep in mind, or else (well, still) I could use get_profile(), which I think is ugly).

Also I would like to use that new extended User model in request.user, like this:

Extended User model:

```<code># imports etc

class CustomUser(User):
    extra_field = ...

    def extra_function(self):
        ...

        return ...
</code>```

Example usage view:

```<code># imports etc

def extra_function_view(request):
    print request.user.username
    print request.user.extra_field

    request.user.extra_function()

    return HttpResponse( ... )
</code>```

The above code obviously doesn't work, because extra_field and extra_function are not in the User model.

Now I found a method to accomplish this, using an authentication backend, which is kinda complex, and which I couldn't get to work in Django 1.2.3.

```<code>AUTHENTICATION_BACKENDS = (
    'myproject.auth_backends.CustomUserModelBackend',
)
...

CUSTOM_USER_MODEL = 'accounts.CustomUser'
</code>```

Further more tried some other methods, like using signals, which didn't work. To me, the only solution seems to adjust the User model within Django (which isn't an elegant solution, adjusting Django's source code, but is code-wise a neat solution).

So I'm looking for a solution for this.. has anyone done this before?

Thanks for now

Stefan

答:
You're on the right track with adjusting the Authentication Backend.

Authentication backends can be pretty simple, here is a snip of ours we use in our project.

```<code>class LocalAccount(object):
    def authenticate(self, system=None, username=None, password=None):
        try:
            user = User.objects.get(system=system, alias=username)
            if user.check_password(password):
                return user
        except User.DoesNotExist:
            return None

    def get_user(self, user_id):
        'returns user'

    def get_all_permissions(self, user_obj):
        'returns user permissions'

    def has_perm(self, user_obj, perm):
        'verifies permission, remember you can hardcode these'

    def get_group_permissions(self, user_obj):
        return set() #We don't use this

    def has_module_perms(self, user_obj, app_label):
        return False
</code>```

This allows you to return whatever user model you wish to return. As long as your user model is basically like Django's user model you won't run into any issues.

Also keep in mind that extending user and including the application will cause both the Django User model and your own User model to be in the database with model inheritance. Your best option is to copy the Django User model and alter it. For our project we don't even include 'auth' in the installed apps setting.

The concept here is Python duck typing. As long as the User model that you create has the same interface that Django is looking for (methods, fields) it doesn't matter if it's actually the User class it specified.

Body:
I'd like to extend the User model, so I can put in some extra fields and functions (not only fields, keep in mind, or else (well, still) I could use get_profile(), which I think is ugly).

Also I would like to use that new extended User model in request.user, like this:

Extended User model:

# imports etc

class CustomUser(User):
    extra_field = ...

    def extra_function(self):
        ...

        return ...

Example usage view:

# imports etc

def extra_function_view(request):
    print request.user.username
    print request.user.extra_field

    request.user.extra_function()

    return HttpResponse( ... )

The above code obviously doesn't work, because extra_field and extra_function are not in the User model.

Now I found a method to accomplish this, using an authentication backend, which is kinda complex, and which I couldn't get to work in Django 1.2.3.

AUTHENTICATION_BACKENDS = (
    'myproject.auth_backends.CustomUserModelBackend',
)
...

CUSTOM_USER_MODEL = 'accounts.CustomUser'

Further more tried some other methods, like using signals, which didn't work. To me, the only solution seems to adjust the User model within Django (which isn't an elegant solution, adjusting Django's source code, but is code-wise a neat solution).

So I'm looking for a solution for this.. has anyone done this before?

Thanks for now

Stefan

Body:
You're on the right track with adjusting the Authentication Backend.

Authentication backends can be pretty simple, here is a snip of ours we use in our project.

class LocalAccount(object):
    def authenticate(self, system=None, username=None, password=None):
        try:
            user = User.objects.get(system=system, alias=username)
            if user.check_password(password):
                return user
        except User.DoesNotExist:
            return None

    def get_user(self, user_id):
        'returns user'

    def get_all_permissions(self, user_obj):
        'returns user permissions'

    def has_perm(self, user_obj, perm):
        'verifies permission, remember you can hardcode these'

    def get_group_permissions(self, user_obj):
        return set() #We don't use this

    def has_module_perms(self, user_obj, app_label):
        return False

This allows you to return whatever user model you wish to return. As long as your user model is basically like Django's user model you won't run into any issues.

Also keep in mind that extending user and including the application will cause both the Django User model and your own User model to be in the database with model inheritance. Your best option is to copy the Django User model and alter it. For our project we don't even include 'auth' in the installed apps setting.

The concept here is Python duck typing. As long as the User model that you create has the same interface that Django is looking for (methods, fields) it doesn't matter if it's actually the User class it specified.


问:
Convert a list of words to a list of integers in scikit-learn
I want to convert a list of words to a list of integers in scikit-learn, and do so for a corpus that consists of a list of lists of words. E.g. the corpus can be a bunch of sentences.

I can do as follows using  sklearn.feature_extraction.text.CountVectorizer, but is there any simpler way? I suspect I may be missing some CountVectorizer functionalities, as it's a common pre-processing step in natural language processing. In this code I first fit CountVectorizer, then I have to iterate over each words of each list of words to generate the list of integers.

```<code>import sklearn
import sklearn.feature_extraction
import numpy as np

def reverse_dictionary(dict):
    '''
    http://stackoverflow.com/questions/483666/python-reverse-inverse-a-mapping
    '''
    return {v: k for k, v in dict.items()}

vectorizer = sklearn.feature_extraction.text.CountVectorizer(min_df=1)

corpus = ['This is the first document.',
        'This is the second second document.',
        'And the third one.',
        'Is this the first document? This is right.',]

X = vectorizer.fit_transform(corpus).toarray()

tokenizer = vectorizer.build_tokenizer()
output_corpus = []
for line in corpus:
    line = tokenizer(line.lower())
    output_line = np.empty_like(line, dtype=np.int)
    for token_number, token in np.ndenumerate(line):
        output_line[token_number] = vectorizer.vocabulary_.get(token)
    output_corpus.append(output_line)
print('output_corpus: {0}'.format(output_corpus))

word2idx = vectorizer.vocabulary_
print('word2idx: {0}'.format(word2idx))

idx2word = reverse_dictionary(word2idx)
print('idx2word: {0}'.format(idx2word))
</code>```

outputs:

```<code>output_corpus: [array([9, 3, 7, 2, 1]), # 'This is the first document.'
                array([9, 3, 7, 6, 6, 1]), # 'This is the second second document.'
                array([0, 7, 8, 4]), # 'And the third one.'
                array([3, 9, 7, 2, 1, 9, 3, 5])] # 'Is this the first document? This is right.'
word2idx: {u'and': 0, u'right': 5, u'third': 8, u'this': 9, u'is': 3, u'one': 4,
           u'second': 6, u'the': 7, u'document': 1, u'first': 2}
idx2word: {0: u'and', 1: u'document', 2: u'first', 3: u'is', 4: u'one', 5: u'right',
           6: u'second', 7: u'the', 8: u'third', 9: u'this'}
</code>```

答:
I often use Counter to solve this in python, e.g.

```<code>from collections import Counter

corpus = ['This is the first document.',
        'This is the second second document.',
        'And the third one.',
        'Is this the first document? This is right.',]

#convert to str from list and split
as_one = ''
for sentence in corpus:
    as_one = as_one + ' ' + sentence

words = as_one.split()

from collections import Counter
counts = Counter(words)
vocab = sorted(counts, key=counts.get, reverse=True)
vocab_to_int = {word: ii for ii, word in enumerate(vocab, 1)}

print(vocab_to_int)
</code>```

output:

{'the': 1, 'This': 2, 'is': 3, 'first': 4, 'document.': 5, 'second':
  6, 'And': 7, 'third': 8, 'one.': 9, 'Is': 10, 'this': 11, 'document?':
  12, 'right.': 13}

Body:
I want to convert a list of words to a list of integers in scikit-learn, and do so for a corpus that consists of a list of lists of words. E.g. the corpus can be a bunch of sentences.

I can do as follows using  sklearn.feature_extraction.text.CountVectorizer, but is there any simpler way? I suspect I may be missing some CountVectorizer functionalities, as it's a common pre-processing step in natural language processing. In this code I first fit CountVectorizer, then I have to iterate over each words of each list of words to generate the list of integers.

import sklearn
import sklearn.feature_extraction
import numpy as np

def reverse_dictionary(dict):
    '''
    http://stackoverflow.com/questions/483666/python-reverse-inverse-a-mapping
    '''
    return {v: k for k, v in dict.items()}

vectorizer = sklearn.feature_extraction.text.CountVectorizer(min_df=1)

corpus = ['This is the first document.',
        'This is the second second document.',
        'And the third one.',
        'Is this the first document? This is right.',]

X = vectorizer.fit_transform(corpus).toarray()

tokenizer = vectorizer.build_tokenizer()
output_corpus = []
for line in corpus:
    line = tokenizer(line.lower())
    output_line = np.empty_like(line, dtype=np.int)
    for token_number, token in np.ndenumerate(line):
        output_line[token_number] = vectorizer.vocabulary_.get(token)
    output_corpus.append(output_line)
print('output_corpus: {0}'.format(output_corpus))

word2idx = vectorizer.vocabulary_
print('word2idx: {0}'.format(word2idx))

idx2word = reverse_dictionary(word2idx)
print('idx2word: {0}'.format(idx2word))

outputs:

output_corpus: [array([9, 3, 7, 2, 1]), # 'This is the first document.'
                array([9, 3, 7, 6, 6, 1]), # 'This is the second second document.'
                array([0, 7, 8, 4]), # 'And the third one.'
                array([3, 9, 7, 2, 1, 9, 3, 5])] # 'Is this the first document? This is right.'
word2idx: {u'and': 0, u'right': 5, u'third': 8, u'this': 9, u'is': 3, u'one': 4,
           u'second': 6, u'the': 7, u'document': 1, u'first': 2}
idx2word: {0: u'and', 1: u'document', 2: u'first', 3: u'is', 4: u'one', 5: u'right',
           6: u'second', 7: u'the', 8: u'third', 9: u'this'}

Body:
I often use Counter to solve this in python, e.g.

from collections import Counter

corpus = ['This is the first document.',
        'This is the second second document.',
        'And the third one.',
        'Is this the first document? This is right.',]

#convert to str from list and split
as_one = ''
for sentence in corpus:
    as_one = as_one + ' ' + sentence

words = as_one.split()

from collections import Counter
counts = Counter(words)
vocab = sorted(counts, key=counts.get, reverse=True)
vocab_to_int = {word: ii for ii, word in enumerate(vocab, 1)}

print(vocab_to_int)

output:

{'the': 1, 'This': 2, 'is': 3, 'first': 4, 'document.': 5, 'second':
  6, 'And': 7, 'third': 8, 'one.': 9, 'Is': 10, 'this': 11, 'document?':
  12, 'right.': 13}


问:
Unauthorized request handling in Angular.js with Box API v2
I am developing a web app with angular.js v1.5.7, which integrates Box Services using oauth2 authentication on the client-side to retrive the tokens for accessing the API.

I have a problem when the access token expires. I make a request with the expired token, and I receive a 401 (unauthorized) response that I can't catch in Angular because the response has a status code of -1.  This happens before I am able to catch this response in a $httpsInterceptor.

I made a repository in GitHub to demonstrate this behavior https://github.com/danyfu/box-api-test, it's an express server that serves the 3000 port the Angular app.

In the Angular app, it's only a button you click to request to the API to GET the root folder of the user:

```<code>https://api.box.com/2.0/folders/0?fields=id,name,type,item_status,size,item_collection,shared_link
</code>```

With the request I add the access token.

When I make the request with the invalid token, the response returns two error logs.
Errors

When I make the request with a valid access token, it retrieves the folder info and a status of 200.
Correct Information

答:
You can use passport-box which will do the oauth flow in your app.

https://github.com/bluedge/passport-box

Here's an example where I use it as well:

https://github.com/kendomen/boxadmin

Body:
I am developing a web app with angular.js v1.5.7, which integrates Box Services using oauth2 authentication on the client-side to retrive the tokens for accessing the API.

I have a problem when the access token expires. I make a request with the expired token, and I receive a 401 (unauthorized) response that I can't catch in Angular because the response has a status code of -1.  This happens before I am able to catch this response in a $httpsInterceptor.

I made a repository in GitHub to demonstrate this behavior https://github.com/danyfu/box-api-test, it's an express server that serves the 3000 port the Angular app.

In the Angular app, it's only a button you click to request to the API to GET the root folder of the user:

https://api.box.com/2.0/folders/0?fields=id,name,type,item_status,size,item_collection,shared_link

With the request I add the access token.

When I make the request with the invalid token, the response returns two error logs.
Errors

When I make the request with a valid access token, it retrieves the folder info and a status of 200.
Correct Information


问:
how to build OpenBR?
When i build OpenBR on windows and when i type following code on VS2015 x86 x64 Cross Tools Command Prompt as mentioned in A hacker's guide to building, editing, and running OpenBR :

```<code>cmake -G "CodeBlocks - NMake Makefiles" -DCMAKE_PREFIX_PATH="H:/opencv-2.4.11/build/install;H:/Qt/Qt5.8/5.8/msvc2015_64" -DCMAKE_INSTALL_PREFIX="./install" -DBR_INSTALL_DEPENDENCIES=ON -DCMAKE_BUILD_TYPE=Release ..
</code>```

i get this error :

```<code>H:\openbr\build-msvc2015>cmake -G "CodeBlocks - NMake Makefiles" -DCMAKE_PREFIX_
PATH="H:/opencv-2.4.11/build/install;H:/Qt/Qt5.8/5.8/msvc2015_64" -DC
MAKE_INSTALL_PREFIX="./install" -DBR_INSTALL_DEPENDENCIES=ON -DCMAKE_BUILD_TYPE=
Release ..
-- The C compiler identification is MSVC 19.0.23506.0
-- The CXX compiler identification is MSVC 19.0.23506.0
-- Check for working C compiler: C:/Program Files (x86)/Microsoft Visual Studio
14.0/VC/bin/x86_amd64/cl.exe
-- Check for working C compiler: C:/Program Files (x86)/Microsoft Visual Studio
14.0/VC/bin/x86_amd64/cl.exe -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working CXX compiler: C:/Program Files (x86)/Microsoft Visual Studi
o 14.0/VC/bin/x86_amd64/cl.exe
-- Check for working CXX compiler: C:/Program Files (x86)/Microsoft Visual Studi
o 14.0/VC/bin/x86_amd64/cl.exe -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- OpenCV ARCH: x64
-- OpenCV RUNTIME:
-- OpenCV STATIC: OFF
CMake Warning at H:/opencv-2.4.11/build-msvc2015/install/OpenCVConfig.cmake:161
(message):
  Found OpenCV Windows Pack but it has not binaries compatible with your
  configuration.

  You should manually point CMake variable OpenCV_DIR to your build of OpenCV
  library.
Call Stack (most recent call first):
  CMakeLists.txt:88 (find_package)

CMake Error at CMakeLists.txt:88 (find_package):
  Found package configuration file:

    H:/opencv-2.4.11/build-msvc2015/install/OpenCVConfig.cmake

  but it set OpenCV_FOUND to FALSE so package "OpenCV" is considered to be
  NOT FOUND.

-- Configuring incomplete, errors occurred!
See also "C:/openbr/build-msvc2015/CMakeFiles/CMakeOutput.log".
</code>```

what's problem?

答:
Try to edit OpenCVConfig.cmake file (H:/opencv-2.4.11/build-msvc2015/install/OpenCVConfig.cmake). And set OpenCV_RUNTIME to VC14:</p>

```<code>elseif(MSVC_VERSION EQUAL 1800)
  set(OpenCV_RUNTIME vc12)
elseif(MSVC_VERSION EQUAL 1900)
  set(OpenCV_RUNTIME vc14)
endif()
</code>```

Title: how to build OpenBR?

Body:
When i build OpenBR on windows and when i type following code on VS2015 x86 x64 Cross Tools Command Prompt as mentioned in A hacker's guide to building, editing, and running OpenBR :

cmake -G "CodeBlocks - NMake Makefiles" -DCMAKE_PREFIX_PATH="H:/opencv-2.4.11/build/install;H:/Qt/Qt5.8/5.8/msvc2015_64" -DCMAKE_INSTALL_PREFIX="./install" -DBR_INSTALL_DEPENDENCIES=ON -DCMAKE_BUILD_TYPE=Release ..

i get this error :

H:\openbr\build-msvc2015>cmake -G "CodeBlocks - NMake Makefiles" -DCMAKE_PREFIX_
PATH="H:/opencv-2.4.11/build/install;H:/Qt/Qt5.8/5.8/msvc2015_64" -DC
MAKE_INSTALL_PREFIX="./install" -DBR_INSTALL_DEPENDENCIES=ON -DCMAKE_BUILD_TYPE=
Release ..
-- The C compiler identification is MSVC 19.0.23506.0
-- The CXX compiler identification is MSVC 19.0.23506.0
-- Check for working C compiler: C:/Program Files (x86)/Microsoft Visual Studio
14.0/VC/bin/x86_amd64/cl.exe
-- Check for working C compiler: C:/Program Files (x86)/Microsoft Visual Studio
14.0/VC/bin/x86_amd64/cl.exe -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working CXX compiler: C:/Program Files (x86)/Microsoft Visual Studi
o 14.0/VC/bin/x86_amd64/cl.exe
-- Check for working CXX compiler: C:/Program Files (x86)/Microsoft Visual Studi
o 14.0/VC/bin/x86_amd64/cl.exe -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- OpenCV ARCH: x64
-- OpenCV RUNTIME:
-- OpenCV STATIC: OFF
CMake Warning at H:/opencv-2.4.11/build-msvc2015/install/OpenCVConfig.cmake:161
(message):
  Found OpenCV Windows Pack but it has not binaries compatible with your
  configuration.

  You should manually point CMake variable OpenCV_DIR to your build of OpenCV
  library.
Call Stack (most recent call first):
  CMakeLists.txt:88 (find_package)

CMake Error at CMakeLists.txt:88 (find_package):
  Found package configuration file:

    H:/opencv-2.4.11/build-msvc2015/install/OpenCVConfig.cmake

  but it set OpenCV_FOUND to FALSE so package "OpenCV" is considered to be
  NOT FOUND.

-- Configuring incomplete, errors occurred!
See also "C:/openbr/build-msvc2015/CMakeFiles/CMakeOutput.log".

what's problem?

Body:
Try to edit OpenCVConfig.cmake file (H:/opencv-2.4.11/build-msvc2015/install/OpenCVConfig.cmake). And set OpenCV_RUNTIME to VC14:

elseif(MSVC_VERSION EQUAL 1800)
  set(OpenCV_RUNTIME vc12)
elseif(MSVC_VERSION EQUAL 1900)
  set(OpenCV_RUNTIME vc14)
endif()


问:
Fix already commited CRLF in git
I have set git to core.autocrlf = true. However it seems there are already commited files that have CRLF inside the repository. When I modify such a file, then git seems to assume that no implicit conversion is necessary and as a result git diff shows those annoying ^M at the end of each line. For other files which are checked out as CRLF but commited as LF I do not see any ^M at the end of changed lines. How can I fix the problematic files in my repository?

I do not want to use solutions that use git filter-branch since I do not want to rewrite the history. I want to create add a new commit that fixes the problematic files. Preferably I would like to fix individual files and not everything at once.

答: Use your favorite text editor to change all CRLF to LF. Any good programming editor or IDE has an option for which EOL sequence to use. Change it to Unix style and reformat all files in your project. Then make a commit.</p>

Title: Fix already commited CRLF in git


问:
observeSingleEvent(of:with:) fetching old data
Background:

I have an app where new users complete a sign-up form (consisting of a username, email, and a password) to register for an account. When the new user submits the form, the app checks its Firebase Database to see if the username has already been taken. The problem here is that observeSingleEvent(of:with:) is not getting the newest data. When I update the data directly from the Firebase console, the changes are not reflected back in the returned results of observeSingleEvent(of:with:). Even between app restarts, the new data changes are not returned.

The only thing I've seen on the issue is here. A user says not to have persistence enabled when using observeSingleEvent(of:with:). But, I have persistence disabled. Also, I set the keepSynced() on the FIRDatabase instance to false (and I've tried true as well). No luck with either setting.

Here's an example of what I am trying:

```<code>let usersDatabaseReference = FIRDatabase.database().reference().child("users")
usersDatabaseReference.keepSynced(false)

// Query the database to see if the username is available
// The user with the username "mark" was removed from the database via the Firebase console
let username = "mark" // This user used to exist in the database (and was previously added through the app).
usersDatabaseReference.child(username).observeSingleEvent(of: .value, with: { (snapshot) in ... } )
</code>```

The above code block should return the newest data (one where the user "mark" should not exist).

I am wondering if anyone else ran into this problem, or if anyone has possible solutions.

Note: Developing using iOS 10.1 and swift 3.

答: I recommend you refactor your JSON data model using the username as key. Doing this, you should get an error when trying to create a duplicate user in the database.

Body:
Background:

I have an app where new users complete a sign-up form (consisting of a username, email, and a password) to register for an account. When the new user submits the form, the app checks its Firebase Database to see if the username has already been taken. The problem here is that observeSingleEvent(of:with:) is not getting the newest data. When I update the data directly from the Firebase console, the changes are not reflected back in the returned results of observeSingleEvent(of:with:). Even between app restarts, the new data changes are not returned.

The only thing I've seen on the issue is here. A user says not to have persistence enabled when using observeSingleEvent(of:with:). But, I have persistence disabled. Also, I set the keepSynced() on the FIRDatabase instance to false (and I've tried true as well). No luck with either setting.

Here's an example of what I am trying:

let usersDatabaseReference = FIRDatabase.database().reference().child("users")
usersDatabaseReference.keepSynced(false)

// Query the database to see if the username is available
// The user with the username "mark" was removed from the database via the Firebase console
let username = "mark" // This user used to exist in the database (and was previously added through the app).
usersDatabaseReference.child(username).observeSingleEvent(of: .value, with: { (snapshot) in ... } )

The above code block should return the newest data (one where the user "mark" should not exist).

I am wondering if anyone else ran into this problem, or if anyone has possible solutions.

Note: Developing using iOS 10.1 and swift 3.


问:
difference between spring webflow and MVC
what is the basic difference between these two pattern how webflow runs on top of MVC I am not clear on these design</p>

答:
Spring MVC is a framework build on top of the model-view-controller pattern where you could bind a view(View layer) to a controller to display the data(Model).

Spring webflow inherits all of spring MVC features but is designed more as a state machine.

Webflow offers support for wizard style usecases when the output of an action is the input of another(transitions which can be bound to spring-beans).

For example :

There is a clear start and an end point.

The user must go through a set of screens in a specific order.

The changes are not finalized until the last step.

Once complete it shouldn't be possible to repeat a transaction accidentally

You can find more info on this topic here


问:
Find max value from input text file in java
Im trying to get the max number in a certain text file the user inputs. I also put it into separate methods. Heres what I have so far:

```<code>public static void FindMax(String file)throws IOException{
 int maximum = 0;
 Scanner fileScanner = new Scanner(new File(file)); {
            int big = fileScanner.nextInt();
            while (fileScanner.hasNextInt()) {
                int num = fileScanner.nextInt();
                if(num > big) {
                   maximum++;
                     System.out.println(num);;
                }
           }
  }
}
public static void main(String[] args)throws IOException{

    Scanner keyboard = new Scanner(System.in);
     String file;

      System.out.print("Enter file: ");
       file = keyboard.nextLine();

       FindMax(file);

}
</code>```

The output is printing all the content in the text file except the first value, instead of printing the maximum. For example if the text file is:

```<code>1
2
3
4
5
</code>```

It only prints 2,3,4, and 5 and I don't know why.How can I get the max value? Id appreciate any help/advice. Thanks in advance.

EDIT: All of you guys are saying similar solutions but when I try them, it just prints the same output. Im very confused.

答:
```<code>import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class FindMax {
    public static void findMax(String file) throws IOException {
        Scanner fileScanner = new Scanner(new File(file));
        int max = fileScanner.nextInt();
        while (fileScanner.hasNextInt()) {
            int num = fileScanner.nextInt();
            if (num > max) {
                max=num;
            }
        }
        System.out.println(max);
        fileScanner.close();
    }

    public static void main(String[] args) throws IOException {

        Scanner keyboard = new Scanner(System.in);
        String file;

        System.out.print("Enter file: ");
        file = keyboard.nextLine();

        findMax(file);
        keyboard.close();
    }
}
</code>```

I fixed logical errors in your code. I am not sure why you defined the maximum variable. It is not really used in any meaningful way in your code. You might want to consider changing the return type of your method to "int" and return the found maximum.

Also, method names must always start with small letters:
http://www.javatpoint.com/java-naming-conventions

You should also always correctly close your resources:
How to Correctly Close Resources

Body:
Im trying to get the max number in a certain text file the user inputs. I also put it into separate methods. Heres what I have so far:

public static void FindMax(String file)throws IOException{
 int maximum = 0;
 Scanner fileScanner = new Scanner(new File(file)); {
            int big = fileScanner.nextInt();
            while (fileScanner.hasNextInt()) {
                int num = fileScanner.nextInt();
                if(num > big) {
                   maximum++;
                     System.out.println(num);;
                }
           }
  }
}
public static void main(String[] args)throws IOException{

    Scanner keyboard = new Scanner(System.in);
     String file;

      System.out.print("Enter file: ");
       file = keyboard.nextLine();

       FindMax(file);

}

The output is printing all the content in the text file except the first value, instead of printing the maximum. For example if the text file is:

1
2
3
4
5

It only prints 2,3,4, and 5 and I don't know why.How can I get the max value? Id appreciate any help/advice. Thanks in advance.

EDIT: All of you guys are saying similar solutions but when I try them, it just prints the same output. Im very confused.

Body:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class FindMax {
    public static void findMax(String file) throws IOException {
        Scanner fileScanner = new Scanner(new File(file));
        int max = fileScanner.nextInt();
        while (fileScanner.hasNextInt()) {
            int num = fileScanner.nextInt();
            if (num > max) {
                max=num;
            }
        }
        System.out.println(max);
        fileScanner.close();
    }

    public static void main(String[] args) throws IOException {

        Scanner keyboard = new Scanner(System.in);
        String file;

        System.out.print("Enter file: ");
        file = keyboard.nextLine();

        findMax(file);
        keyboard.close();
    }
}

I fixed logical errors in your code. I am not sure why you defined the maximum variable. It is not really used in any meaningful way in your code. You might want to consider changing the return type of your method to "int" and return the found maximum.

Also, method names must always start with small letters:
http://www.javatpoint.com/java-naming-conventions

You should also always correctly close your resources:
How to Correctly Close Resources