问:
Filtering List from a List
Bottom line is I would like a linq statement that returns the same list as the code below.

I feel like this is possible and I feel like I got very close before I gave up and just spelled out what I wanted with more lines of code.

Although I would love and appreciate anyone that could demonstrate what I'm looking to achieve for the future and to replace what I have.

```<code>public ObservableCollection<VarItem> IndexChannels
{
    get
    {
        ObservableCollection<VarItem> filtered = new ObservableCollection<VarItem>();

        filtered.Add(indexChannels.First());//add Disabled no matter what

        //add the cur channels selected index if it isn't already disabled
        if (!filtered.Contains(indexChannels.FirstOrDefault(i => i == CurChannel.IndexChannel)))
        {
           filtered.Add(indexChannels.FirstOrDefault(i => i == CurChannel.IndexChannel));
        }

        foreach (PdioChannelModel ch in channels)
        {
           //if the channels mode isn't q-decode or quad index add its Number as an index
           if (ch.Mode.Value != "Q-Decode" && ch.Mode.Value != "Quad Index")
           {
              filtered.Add(indexChannels.FirstOrDefault(i => i.ID == ch.Number));
           }
        }
        return filtered;
    }
}
</code>```

Basic structure of VarItem

public class VarItem
   {
      public int ID { get; private set; }
      public string Value { get; private set; }
      public Dictionary MetaData { get; private set; }

```<code>  public VarItem(int id, string value)
  {
     this.ID = id;
     this.Value = value;
     MetaData = new Dictionary<string, string>();
  }
</code>```

example master list contains VarItems:

-1, "Disable"

1, "Channel 1"

2, "Channel 2"

3, "Channel 3"

Filtered list should always contain VarItem(-1, Disabled). It should also contain the VarItem where the ID matches CurChannel.IndexChanneland lastly it sould contain any VarItems where the ID matches any PdioChannelModel.Number where PdioChannelModel.Mode.Value != "Q-Decode" or "Quad Index"

If I missed any detail needed let me know. If I confused you and wrote to much or need clarification just let me know as well.

答:
Do you care if you add null values to your ObservableCollection? If you want to exclude null values, then FirstOrDefault is not the right method to use inside your foreach. If, on the other hand, you know for sure than every channel Number property will exist at least once in indexChannels, then just use First. That way if your assumption is wrong (and Number does not match any ID), then First will throw an exception, which is probably what you want instead of a NullReferenceException later on that will be harder to debug. If, in addition, you know for sure that every channel Number property will exist only once in indexChannels, then use Single, so you get an exception when this second assumption is violated. That again, is easier to debug than some unexpected behavior later.

Here's an example solution:

```<code>return new ObservableCollection<VarItem>(
    indexChannels
    .Take(1)
    .Union(indexChannels.Where(i => i == CurChannel.IndexChannel).Take(1))
    .Union(channels
        .Where(c => c.Mode.Value != "Q-Decode" &&
                    c.Mode.Value != "Quad Index")
        // The following line could be turned into
        // .Select(c => indexChannels.First(i => i.ID == c.Number))
        // OR
        // .Select(c => indexChannels.Single(i => i.ID == c.Number))
        // OR
        // .SelectMany(c => indexChannels.Where(i => i.ID == c.Number))
        // depending on how many channels in indexChannels
        // are expected to match each Number property.
        .Select(c => indexChannels.FirstOrDefault(i => i.ID == c.Number))
);
</code>```

Title: Filtering List from a List

Body:
Bottom line is I would like a linq statement that returns the same list as the code below.

I feel like this is possible and I feel like I got very close before I gave up and just spelled out what I wanted with more lines of code.

Although I would love and appreciate anyone that could demonstrate what I'm looking to achieve for the future and to replace what I have.

public ObservableCollection<VarItem> IndexChannels
{
    get
    {
        ObservableCollection<VarItem> filtered = new ObservableCollection<VarItem>();

        filtered.Add(indexChannels.First());//add Disabled no matter what

        //add the cur channels selected index if it isn't already disabled
        if (!filtered.Contains(indexChannels.FirstOrDefault(i => i == CurChannel.IndexChannel)))
        {
           filtered.Add(indexChannels.FirstOrDefault(i => i == CurChannel.IndexChannel));
        }

        foreach (PdioChannelModel ch in channels)
        {
           //if the channels mode isn't q-decode or quad index add its Number as an index
           if (ch.Mode.Value != "Q-Decode" && ch.Mode.Value != "Quad Index")
           {
              filtered.Add(indexChannels.FirstOrDefault(i => i.ID == ch.Number));
           }
        }
        return filtered;
    }
}

Basic structure of VarItem

public class VarItem
   {
      public int ID { get; private set; }
      public string Value { get; private set; }
      public Dictionary MetaData { get; private set; }

  public VarItem(int id, string value)
  {
     this.ID = id;
     this.Value = value;
     MetaData = new Dictionary<string, string>();
  }

example master list contains VarItems:

-1, "Disable"

1, "Channel 1"

2, "Channel 2"

3, "Channel 3"

Filtered list should always contain VarItem(-1, Disabled). It should also contain the VarItem where the ID matches CurChannel.IndexChanneland lastly it sould contain any VarItems where the ID matches any PdioChannelModel.Number where PdioChannelModel.Mode.Value != "Q-Decode" or "Quad Index"

If I missed any detail needed let me know. If I confused you and wrote to much or need clarification just let me know as well.

Body:
Do you care if you add null values to your ObservableCollection? If you want to exclude null values, then FirstOrDefault is not the right method to use inside your foreach. If, on the other hand, you know for sure than every channel Number property will exist at least once in indexChannels, then just use First. That way if your assumption is wrong (and Number does not match any ID), then First will throw an exception, which is probably what you want instead of a NullReferenceException later on that will be harder to debug. If, in addition, you know for sure that every channel Number property will exist only once in indexChannels, then use Single, so you get an exception when this second assumption is violated. That again, is easier to debug than some unexpected behavior later.

Here's an example solution:

return new ObservableCollection<VarItem>(
    indexChannels
    .Take(1)
    .Union(indexChannels.Where(i => i == CurChannel.IndexChannel).Take(1))
    .Union(channels
        .Where(c => c.Mode.Value != "Q-Decode" &&
                    c.Mode.Value != "Quad Index")
        // The following line could be turned into
        // .Select(c => indexChannels.First(i => i.ID == c.Number))
        // OR
        // .Select(c => indexChannels.Single(i => i.ID == c.Number))
        // OR
        // .SelectMany(c => indexChannels.Where(i => i.ID == c.Number))
        // depending on how many channels in indexChannels
        // are expected to match each Number property.
        .Select(c => indexChannels.FirstOrDefault(i => i.ID == c.Number))
);


来源: stackexchange

问:
Changing Passenger Default Error Page for Nginx
Currently if there's a problem launching a Rails app on our server, users are taken to a Passenger error page with an error like "Ruby (Rack) application could not be started".

Is it possible to customize this error page and display something else so users of a live site don't see this?

I'm using nginx for the server.

Thanks

答:
In testing Passenger 5.1, I found that setting passenger_friendly_error_pages off is not enough to change the default error page. This disables exposing backtrace or environment variables but still shows Passenger's error page.

To resolve this I had to set the following:

```<code>passenger_intercept_errors on;
error_page 500 /500.html;
</code>```

The command passenger_intercept_errors tells nginx to handle status codes of 400 or higher. The error_page command customizes the error. You might want to customize other errors as well.

For a Rails app, the location of the pages is relative to the public folder of the app (what you set in the root command for nginx).

As mentioned is this comment, the similar configuration for Apache is:

```<code>PassengerErrorOverride on
ErrorDocument 500 /path/to/500.html
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In testing Passenger 5.1, I found that setting passenger_friendly_error_pages off is not enough to change the default error page. This disables exposing backtrace or environment variables but still shows Passenger's error page.

To resolve this I had to set the following:

passenger_intercept_errors on;
error_page 500 /500.html;

The command passenger_intercept_errors tells nginx to handle status codes of 400 or higher. The error_page command customizes the error. You might want to customize other errors as well.

For a Rails app, the location of the pages is relative to the public folder of the app (what you set in the root command for nginx).

As mentioned is this comment, the similar configuration for Apache is:

PassengerErrorOverride on
ErrorDocument 500 /path/to/500.html


问:
Regex for cleaning Google Alert URL
Looking for a Regex to remove everything before and including q= and after and including &ct form the following URL.

http://www.google.com/url?sa=X&q=http://www-possible-spam-link-com/foo-bar-foo-bar-foo-bar-foo-1-ea-from-foo.html&ct=ga&cad=:s7:f1:v0:d2:i2:lt:e0:p0:t1289126539:&cd=bar&usg=foo

答:
```<code>>>> re.match(r'http://.*?q=([^&]*).*?', url).group(1)
'http://www.foo.com/bar-foo-bar-foo-bar-foo-bar-1-ea-from-foo.html'
</code>```

You will also probably also need to decode the url in case it has any escaped entities such as & or %20. This is language-dependent though.

In PHP

```<code>preg_match('/^http:\\/\\/.*?q=([^&]*)/', $url, $matches);
print($matches[1]);
</code>```

ContentLicense: CC BY-SA 2.5

Title: Regex for cleaning Google Alert URL

Body:
>>> re.match(r'http://.*?q=([^&]*).*?', url).group(1)
'http://www.foo.com/bar-foo-bar-foo-bar-foo-bar-1-ea-from-foo.html'

You will also probably also need to decode the url in case it has any escaped entities such as & or %20. This is language-dependent though.

In PHP

preg_match('/^http:\\/\\/.*?q=([^&]*)/', $url, $matches);
print($matches[1]);


答:
You can compare all the elements in your dictionary list this way:</p>

```<code>import copy
li = [{
        "keep this value":5,
        "remove this":59
    },{
        "keep this value":5,
        "remove this":12
    }]

def compareList(li):
    result = copy.deepcopy(li[0])
    for element in li:
        for key in element:
            if key in result and result[key] != element[key]:
                del result[key]
    return result

print (compareList(li))
</code>```

Title: Find common key: value pair in dict for non hashable keys and values

Body:
i have a list of dictionaries as below:

    [{'EchoTime': 0,
      'FlipAngle': 90,
      'MRAcquisitionType': '2D',
      'MagneticFieldStrength': 3,
      'Manufacturer': 'SIEMENS',
      'ManufacturerModelName': 'TrioTim',
      'RepetitionTime': 2,
      'ScanOptions': 'FS',
      'ScanningSequence': 'EP',
      'SequenceName': 'epfid2d1_64',
      'SequenceVariant': 'SK',
      'SliceTiming': [[0.0025000000000000022],
       [0.5],
       [-0.030000000000000027],
       [0.46625],
       [0.168749999995],
       [-0.36124999999999996],
       [-0.46124999999500005],
       [0.036250000005000005]],
      'TaskName': 'tom'},
     {'EchoTime': 0,
      'FlipAngle': 90,
      'MRAcquisitionType': '2D',
      'MagneticFieldStrength': 3,
      'Manufacturer': 'SIEMENS',
      'ScanningSequence': 'EP',
      'SequenceName': 'epfid2d1_64',
      'SequenceVariant': 'SK',
      'SliceTiming': [[0.0037500000050000315],
       [0.5],
       [-0.030000000000000027],
       [0.46750000001500003],
       [-0.0625],
       [0.36750000001],
       [-0.16249999998999998],
       [0.33500000000499996],
       [-0.19499999998999995],
       [0.301250000005]],
      'TaskName': 'tom'},
       {'EchoTime': 0,
  'FlipAngle': 90,
  'MRAcquisitionType': '2D',
  'MagneticFieldStrength': 3,
  'RepetitionTime': 2,
  'ScanOptions': 'FS',
  'ScanningSequence': 'EP',
  'SequenceName': 'epfid2d1_64',
  'SequenceVariant': 'SK',
  'SliceTiming': [[0.0025000000000000022],
   [0.5],
   [-0.030000000000000027],
   [0.46625],
   [-0.19625000000000004],
   [0.301250000005],
   [-0.22875],
   [0.26749999999999996],
   [-0.26249999999500007]],
  'TaskName': 't1'},
  {'EchoTime': 0,
  'FlipAngle': 90,
  'MRAcquisitionType': '2D',
  'Manufacturer': 'SIEMENS',
  'ManufacturerModelName': 'TrioTim',
  'SequenceVariant': 'SK',
  'SliceTiming': [[0.0025000000000000022],
   [0.5],
   [-0.030000000000000027],
   [0.46625],
   [-0.06374999999999997],
   [0.43375000000499997],
   [-0.09624999999999995],
   [0.4],
   [-0.22875],
   [0.26749999999999996],
   [-0.26249999999500007],
   [0.235]],
  'TaskName': 'fb'}]

there are about 2000 dict in the list.
Now i want to find common key: value pair amongst all the dict in the list.
For the same i used following function:

def twodict_intersec(json1, json2):
    d = {x:json1[x] for x in json1 if x in json2}
    return d

for i in range(0,10,1):
    print(i)
    if i == 0:
        res = twodict_intersec(json_list[i], json_list[i+1])
    else:
        res = dict_intersect(res, json_list[i+1])
print(res)

But the output is something like below where each key contains list of all values instead of common value

res = {'EchoTime': [[[[[[[[[0, 0], 0], 0], 0], 0], 0], 0], 0], 0], 'FlipAngle': [[[[[[[[[90, 90], 90], 90], 90], 90], 90], 90], 90], 90], 'ManufacturerModelName': [[[[[[[[['TrioTim', 'TrioTim'], 'TrioTim'], 'TrioTim'], 'TrioTim'], 'TrioTim'], 'TrioTim'], 'TrioTim'], 'TrioTim']}

i am not able to get output where each key will have only one value which common in all dict instead of above situation. Can someone point out my mistake ?

Body:
You can compare all the elements in your dictionary list this way:

import copy
li = [{
        "keep this value":5,
        "remove this":59
    },{
        "keep this value":5,
        "remove this":12
    }]

def compareList(li):
    result = copy.deepcopy(li[0])
    for element in li:
        for key in element:
            if key in result and result[key] != element[key]:
                del result[key]
    return result

print (compareList(li))


问:
Turning a string into a dictionary
Having had a python class behind me, I was presented with this question in the next class and I seem to be having a mental block on how to even get started.

"Write a python program that asks the user for a string,  then create the following dictionary: The values are the letters in the string, with the corresponding key being the place in the string. For example if the user entered the string “ABC123” then the dictionary would be: D = {‘A’:0, ‘B’:1, ‘C’:2, ‘1’:3, ‘2’:4, ‘3’:5}

I started with asking for the user input with something simple like

```<code>s = input('Enter string: ')
</code>```

however, I do not know how to proceed to the next step. Any help would be much appreciated.

答:
```<code>In [55]: s = input("Enter a string: ")
Enter a string: ABC123

In [56]: d = {char:i for i,char in enumerate(s)}

In [57]: d
Out[57]: {'C': 2, '1': 3, '2': 4, '3': 5, 'B': 1, 'A': 0}
</code>```

Note however, that if there are repeated characters in the user's input, d will have the index of the last occurrence of each character:

```<code>In [62]: s = input("Enter a string: ")
Enter a string: ABC123A

In [63]: d = {char:i for i,char in enumerate(s)}

In [64]: d
Out[64]: {'C': 2, '1': 3, '2': 4, '3': 5, 'B': 1, 'A': 6}
</code>```

Title: Turning a string into a dictionary

Body:
Having had a python class behind me, I was presented with this question in the next class and I seem to be having a mental block on how to even get started.

"Write a python program that asks the user for a string,  then create the following dictionary: The values are the letters in the string, with the corresponding key being the place in the string. For example if the user entered the string “ABC123” then the dictionary would be: D = {‘A’:0, ‘B’:1, ‘C’:2, ‘1’:3, ‘2’:4, ‘3’:5}

I started with asking for the user input with something simple like

s = input('Enter string: ')

however, I do not know how to proceed to the next step. Any help would be much appreciated.

Body:
In [55]: s = input("Enter a string: ")
Enter a string: ABC123

In [56]: d = {char:i for i,char in enumerate(s)}

In [57]: d
Out[57]: {'C': 2, '1': 3, '2': 4, '3': 5, 'B': 1, 'A': 0}

Note however, that if there are repeated characters in the user's input, d will have the index of the last occurrence of each character:

In [62]: s = input("Enter a string: ")
Enter a string: ABC123A

In [63]: d = {char:i for i,char in enumerate(s)}

In [64]: d
Out[64]: {'C': 2, '1': 3, '2': 4, '3': 5, 'B': 1, 'A': 6}


问:
What metrics for GUI usability do you know?
Of course the best metric would be a happiness of your users.

But what metrics do you know for GUI usability measurements?

For example, one of the common metrics is a average click count to perform action.
What other metrics do you know?

答: I just look at where I want users to go and where (physically) they are going on screen, I do this with data from Google Analytics.</p>

OwnerDisplayName: aku

OwnerDisplayName: Unkwntech


问:
RFC documents to A4 format
When printing RFC documents on my A4 format printer I noticed that I print more than it is considered to be one page in RFC document. I figure this is because probably RFC is written in North American paper letter format (216 × 279 mm) and I want to use ISO A4 format (210 × 297 mm). Info on Paper size. So my question is if there is some way or program with which I would at least be able to print every letter format page on to the separate A4 format page. I know there will be some unused space at the bottom but at least there will just be one text page per A4 paper page. I tried changing paper size on printer from A4 to letter, but it didn't help.</p>

答: Use MS word to open RFC txt file from http://www.ietf.org/rfc/rfcXXXX.txt. It formats every RFC page to document page and you will be able to zoom/scale it anyway you want. Just printed one rfc myself:) </p>

Title: RFC documents to A4 format


问:
Media Query Triggering when it should not?
I have this test page.  Within it there's a .Test_container class that is supposed to have a flex box column layout unless the minimum width is 768 px.  This is the media query rule that is supposed to kick in at 768 px.

```<code>@media (min-width: 768px) index.css:1
 .u-md-flex-row {
     -webkit-box-orient: horizontal!important;
     -webkit-box-direction: normal!important;
      -ms-flex-direction: row!important;
      flex-direction: row!important;
 }
</code>```

If I uncheck `flex-direction: row then the layout renders in a column.  If I view the page on my cell phone or shrink the width below 768 px, then media query is still in effect.  Thoughts?

答:
Why you have all rules with !important? You must try to avoid that if you can. If you cant, anyway, I think you can use this:

```<code>@media only screen and (min-width: 768px){
    -webkit-box-orient: horizontal !important;
    -webkit-box-direction: normal !important;
    -ms-flex-direction: row !important;
    flex-direction: row !important;
}
</code>```

I can't test it right now but it should work

Body:
I have this test page.  Within it there's a .Test_container class that is supposed to have a flex box column layout unless the minimum width is 768 px.  This is the media query rule that is supposed to kick in at 768 px.

@media (min-width: 768px) index.css:1
 .u-md-flex-row {
     -webkit-box-orient: horizontal!important;
     -webkit-box-direction: normal!important;
      -ms-flex-direction: row!important;
      flex-direction: row!important;
 }

If I uncheck `flex-direction: row then the layout renders in a column.  If I view the page on my cell phone or shrink the width below 768 px, then media query is still in effect.  Thoughts?

Body:
Why you have all rules with !important? You must try to avoid that if you can. If you cant, anyway, I think you can use this:

@media only screen and (min-width: 768px){
    -webkit-box-orient: horizontal !important;
    -webkit-box-direction: normal !important;
    -ms-flex-direction: row !important;
    flex-direction: row !important;
}

I can't test it right now but it should work


问:
Cannot get MNIST database through Anaconda/jupyter
Hu guys,

I'm new to python/anaconda/jupyter/numPy, panda, etc.... so please excuse me if it's a really stupid question.
I'm trying to obtain MNIST database by using anaconda/jupyter. But everytime I get an HTTP error 500 at the end. Is it really a server problem (as 500 would suggest) or am I doing something wrong?

Input in jupyter:

```<code>from sklearn.datasets import fetch_mldata
mnist = fetch_mldata('MNIST original')
</code>```

Result:

```<code>    ---------------------------------------------------------------------------
    HTTPError                                 Traceback (most recent call last)
    <ipython-input-1-15dc285fb373> in <module>()
          1 from sklearn.datasets import fetch_mldata
    ----> 2 mnist = fetch_mldata('MNIST original')

    e:\ProgramData\Anaconda3\lib\site-packages\sklearn\datasets\mldata.py in fetch_mldata(dataname, target_name, data_name, transpose_data, data_home)
        140         urlname = MLDATA_BASE_URL % quote(dataname)
        141         try:
    --> 142             mldata_url = urlopen(urlname)
        143         except HTTPError as e:
        144             if e.code == 404:

    e:\ProgramData\Anaconda3\lib\urllib\request.py in urlopen(url, data, timeout, cafile, capath, cadefault, context)
        221     else:
        222         opener = _opener
    --> 223     return opener.open(url, data, timeout)
        224
        225 def install_opener(opener):

    e:\ProgramData\Anaconda3\lib\urllib\request.py in open(self, fullurl, data, timeout)
        530         for processor in self.process_response.get(protocol, []):
        531             meth = getattr(processor, meth_name)
    --> 532             response = meth(req, response)
        533
        534         return response

    e:\ProgramData\Anaconda3\lib\urllib\request.py in http_response(self, request, response)
        640         if not (200 <= code < 300):
        641             response = self.parent.error(
    --> 642                 'http', request, response, code, msg, hdrs)
        643
        644         return response

    e:\ProgramData\Anaconda3\lib\urllib\request.py in error(self, proto, *args)
        562             http_err = 0
        563         args = (dict, proto, meth_name) + args
    --> 564         result = self._call_chain(*args)
        565         if result:
        566             return result

    e:\ProgramData\Anaconda3\lib\urllib\request.py in _call_chain(self, chain, kind, meth_name, *args)
        502         for handler in handlers:
        503             func = getattr(handler, meth_name)
    --> 504             result = func(*args)
        505             if result is not None:
        506                 return result

    e:\ProgramData\Anaconda3\lib\urllib\request.py in http_error_302(self, req, fp, code, msg, headers)
        754         fp.close()
        755
    --> 756         return self.parent.open(new, timeout=req.timeout)
        757
        758     http_error_301 = http_error_303 = http_error_307 = http_error_302

    e:\ProgramData\Anaconda3\lib\urllib\request.py in open(self, fullurl, data, timeout)
        530         for processor in self.process_response.get(protocol, []):
        531             meth = getattr(processor, meth_name)
    --> 532             response = meth(req, response)
        533
        534         return response

    e:\ProgramData\Anaconda3\lib\urllib\request.py in http_response(self, request, response)
        640         if not (200 <= code < 300):
        641             response = self.parent.error(
    --> 642                 'http', request, response, code, msg, hdrs)
        643
        644         return response

    e:\ProgramData\Anaconda3\lib\urllib\request.py in error(self, proto, *args)
        568         if http_err:
        569             args = (dict, 'default', 'http_error_default') + orig_args
    --> 570             return self._call_chain(*args)
        571
        572 # XXX probably also want an abstract factory that knows when it makes

    e:\ProgramData\Anaconda3\lib\urllib\request.py in _call_chain(self, chain, kind, meth_name, *args)
        502         for handler in handlers:
        503             func = getattr(handler, meth_name)
    --> 504             result = func(*args)
        505             if result is not None:
        506                 return result

    e:\ProgramData\Anaconda3\lib\urllib\request.py in http_error_default(self, req, fp, code, msg, hdrs)
        648 class HTTPDefaultErrorHandler(BaseHandler):
        649     def http_error_default(self, req, fp, code, msg, hdrs):
    --> 650         raise HTTPError(req.full_url, code, msg, hdrs, fp)
        651
        652 class HTTPRedirectHandler(BaseHandler):

    HTTPError: HTTP Error 500: INTERNAL SERVER ERROR
</code>```

答:
I also get the same error as you. Here are some possible solutions that do not require this server.

If you have tensorflow installed, you can get MNIST data in the following way:

```<code>import tensorflow.examples.tutorials.mnist.input_data as input_data
m=input_data.read_data_sets("MNIST")
</code>```

Then for example len(m.train.images) is 55000.

If you don't have tensorflow, you can get this dataset using the instructions here.

Body:
Hu guys,

I'm new to python/anaconda/jupyter/numPy, panda, etc.... so please excuse me if it's a really stupid question.
I'm trying to obtain MNIST database by using anaconda/jupyter. But everytime I get an HTTP error 500 at the end. Is it really a server problem (as 500 would suggest) or am I doing something wrong?

Input in jupyter:

from sklearn.datasets import fetch_mldata
mnist = fetch_mldata('MNIST original')

Result:

    ---------------------------------------------------------------------------
    HTTPError                                 Traceback (most recent call last)
    <ipython-input-1-15dc285fb373> in <module>()
          1 from sklearn.datasets import fetch_mldata
    ----> 2 mnist = fetch_mldata('MNIST original')

    e:\ProgramData\Anaconda3\lib\site-packages\sklearn\datasets\mldata.py in fetch_mldata(dataname, target_name, data_name, transpose_data, data_home)
        140         urlname = MLDATA_BASE_URL % quote(dataname)
        141         try:
    --> 142             mldata_url = urlopen(urlname)
        143         except HTTPError as e:
        144             if e.code == 404:

    e:\ProgramData\Anaconda3\lib\urllib\request.py in urlopen(url, data, timeout, cafile, capath, cadefault, context)
        221     else:
        222         opener = _opener
    --> 223     return opener.open(url, data, timeout)
        224
        225 def install_opener(opener):

    e:\ProgramData\Anaconda3\lib\urllib\request.py in open(self, fullurl, data, timeout)
        530         for processor in self.process_response.get(protocol, []):
        531             meth = getattr(processor, meth_name)
    --> 532             response = meth(req, response)
        533
        534         return response

    e:\ProgramData\Anaconda3\lib\urllib\request.py in http_response(self, request, response)
        640         if not (200 <= code < 300):
        641             response = self.parent.error(
    --> 642                 'http', request, response, code, msg, hdrs)
        643
        644         return response

    e:\ProgramData\Anaconda3\lib\urllib\request.py in error(self, proto, *args)
        562             http_err = 0
        563         args = (dict, proto, meth_name) + args
    --> 564         result = self._call_chain(*args)
        565         if result:
        566             return result

    e:\ProgramData\Anaconda3\lib\urllib\request.py in _call_chain(self, chain, kind, meth_name, *args)
        502         for handler in handlers:
        503             func = getattr(handler, meth_name)
    --> 504             result = func(*args)
        505             if result is not None:
        506                 return result

    e:\ProgramData\Anaconda3\lib\urllib\request.py in http_error_302(self, req, fp, code, msg, headers)
        754         fp.close()
        755
    --> 756         return self.parent.open(new, timeout=req.timeout)
        757
        758     http_error_301 = http_error_303 = http_error_307 = http_error_302

    e:\ProgramData\Anaconda3\lib\urllib\request.py in open(self, fullurl, data, timeout)
        530         for processor in self.process_response.get(protocol, []):
        531             meth = getattr(processor, meth_name)
    --> 532             response = meth(req, response)
        533
        534         return response

    e:\ProgramData\Anaconda3\lib\urllib\request.py in http_response(self, request, response)
        640         if not (200 <= code < 300):
        641             response = self.parent.error(
    --> 642                 'http', request, response, code, msg, hdrs)
        643
        644         return response

    e:\ProgramData\Anaconda3\lib\urllib\request.py in error(self, proto, *args)
        568         if http_err:
        569             args = (dict, 'default', 'http_error_default') + orig_args
    --> 570             return self._call_chain(*args)
        571
        572 # XXX probably also want an abstract factory that knows when it makes

    e:\ProgramData\Anaconda3\lib\urllib\request.py in _call_chain(self, chain, kind, meth_name, *args)
        502         for handler in handlers:
        503             func = getattr(handler, meth_name)
    --> 504             result = func(*args)
        505             if result is not None:
        506                 return result

    e:\ProgramData\Anaconda3\lib\urllib\request.py in http_error_default(self, req, fp, code, msg, hdrs)
        648 class HTTPDefaultErrorHandler(BaseHandler):
        649     def http_error_default(self, req, fp, code, msg, hdrs):
    --> 650         raise HTTPError(req.full_url, code, msg, hdrs, fp)
        651
        652 class HTTPRedirectHandler(BaseHandler):

    HTTPError: HTTP Error 500: INTERNAL SERVER ERROR

Body:
I also get the same error as you. Here are some possible solutions that do not require this server.

If you have tensorflow installed, you can get MNIST data in the following way:

import tensorflow.examples.tutorials.mnist.input_data as input_data
m=input_data.read_data_sets("MNIST")

Then for example len(m.train.images) is 55000.

If you don't have tensorflow, you can get this dataset using the instructions here.


问:
How to independently use single Zend Framework component like XML-RPC or REST?
Zend framework is well known for loosely coupled components.

I would like to use XML-RPC from zend framework, is there any dependency for XML-RPC? Like if I had taken out XML-RPC folder off Zend Framework Library and try to instantiate RPC object, would it throw error?

Where can I find the proper way of separating component from the framework?

Thanks

答:
I wrote a tool which takes ZF components and their dependencies so you can easily take just one (or several) component from ZF.

http://epic.codeutopia.net/pack/

It doesn't have the latest ZF release 1.11 (because I'm lazy), but 1.10.6 should work just fine.


问:
Setup sending post request from android to php script
Android Retrofit's servise interface:

```<code>//@Headers("Authorization: " + BuildConfig.CLIENT_NAME + " " + BuildConfig.CLIENT_PASSWORD)
@FormUrlEncoded
@POST("api/post/report")
Observable<Object> postReport(@Field("message") String message);
</code>```

Android monitor tells:

```<code>--> POST http://<mysite>/api/post/report http/1.1
D/OkHttp: Content-Type: application/x-www-form-urlencoded
D/OkHttp: Content-Length: 104
D/OkHttp: message=%D0%B2%D0%BB%D0%BE%D1%81%D0%B8%3A%20%D1%81%D0%BB%D1%87%D0%BB%D1%8C%D1%8F%D0%B1%D1%8B%D0%B6%D1%8B
D/OkHttp: --> END POST (104-byte body)
</code>```

I do not know how to catch the Message from PHP.

$_POST - is empty

```<code>parse_str(file_get_contents("php://input"), $data);
$data = (object)$data;
</code>```

Different variants of ^ are also not working. They returns nullable results, empty objects and ext

答:
Ok.ok. I did this:

```<code>//@Headers("Authorization: " + BuildConfig.CLIENT_NAME + " " +    BuildConfig.CLIENT_PASSWORD)
@POST("api/post/report")
Observable<Object> postReport(@Header("message") String message);
</code>```

I sent this via Header & catched the message with getHeaders() method...

Body:
Android Retrofit's servise interface:

//@Headers("Authorization: " + BuildConfig.CLIENT_NAME + " " + BuildConfig.CLIENT_PASSWORD)
@FormUrlEncoded
@POST("api/post/report")
Observable<Object> postReport(@Field("message") String message);

Android monitor tells:

--> POST http://<mysite>/api/post/report http/1.1
D/OkHttp: Content-Type: application/x-www-form-urlencoded
D/OkHttp: Content-Length: 104
D/OkHttp: message=%D0%B2%D0%BB%D0%BE%D1%81%D0%B8%3A%20%D1%81%D0%BB%D1%87%D0%BB%D1%8C%D1%8F%D0%B1%D1%8B%D0%B6%D1%8B
D/OkHttp: --> END POST (104-byte body)

I do not know how to catch the Message from PHP.

$_POST - is empty

parse_str(file_get_contents("php://input"), $data);
$data = (object)$data;

Different variants of ^ are also not working. They returns nullable results, empty objects and ext

Body:
Ok.ok. I did this:

//@Headers("Authorization: " + BuildConfig.CLIENT_NAME + " " +    BuildConfig.CLIENT_PASSWORD)
@POST("api/post/report")
Observable<Object> postReport(@Header("message") String message);

I sent this via Header & catched the message with getHeaders() method...


问:
Loading Images from Gallery into ImageViews Separatly
Ok so i have 3 ImageViews who load image from gallery when i click them.

My problem is , how to set the Image that i have loaded in the specific ImageView .

Im facing some issue with the ActivityForResult code (when load an Image and set it in ImageView1 for exemple , All ImageView take the same image instantly)

The full code :

```<code>package kane.navigationdrawer.activity;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import kane.navigationdrawer.R;
import static android.R.attr.data;
import static kane.navigationdrawer.R.id.spinner;
import static kane.navigationdrawer.R.id.spinner4;

   public class FormActivity extends AppCompatActivity {

private Spinner spinner1;
Button b1;
ImageView img1,img2,img3;
private static int RESULT_LOAD_IMAGE = 1;
private static int RESULT_LOAD_IMAGE2 = 1;
private static int RESULT_LOAD_IMAGE3 = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_form);

    Spinner spinner = (Spinner) findViewById(R.id.spinner4);
    Spinner spinner2 = (Spinner) findViewById(R.id.spinner);
    img1 = (ImageView) findViewById(R.id.img1);
    img2 = (ImageView) findViewById(R.id.img2);
    img3 = (ImageView) findViewById(R.id.img3);

    spinner2.setAdapter(
            new ArrayAdapter<CharSequence>(this,
                    R.layout.custom_spinner_item,
                    FormActivity.this.getResources().getTextArray(R.array.cat_arrays)));

    spinner.setAdapter(
            new ArrayAdapter<CharSequence>(this,
                    R.layout.custom_spinner_item,
                    FormActivity.this.getResources().getTextArray(R.array.vil_arrays)));

    img1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            Intent loadIntent = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            startActivityForResult(loadIntent, RESULT_LOAD_IMAGE);
        }
    });

    img2.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            Intent loadIntent2 = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            startActivityForResult(loadIntent2, RESULT_LOAD_IMAGE2);
        }
    });

    img3.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            Intent loadIntent3 = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            startActivityForResult(loadIntent3, RESULT_LOAD_IMAGE3);
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

        img1.setImageBitmap(BitmapFactory.decodeFile(picturePath));
    }

    if (requestCode == RESULT_LOAD_IMAGE2 && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

        img2.setImageBitmap(BitmapFactory.decodeFile(picturePath));
    }
    if (requestCode == RESULT_LOAD_IMAGE3 && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

        img3.setImageBitmap(BitmapFactory.decodeFile(picturePath));
    }
}
}
</code>```

Need your help , Thanks

答:
You defined three request codes, but they all have the same value, hence all three if statements will be executed regardless of your image choice.

Simply assigning different values to your request code variables should fix the problem.

```<code>private static int RESULT_LOAD_IMAGE = 1;
private static int RESULT_LOAD_IMAGE2 = 2;
private static int RESULT_LOAD_IMAGE3 = 3;
</code>```

Body:
Ok so i have 3 ImageViews who load image from gallery when i click them.

My problem is , how to set the Image that i have loaded in the specific ImageView .

Im facing some issue with the ActivityForResult code (when load an Image and set it in ImageView1 for exemple , All ImageView take the same image instantly)

The full code :

package kane.navigationdrawer.activity;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import kane.navigationdrawer.R;
import static android.R.attr.data;
import static kane.navigationdrawer.R.id.spinner;
import static kane.navigationdrawer.R.id.spinner4;

   public class FormActivity extends AppCompatActivity {

private Spinner spinner1;
Button b1;
ImageView img1,img2,img3;
private static int RESULT_LOAD_IMAGE = 1;
private static int RESULT_LOAD_IMAGE2 = 1;
private static int RESULT_LOAD_IMAGE3 = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_form);

    Spinner spinner = (Spinner) findViewById(R.id.spinner4);
    Spinner spinner2 = (Spinner) findViewById(R.id.spinner);
    img1 = (ImageView) findViewById(R.id.img1);
    img2 = (ImageView) findViewById(R.id.img2);
    img3 = (ImageView) findViewById(R.id.img3);

    spinner2.setAdapter(
            new ArrayAdapter<CharSequence>(this,
                    R.layout.custom_spinner_item,
                    FormActivity.this.getResources().getTextArray(R.array.cat_arrays)));

    spinner.setAdapter(
            new ArrayAdapter<CharSequence>(this,
                    R.layout.custom_spinner_item,
                    FormActivity.this.getResources().getTextArray(R.array.vil_arrays)));

    img1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            Intent loadIntent = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            startActivityForResult(loadIntent, RESULT_LOAD_IMAGE);
        }
    });

    img2.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            Intent loadIntent2 = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            startActivityForResult(loadIntent2, RESULT_LOAD_IMAGE2);
        }
    });

    img3.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            Intent loadIntent3 = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            startActivityForResult(loadIntent3, RESULT_LOAD_IMAGE3);
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

        img1.setImageBitmap(BitmapFactory.decodeFile(picturePath));
    }

    if (requestCode == RESULT_LOAD_IMAGE2 && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

        img2.setImageBitmap(BitmapFactory.decodeFile(picturePath));
    }
    if (requestCode == RESULT_LOAD_IMAGE3 && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

        img3.setImageBitmap(BitmapFactory.decodeFile(picturePath));
    }
}
}

Need your help , Thanks

Body:
You defined three request codes, but they all have the same value, hence all three if statements will be executed regardless of your image choice.

Simply assigning different values to your request code variables should fix the problem.

private static int RESULT_LOAD_IMAGE = 1;
private static int RESULT_LOAD_IMAGE2 = 2;
private static int RESULT_LOAD_IMAGE3 = 3;


问:
Decimal to integer conversion error
I'm working on a school project using VIsual Studio 2015, the assignment is to create GUI "Commute Calculator" with three options for mode of transportation. I've wrote the code following the instructions in my textbook but am getting the following error:

"BC30057  Too many arguments to 'Private Function CarFindCost(intCommuteChoice As Integer, intDays As Integer) As Decimal'."

I'm a newbie to vs, but based on the error I believe the problem is with how I declared variables. I googled how to convert an integer to decimal, but haven't found anything that worked. The code is lengthy, but I included it all as an FYI. The error is in the private sub btnCommute and appears to be tied to three private functions: CarFindCost, BusFindCost and TrainFindCost. How to I fix it so I don't get errors on the variable intLength in the private sub bthCommute?

```<code>Option Strict On

Public Class frmCommuteCalc
    Dim intCommuteChoice As Integer
    Dim strSelectedMode As String = ""
    Private _strGas As Integer
    Private _strMiles As String = "Enter the total miles for a round trip: "
    Private _strMilesPerGallon As Double = 2.15
    Private _strDailyParking As Decimal = 10
    Private _strMonthlyParking As Decimal
    Private _strMonthlyUpkeep As Decimal = 112
    Private _strRTBusFare As String = "Round trip bus fare is "
    Private _strRTTrainFare As String = "Round trip train fare is "
    Private _StrDays As String = "Enter the number of days worked per month: "
    Private _intTrainFare As Integer

    Private Sub frmCommuteCalc_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Threading.Thread.Sleep(5000)

    End Sub

    Private Sub cboCommuteMethod_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboCommuteMethod.SelectedIndexChanged

        Dim intCommuteChoice As Integer

        intCommuteChoice = cboCommuteMethod.SelectedIndex()
        lstCommute.Items.Clear()

        Select Case intCommuteChoice
            Case 0
                Car()
            Case 1
                Train()
            Case 2
                Bus()
        End Select

        lblDays.Visible = True
        lblMiles.Visible = True
        lblLength.Visible = True
        txtDays.Visible = True
        'txtMonthlyTotal.Visible = True

    End Sub

    Private Sub btnCompute_Click(sender As Object, e As EventArgs) Handles btnCompute.Click

        Dim intCommuteChoice As Integer
        Dim intDaysPerMonth As Integer
        Dim decTotalCost As Decimal
        Dim intLength As Integer = 0
        Dim strSelectedMode As String = ""
        Dim blnNumberInDaysIsValid As Boolean = False
        Dim blnCommuteMethodIsSelected As Boolean = False

        blnNumberInDaysIsValid = ValidateNumberInDays()

        intCommuteChoice = ValidateCommuteSelection(blnCommuteMethodIsSelected, strSelectedMode)

        If (blnNumberInDaysIsValid And blnCommuteMethodIsSelected) Then
            intDaysPerMonth = Convert.ToInt32(txtDays.Text)
            intCommuteChoice = cboCommuteMethod.SelectedIndex()
            Select Case intCommuteChoice
                Case 0
                    decTotalCost = CarFindCost(intCommuteChoice, intDaysPerMonth, intLength)
                Case 1
                    decTotalCost = BusFindCost(intCommuteChoice, intDaysPerMonth, intLength)
                Case 2
                    decTotalCost = TrainFindCost(intCommuteChoice, intDaysPerMonth, intLength)
            End Select

        End If

    End Sub

    Private Function intLength() As Object
        Throw New NotImplementedException()
    End Function

    Function ComputeCommuteCost(ByVal decMiles As Decimal, ByVal decGallons As Decimal) As Decimal

        Dim decMilage As Decimal

        decMilage = decMiles / decGallons
        Return decMilage

    End Function
    Private Sub Car()

        lstCommute.Items.Add(_strMiles)
        lstCommute.Items.Add(_strMilesPerGallon)
        lstCommute.Items.Add(_StrDays)
        lstCommute.Items.Add(_strMonthlyParking)
        lstCommute.Items.Add(_strMonthlyUpkeep)

    End Sub

    Private Sub Bus()

        lstCommute.Items.Add(_strRTBusFare)
        lstCommute.Items.Add(_StrDays)
    End Sub

    Private Sub Train()
        lstCommute.Items.Add(_StrDays)
        lstCommute.Items.Add(_strRTTrainFare)

    End Sub
    Private Function ValidateNumberInDays() As Boolean

        Dim intDays As Integer
        Dim blnValidityCheck As Boolean = False
        Dim strNumberInDaysMessage As String = "Please enter the No. of days per month you will be commuting "
        Dim strMessageBoxTitle As String = "Error"

        Try
            intDays = Convert.ToInt32(txtDays.Text)
            If intDays >= 1 And intDays <= 21 Then
                blnValidityCheck = True
            Else
                MsgBox(strNumberInDaysMessage, , strMessageBoxTitle)
                txtDays.Focus()
                txtDays.Clear()
            End If
        Catch Exception As FormatException
            MsgBox(strNumberInDaysMessage, , strMessageBoxTitle)
            txtDays.Focus()
            txtDays.Clear()
        Catch Exception As OverflowException
            MsgBox(strNumberInDaysMessage, , strMessageBoxTitle)
            txtDays.Focus()
            txtDays.Clear()
        Catch Exception As SystemException
            MsgBox(strNumberInDaysMessage, , strMessageBoxTitle)
            txtDays.Focus()
            txtDays.Clear()
        End Try

        Return blnValidityCheck

    End Function

    Private Function ValidateCommuteSelection(ByRef blnDays As Boolean, ByRef strDays As String) As Integer
        Dim intCommuteChoice As Integer

        Try
            intCommuteChoice = Convert.ToInt32(lstCommute.SelectedIndex)
            strDays = lstCommute.SelectedItem.ToString()
            blnDays = True
        Catch Exception As SystemException
            MsgBox("Select a commute mode", , "Error")
            blnDays = False
        End Try

        Return intCommuteChoice

    End Function

    Private Function CarFindCost(ByVal intCommuteChoice As Integer, ByVal intDays As Integer) As Decimal
        Dim decDaysPerMonth As Decimal
        Dim decMiles As Decimal
        Dim decMilesPerGallon As Decimal = 2
        Dim decGasTotal As Decimal
        Dim decDailyParking As Decimal = 10
        Dim decMonthlyParking As Decimal
        Dim decMonthlyUpkeep As Decimal = 112
        Dim decFinalCost As Decimal
        Dim intLength As Integer = 0

        decMiles = Convert.ToDecimal(txtMiles.Text)
        decMilesPerGallon = Convert.ToDecimal(txtGallons.Text)
        decGasTotal = decMilesPerGallon * decMiles
        decMonthlyParking = Convert.ToDecimal(lblLength.Text)
        decMonthlyParking = decDailyParking * decDaysPerMonth
        decFinalCost = Convert.ToDecimal(lblLength.Text)
        decFinalCost = decGasTotal + decMonthlyUpkeep + decMonthlyParking

        Return decFinalCost

    End Function

    Private Function BusFindCost(ByVal intCommuteChoice As Integer, ByVal intDays As Integer) As Decimal

        Dim intLength As Integer = 0
        Dim decDaysPerMonth As Decimal
        Dim decBusFarePerDay As Decimal = 4
        Dim decFinalCost As Decimal

        decBusFarePerDay = Convert.ToDecimal(txtMonthlyTotal)
        decFinalCost = decBusFarePerDay * decDaysPerMonth

        Return decFinalCost

    End Function

    Private Function TrainFindCost(ByVal intCommuteChoice As Integer, ByVal intDays As Integer) As Decimal

        Dim intLength As Integer = 0
        Dim decDaysPerMonth As Decimal
        Dim decTrainFarePerDay As Decimal = 18
        Dim decFinalCost As Decimal

        decTrainFarePerDay = Convert.ToDecimal(txtMonthlyTotal)
        decFinalCost = Convert.ToDecimal(txtMonthlyTotal)
        decFinalCost = decDaysPerMonth * decTrainFarePerDay

        Return decFinalCost

    End Function
End Class
</code>```

答:
In:

```<code>Select Case intCommuteChoice ... End Select
</code>```

in each case; call function CarFindCost with 3 parameters y you have declared with only 2.

Title: Decimal to integer conversion error

Body:
I'm working on a school project using VIsual Studio 2015, the assignment is to create GUI "Commute Calculator" with three options for mode of transportation. I've wrote the code following the instructions in my textbook but am getting the following error:

"BC30057  Too many arguments to 'Private Function CarFindCost(intCommuteChoice As Integer, intDays As Integer) As Decimal'."

I'm a newbie to vs, but based on the error I believe the problem is with how I declared variables. I googled how to convert an integer to decimal, but haven't found anything that worked. The code is lengthy, but I included it all as an FYI. The error is in the private sub btnCommute and appears to be tied to three private functions: CarFindCost, BusFindCost and TrainFindCost. How to I fix it so I don't get errors on the variable intLength in the private sub bthCommute?

Option Strict On

Public Class frmCommuteCalc
    Dim intCommuteChoice As Integer
    Dim strSelectedMode As String = ""
    Private _strGas As Integer
    Private _strMiles As String = "Enter the total miles for a round trip: "
    Private _strMilesPerGallon As Double = 2.15
    Private _strDailyParking As Decimal = 10
    Private _strMonthlyParking As Decimal
    Private _strMonthlyUpkeep As Decimal = 112
    Private _strRTBusFare As String = "Round trip bus fare is "
    Private _strRTTrainFare As String = "Round trip train fare is "
    Private _StrDays As String = "Enter the number of days worked per month: "
    Private _intTrainFare As Integer

    Private Sub frmCommuteCalc_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Threading.Thread.Sleep(5000)

    End Sub

    Private Sub cboCommuteMethod_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboCommuteMethod.SelectedIndexChanged

        Dim intCommuteChoice As Integer

        intCommuteChoice = cboCommuteMethod.SelectedIndex()
        lstCommute.Items.Clear()

        Select Case intCommuteChoice
            Case 0
                Car()
            Case 1
                Train()
            Case 2
                Bus()
        End Select

        lblDays.Visible = True
        lblMiles.Visible = True
        lblLength.Visible = True
        txtDays.Visible = True
        'txtMonthlyTotal.Visible = True

    End Sub

    Private Sub btnCompute_Click(sender As Object, e As EventArgs) Handles btnCompute.Click

        Dim intCommuteChoice As Integer
        Dim intDaysPerMonth As Integer
        Dim decTotalCost As Decimal
        Dim intLength As Integer = 0
        Dim strSelectedMode As String = ""
        Dim blnNumberInDaysIsValid As Boolean = False
        Dim blnCommuteMethodIsSelected As Boolean = False

        blnNumberInDaysIsValid = ValidateNumberInDays()

        intCommuteChoice = ValidateCommuteSelection(blnCommuteMethodIsSelected, strSelectedMode)

        If (blnNumberInDaysIsValid And blnCommuteMethodIsSelected) Then
            intDaysPerMonth = Convert.ToInt32(txtDays.Text)
            intCommuteChoice = cboCommuteMethod.SelectedIndex()
            Select Case intCommuteChoice
                Case 0
                    decTotalCost = CarFindCost(intCommuteChoice, intDaysPerMonth, intLength)
                Case 1
                    decTotalCost = BusFindCost(intCommuteChoice, intDaysPerMonth, intLength)
                Case 2
                    decTotalCost = TrainFindCost(intCommuteChoice, intDaysPerMonth, intLength)
            End Select

        End If

    End Sub

    Private Function intLength() As Object
        Throw New NotImplementedException()
    End Function

    Function ComputeCommuteCost(ByVal decMiles As Decimal, ByVal decGallons As Decimal) As Decimal

        Dim decMilage As Decimal

        decMilage = decMiles / decGallons
        Return decMilage

    End Function
    Private Sub Car()

        lstCommute.Items.Add(_strMiles)
        lstCommute.Items.Add(_strMilesPerGallon)
        lstCommute.Items.Add(_StrDays)
        lstCommute.Items.Add(_strMonthlyParking)
        lstCommute.Items.Add(_strMonthlyUpkeep)

    End Sub

    Private Sub Bus()

        lstCommute.Items.Add(_strRTBusFare)
        lstCommute.Items.Add(_StrDays)
    End Sub

    Private Sub Train()
        lstCommute.Items.Add(_StrDays)
        lstCommute.Items.Add(_strRTTrainFare)

    End Sub
    Private Function ValidateNumberInDays() As Boolean

        Dim intDays As Integer
        Dim blnValidityCheck As Boolean = False
        Dim strNumberInDaysMessage As String = "Please enter the No. of days per month you will be commuting "
        Dim strMessageBoxTitle As String = "Error"

        Try
            intDays = Convert.ToInt32(txtDays.Text)
            If intDays >= 1 And intDays <= 21 Then
                blnValidityCheck = True
            Else
                MsgBox(strNumberInDaysMessage, , strMessageBoxTitle)
                txtDays.Focus()
                txtDays.Clear()
            End If
        Catch Exception As FormatException
            MsgBox(strNumberInDaysMessage, , strMessageBoxTitle)
            txtDays.Focus()
            txtDays.Clear()
        Catch Exception As OverflowException
            MsgBox(strNumberInDaysMessage, , strMessageBoxTitle)
            txtDays.Focus()
            txtDays.Clear()
        Catch Exception As SystemException
            MsgBox(strNumberInDaysMessage, , strMessageBoxTitle)
            txtDays.Focus()
            txtDays.Clear()
        End Try

        Return blnValidityCheck

    End Function

    Private Function ValidateCommuteSelection(ByRef blnDays As Boolean, ByRef strDays As String) As Integer
        Dim intCommuteChoice As Integer

        Try
            intCommuteChoice = Convert.ToInt32(lstCommute.SelectedIndex)
            strDays = lstCommute.SelectedItem.ToString()
            blnDays = True
        Catch Exception As SystemException
            MsgBox("Select a commute mode", , "Error")
            blnDays = False
        End Try

        Return intCommuteChoice

    End Function

    Private Function CarFindCost(ByVal intCommuteChoice As Integer, ByVal intDays As Integer) As Decimal
        Dim decDaysPerMonth As Decimal
        Dim decMiles As Decimal
        Dim decMilesPerGallon As Decimal = 2
        Dim decGasTotal As Decimal
        Dim decDailyParking As Decimal = 10
        Dim decMonthlyParking As Decimal
        Dim decMonthlyUpkeep As Decimal = 112
        Dim decFinalCost As Decimal
        Dim intLength As Integer = 0

        decMiles = Convert.ToDecimal(txtMiles.Text)
        decMilesPerGallon = Convert.ToDecimal(txtGallons.Text)
        decGasTotal = decMilesPerGallon * decMiles
        decMonthlyParking = Convert.ToDecimal(lblLength.Text)
        decMonthlyParking = decDailyParking * decDaysPerMonth
        decFinalCost = Convert.ToDecimal(lblLength.Text)
        decFinalCost = decGasTotal + decMonthlyUpkeep + decMonthlyParking

        Return decFinalCost

    End Function

    Private Function BusFindCost(ByVal intCommuteChoice As Integer, ByVal intDays As Integer) As Decimal

        Dim intLength As Integer = 0
        Dim decDaysPerMonth As Decimal
        Dim decBusFarePerDay As Decimal = 4
        Dim decFinalCost As Decimal

        decBusFarePerDay = Convert.ToDecimal(txtMonthlyTotal)
        decFinalCost = decBusFarePerDay * decDaysPerMonth

        Return decFinalCost

    End Function

    Private Function TrainFindCost(ByVal intCommuteChoice As Integer, ByVal intDays As Integer) As Decimal

        Dim intLength As Integer = 0
        Dim decDaysPerMonth As Decimal
        Dim decTrainFarePerDay As Decimal = 18
        Dim decFinalCost As Decimal

        decTrainFarePerDay = Convert.ToDecimal(txtMonthlyTotal)
        decFinalCost = Convert.ToDecimal(txtMonthlyTotal)
        decFinalCost = decDaysPerMonth * decTrainFarePerDay

        Return decFinalCost

    End Function
End Class

Body:
In:

Select Case intCommuteChoice ... End Select

in each case; call function CarFindCost with 3 parameters y you have declared with only 2.


问:
Espresso Webview select hidden element
How do you find a hidden element inside an Android Webview using espresso? This is what I tried:

```<code>onWebView().withElement(findElement(Locator.CSS_SELECTOR, "#clsp:hidden"));
</code>```

That produces the following stacktrace.

java.lang.RuntimeException: java.lang.RuntimeException: Error in
  evaluationEvaluation: status: 13 value: {message=An invalid or illegal
  selector was specified} hasMessage: true message: An invalid or
  illegal selector was specified at
  android.support.test.espresso.web.sugar.Web$WebInteraction$ExceptionPropagator.(Web.java:323)
  at
  android.support.test.espresso.web.sugar.Web$WebInteraction.doEval(Web.java:292)
  at
  android.support.test.espresso.web.sugar.Web$WebInteraction.withElement(Web.java:208)
  at
  com.middlestump.MainActivityInstrumentationTest.createAlert(MainActivityInstrumentationTest.java:89)
  at java.lang.reflect.Method.invoke(Native Method) at
  java.lang.reflect.Method.invoke(Method.java:372) at
  org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)

The MainActivityInstrumentationTest.java:89 bit is the line of code I have given.

Also tried:

```<code>onWebView().withElement(findElement(Locator.CSS_SELECTOR, "#clsp")).check(isDisplayed());
</code>```

But there is a type mismatch between WebAssertion and ViewAssertion

答:
Swipe webview and find the hidden element:</p>

```<code>onView(withId(R.id.webView)).perform(ViewActions.swipeUp());
</code>```

Title: Espresso Webview select hidden element

Body:
How do you find a hidden element inside an Android Webview using espresso? This is what I tried:

onWebView().withElement(findElement(Locator.CSS_SELECTOR, "#clsp:hidden"));

That produces the following stacktrace.

java.lang.RuntimeException: java.lang.RuntimeException: Error in
  evaluationEvaluation: status: 13 value: {message=An invalid or illegal
  selector was specified} hasMessage: true message: An invalid or
  illegal selector was specified at
  android.support.test.espresso.web.sugar.Web$WebInteraction$ExceptionPropagator.(Web.java:323)
  at
  android.support.test.espresso.web.sugar.Web$WebInteraction.doEval(Web.java:292)
  at
  android.support.test.espresso.web.sugar.Web$WebInteraction.withElement(Web.java:208)
  at
  com.middlestump.MainActivityInstrumentationTest.createAlert(MainActivityInstrumentationTest.java:89)
  at java.lang.reflect.Method.invoke(Native Method) at
  java.lang.reflect.Method.invoke(Method.java:372) at
  org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)

The MainActivityInstrumentationTest.java:89 bit is the line of code I have given.

Also tried:

onWebView().withElement(findElement(Locator.CSS_SELECTOR, "#clsp")).check(isDisplayed());

But there is a type mismatch between WebAssertion and ViewAssertion

Body:
Swipe webview and find the hidden element:

onView(withId(R.id.webView)).perform(ViewActions.swipeUp());


问:
c# dot operator overhead: What is more efficient
So I have a WPF application that has a base MVVM with child MVVMs. I tried googling the answer but wasn't sure of the technical terms so I will provide two examples below and perhaps someone can give me a little insight into the efficiency of the examples. I want to know if there is little difference in the overhead or significant.

Lets say I have a setup similar to the following

```<code>public class ParentViewModel
{
    public ParentViewModel()
    {
        Child = new ChildViewModel();
    }

    public ChildViewModel Child { get; set; }
}

public class ChildViewModel
{
    public ChildViewModel()
    {
        GrandChild = new GrandChildViewModel();
    }

    public GrandChildViewModel GrandChild { get; set; }
}

public class GrandChildViewModel
{
    public GrandChildViewModel()
    {
        GreatGrandChild = new GreatGrandChildViewModel();
    }

    public GreatGrandChildViewModel GreatGrandChild { get; set; }
}

public class GreatGrandChildViewModel
{
    public GreatGrandChildViewModel()
    {
         intA = 1;
         intB = 2;
         intC = 3;
    }

    public int intA { get; set; }
    public int intB { get; set; }
    public int intC { get; set; }
}
</code>```

And the following two examples of usage is where I want the insight.

Example 1:

```<code>public Main()
{
     var parent = new ParentViewModel();

     Console.WriteLine($"A: {parent.Child.GrandChild.GreatGrandChild.intA}" +
                       $"B: {parent.Child.GrandChild.GreatGrandChild.intB}" +
                       $"C: {parent.Child.GrandChild.GreatGrandChild.intC}");
}
</code>```

Example 2:

```<code>public Main()
{
     var greatGrandChild = new ParentViewModel().Child.GrandChild.GreatGrandChild;

     Console.WriteLine($"A: {greatGrandChild.intA}" +
                       $"B: {greatGrandChild.intB}" +
                       $"C: {greatGrandChild.intC}");
}
</code>```

Which one is more efficient? I'm asking because I would think Example 2 would be more efficient as it goes down to the lowest level once and then accesses intA, intB, and intC.
Does this matter? Is the difference in performance significant?

答:
I would recommend getting the smallest object that you need.

The performance difference will be negligible in the example you gave, but if there happens to be a lot more data in the parent/grandparent/greatgrandparent objects, and if you are passing this object around (especially over the network), then it could make a difference. Imagine passing someone's entire family tree object to some web service that really only needs the person's name.

But it also shows your intent by grabbing the smallest object you need. Intentional programming is often easier to read and maintain, and allows you to find bugs more easily.

Body:
So I have a WPF application that has a base MVVM with child MVVMs. I tried googling the answer but wasn't sure of the technical terms so I will provide two examples below and perhaps someone can give me a little insight into the efficiency of the examples. I want to know if there is little difference in the overhead or significant.

Lets say I have a setup similar to the following

public class ParentViewModel
{
    public ParentViewModel()
    {
        Child = new ChildViewModel();
    }

    public ChildViewModel Child { get; set; }
}

public class ChildViewModel
{
    public ChildViewModel()
    {
        GrandChild = new GrandChildViewModel();
    }

    public GrandChildViewModel GrandChild { get; set; }
}

public class GrandChildViewModel
{
    public GrandChildViewModel()
    {
        GreatGrandChild = new GreatGrandChildViewModel();
    }

    public GreatGrandChildViewModel GreatGrandChild { get; set; }
}

public class GreatGrandChildViewModel
{
    public GreatGrandChildViewModel()
    {
         intA = 1;
         intB = 2;
         intC = 3;
    }

    public int intA { get; set; }
    public int intB { get; set; }
    public int intC { get; set; }
}

And the following two examples of usage is where I want the insight.

Example 1:

public Main()
{
     var parent = new ParentViewModel();

     Console.WriteLine($"A: {parent.Child.GrandChild.GreatGrandChild.intA}" +
                       $"B: {parent.Child.GrandChild.GreatGrandChild.intB}" +
                       $"C: {parent.Child.GrandChild.GreatGrandChild.intC}");
}

Example 2:

public Main()
{
     var greatGrandChild = new ParentViewModel().Child.GrandChild.GreatGrandChild;

     Console.WriteLine($"A: {greatGrandChild.intA}" +
                       $"B: {greatGrandChild.intB}" +
                       $"C: {greatGrandChild.intC}");
}

Which one is more efficient? I'm asking because I would think Example 2 would be more efficient as it goes down to the lowest level once and then accesses intA, intB, and intC.
Does this matter? Is the difference in performance significant?


问:
VB.NET Limit to Tab Ordering?
I have inherited a frankenstein VB6 "Converted" to VB.NET winform application. This application has a metric ton of fields in it, the users rightfully complained that the tab order is off (after a certain point it starts jumping all over the form).

Figuring something in tab order was off, I went in and turned on View > Tab Order and it looked good.

To be sure I went through the form again fresh and when I'm in tab order view all is well, but when the app runs it still starts jumping around the same area as before?! Has anyone else encountered this and how did you resolve if you did?

[Edit]: These input forms are all on separate tabs within a tab control, which probably muddies the situation even more.

答:
Chances are, some of your controls are embedded in container controls, and the tab order of your container controls is causing the focus to appear as if it is jumping around randomly. Make sure that when you're in the tab order view, you pay careful attention to the tab order of your container controls: Make sure that none of them have the same tab order, and that they're ordered logically with the tab order of your individual controls.

Otherwise, you need to check your UI code for some calls to Control.Focus that could be interfering with the default tab order at run-time. Some validation code may be changing the focus to the "next" control after it completes successfully (or "back" to a previous control if validation failed).

Title: VB.NET Limit to Tab Ordering?


问:
Where to serve files to be downloaded by IOS
In This Post, Devran Cosmo Uenal explained how to download a file with swift on an IOS device. Should the files that I want to download be stored on an FTP server? Or on a regular web server with Apache?</p>

答:
NSURLTask supports both protocols but the post you are referring to uses a regular http server.
Also the post uses the Alamofire library which I think only supports http</p>


问:
Can I create Multiple Client ID in Google console?
I have one query regarding usage of client Id in Google Developers console.

For one project, someone had created one clientId for using Google fit API's for storing fitness data. And I don't have the credentials for account used for creating the Client-id. Also I'm not able to find the client-id anywhere in code.

Now I want to add Google Sign-in using "AppAuth for Android". For which I need to add clientId and redirectUri in code.

My question is, can I create new clientId and redirectUri with any other account using same SHA1 fingerprint and package name? or Do I have to use the same existing client-id? (which doesn't seem to be a possible way)

Edit1:

As @iainmcgin mentioned I tried to create one using the same SHA-1 and package name, but getting below error.

The fingerprint that you specified is already being used by an Android OAuth2 client ID in this project or another project.

答: Google engineer on the Google Identity Platform team here - we enforce a 1:1 mapping between client IDs and package name + certificate hash, so you can't create another client ID. You'll need to regain access to the project that defined the original client ID; if you are not able to do that, contact me at iainmcgin@google.com with the details of your app and I'll try and put you in touch with people that can verify your ownership of the app and either delete the original client, or give you access to the original project, whichever turns out to be more appropriate.</p>


问:
Golang custom handler for server
I want to use a custom method on http.ListenAndServe

Here is what I have

```<code>http.ListenAndServe(":8000", ErrorHandler)

func ErrorHandler(h http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        h.ServeHTTP(w, r)
    })
}
</code>```

Error

```<code>cannot use ErrorHandler (type func(http.Handler) http.Handler) as type http.Handler in argument to http.ListenAndServe:
        func(http.Handler) http.Handler does not implement http.Handler (missing ServeHTTP method)
</code>```

How can I add a custom method to ListenAndServe?

答:
Your ErrorHandler(h http.Handler) http.Handler func is basically just "middleware" and not a real handler. It takes a handler h and returns a new handler. http.StripPrefix is an example of such "middleware".

If you don't want middleware, but just a handler then you need to define your function a little differently:

```<code>func ErrorHandler(w http.ResponseWriter, r *http.Request) {
    // do stuff with r and w
}
</code>```

Now you can pass your ErrorHandler to ListenAndServe although you still need to cast it to the proper http.Handler type like so:

```<code>http.ListenAndServe(":8000", http.HandlerFunc(ErrorHandler))
</code>```

http.HandlerFunc is an adapter that turns a function, if it has the right signature, into an http.Handler.

Finally, if you don't like the casting, you'll need to define a type instead of a just a function and you'll need to define a method on that type that is required for it to satisfy the http.Handler interface type.

```<code>type ErrorHandler struct{}

func (h *ErrorHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    // do stuff with r and w
}

http.ListenAndServe(":8080", &ErrorHandler{})
</code>```

Read more about it here https://golang.org/pkg/net/http/#Handler

Title: Golang custom handler for server

Body:
I want to use a custom method on http.ListenAndServe

Here is what I have

http.ListenAndServe(":8000", ErrorHandler)

func ErrorHandler(h http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        h.ServeHTTP(w, r)
    })
}

Error

cannot use ErrorHandler (type func(http.Handler) http.Handler) as type http.Handler in argument to http.ListenAndServe:
        func(http.Handler) http.Handler does not implement http.Handler (missing ServeHTTP method)

How can I add a custom method to ListenAndServe?

Body:
Your ErrorHandler(h http.Handler) http.Handler func is basically just "middleware" and not a real handler. It takes a handler h and returns a new handler. http.StripPrefix is an example of such "middleware".

If you don't want middleware, but just a handler then you need to define your function a little differently:

func ErrorHandler(w http.ResponseWriter, r *http.Request) {
    // do stuff with r and w
}

Now you can pass your ErrorHandler to ListenAndServe although you still need to cast it to the proper http.Handler type like so:

http.ListenAndServe(":8000", http.HandlerFunc(ErrorHandler))

http.HandlerFunc is an adapter that turns a function, if it has the right signature, into an http.Handler.

Finally, if you don't like the casting, you'll need to define a type instead of a just a function and you'll need to define a method on that type that is required for it to satisfy the http.Handler interface type.

type ErrorHandler struct{}

func (h *ErrorHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    // do stuff with r and w
}

http.ListenAndServe(":8080", &ErrorHandler{})

Read more about it here https://golang.org/pkg/net/http/#Handler


问:
Sorting dictionary of lists in Python
I'm making an auction program and need to sort stored bids by price, and date. I'm trying to pull any bids that equal the reserve price, and find the earliest one. I've pulled the line below from another question, however I need to find the max bid (sorted in reverse to bring highest bid and then oldest bid if there are two of the same value).

```<code>sorted(stored_bids_1.items(), key=lambda e:e[1][2][3][4])
</code>```

The dictionary has the following info:

```<code>stored_bids_1 {bid_number : [cust_bid_price, bid_date_time, cust_num_seats, cust_name]}
</code>```

I'd like the bids to be ranked by bid price, then date&time.

Any help is much appreciated!

答: At first glance big thing that I can think of doing is to use a different datastructure. The dicitonary you have works well for storing it the information, but is clearly creating a hurtle. I'd suggest another a dictionary of dictionaries maybe, that way you could access the different values (cust_bid_price, bid_date_time, etc.) by the keys they are in the sub-dictionaries. It's definitely not perfect, but it may lead to another way of looking at this and solving the problems you have.</p>

Title: Sorting dictionary of lists in Python

Body:
I'm making an auction program and need to sort stored bids by price, and date. I'm trying to pull any bids that equal the reserve price, and find the earliest one. I've pulled the line below from another question, however I need to find the max bid (sorted in reverse to bring highest bid and then oldest bid if there are two of the same value).

sorted(stored_bids_1.items(), key=lambda e:e[1][2][3][4])

The dictionary has the following info:

stored_bids_1 {bid_number : [cust_bid_price, bid_date_time, cust_num_seats, cust_name]}

I'd like the bids to be ranked by bid price, then date&time.

Any help is much appreciated!


问:
Set 1st folder as variable batch file
Hi how can I always get the 1st folder in a path to be a variable.
Sample

```<code>c:\A\B
c:\A\B\C
C:\A\B\C\D
</code>```

and my variable will always be outputting the folder A because my bat is sometimes will be put deeper in A folder

答:
Use a for /f loop to split the var with delimiter \ and get the 2nd token.

```<code>> For /f "tokens=2delims=\" %A in ("%__CD__%") Do @Echo %A
Users

> For /f "tokens=2delims=\" %A in ("%CD%.\") Do @Echo %A
Users

> Set "MyPath=X:\path\to\somewhere"
> For /f "tokens=2delims=\" %A in ("%MyPath%.\") Do @Echo %A
path
</code>```

Title: Set 1st folder as variable batch file

Body:
Hi how can I always get the 1st folder in a path to be a variable.
Sample

c:\A\B
c:\A\B\C
C:\A\B\C\D

and my variable will always be outputting the folder A because my bat is sometimes will be put deeper in A folder

Body:
Use a for /f loop to split the var with delimiter \ and get the 2nd token.

> For /f "tokens=2delims=\" %A in ("%__CD__%") Do @Echo %A
Users

> For /f "tokens=2delims=\" %A in ("%CD%.\") Do @Echo %A
Users

> Set "MyPath=X:\path\to\somewhere"
> For /f "tokens=2delims=\" %A in ("%MyPath%.\") Do @Echo %A
path


问:
How to retrieve Google Blogger feed in ASP.NET medium trust?
I have an ASP.NET web site hosted at HostMySite.com and they recently changed the shared accounts to run in medium trust. In my web site I query my Blogger account and get blog posts to display on my web site.

I am using Google.GData.Client v1.4.0.2

The retrieval works locally (and worked until medium trust was invoked at the ISP). Now I receive the following error:

```<code>[SecurityException: Request for the permission of type 'System.Net.WebPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.]
   System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet) +0
   System.Security.CodeAccessPermission.Demand() +58
   System.Net.HttpWebRequest..ctor(Uri uri, ServicePoint servicePoint) +147
   System.Net.HttpRequestCreator.Create(Uri Uri) +26
   System.Net.WebRequest.Create(Uri requestUri, Boolean useUriBase) +216
   System.Net.WebRequest.Create(Uri requestUri) +31
   Google.GData.Client.GDataRequest.EnsureWebRequest() +77
   Google.GData.Client.GDataRequest.Execute() +42
   Google.GData.Client.Service.Query(Uri queryUri, DateTime ifModifiedSince, String etag, Int64& contentLength) +193
   Google.GData.Client.Service.Query(FeedQuery feedQuery) +202
</code>```

I've search the Google documentation and on-line but have not been able to find out what I need to change.

答:
Depending on what you want to use this for you could look at the Google AJAX Feed API which is a javascript api that will let you embed rss feeds into your site.

You wouldn't be able to access this from the server side tho, it would only be display in the users browser.

If you are trying to get this content indexed by search engines, need to save it to a database or manipulate it some how then this solution will not work for you.

Google Feed API Docs are at:

http://code.google.com/apis/feed/v1/devguide.html

Body:
I have an ASP.NET web site hosted at HostMySite.com and they recently changed the shared accounts to run in medium trust. In my web site I query my Blogger account and get blog posts to display on my web site.

I am using Google.GData.Client v1.4.0.2

The retrieval works locally (and worked until medium trust was invoked at the ISP). Now I receive the following error:

[SecurityException: Request for the permission of type 'System.Net.WebPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.]
   System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet) +0
   System.Security.CodeAccessPermission.Demand() +58
   System.Net.HttpWebRequest..ctor(Uri uri, ServicePoint servicePoint) +147
   System.Net.HttpRequestCreator.Create(Uri Uri) +26
   System.Net.WebRequest.Create(Uri requestUri, Boolean useUriBase) +216
   System.Net.WebRequest.Create(Uri requestUri) +31
   Google.GData.Client.GDataRequest.EnsureWebRequest() +77
   Google.GData.Client.GDataRequest.Execute() +42
   Google.GData.Client.Service.Query(Uri queryUri, DateTime ifModifiedSince, String etag, Int64& contentLength) +193
   Google.GData.Client.Service.Query(FeedQuery feedQuery) +202

I've search the Google documentation and on-line but have not been able to find out what I need to change.


问:
Error in running Spark in Intellij : "object apache is not a member of package org"
I am running a Spark program on Intellij and getting the below error :
"object apache is not a member of package org".

I have used these import statement in the code :

```<code>import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.SparkConf
</code>```

The above import statement is not running on sbt prompt too.
The corresponding lib appears to be missing but I am not sure how to copy the same and at which path.

答:
Make sure you have entries like this in SBT:

```<code>scalaVersion := "2.11.8"
libraryDependencies ++= Seq(
  "org.apache.spark" %% "spark-core" % "2.1.0",
  "org.apache.spark" %% "spark-sql" % "2.1.0"
)
</code>```

Then make sure IntelliJ knows about these libraries by either enabling "auto-import" or doing it manually by clicking the refresh-looking button on the SBT panel.

Body:
I am running a Spark program on Intellij and getting the below error :
"object apache is not a member of package org".

I have used these import statement in the code :

import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.SparkConf

The above import statement is not running on sbt prompt too.
The corresponding lib appears to be missing but I am not sure how to copy the same and at which path.

Body:
Make sure you have entries like this in SBT:

scalaVersion := "2.11.8"
libraryDependencies ++= Seq(
  "org.apache.spark" %% "spark-core" % "2.1.0",
  "org.apache.spark" %% "spark-sql" % "2.1.0"
)

Then make sure IntelliJ knows about these libraries by either enabling "auto-import" or doing it manually by clicking the refresh-looking button on the SBT panel.


问:
Using JSoup in a do-while loop, still throwing exceptions
When I tried to run it and check for errors, I noticed that the do-while loop inside one of my methods that allows re-tries after illegal input is not working when the method was called.

My questions are:
1) Why is the do-while loop in the PageScanner() method not working?
2) Can you suggest a better way to organize my code?

This is what it currently looks like:

First class: "BulkSpellChecker" (where I tried to organize the code)

```<code>         import java.io.*;

public class BulkSpellChecker extends ParseCleanCheck {

    public static void main(String[] args) throws IOException {
        System.out.println("Let's get started!");

        PageScanner(); // Scan the page and clean it first
        System.out.println("Thanks for using the spell checker!");
    }}
</code>```

Second Class "ParseCleanCheck" (where all of the ugly happens)

```<code>import java.io.*;
import java.util.*;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Whitelist;

public class ParseCleanCheck {

    static Scanner urlInput = new Scanner(System.in);
public static String cleanString = "";
public static String url = "";
public static boolean correct = true;

/**
 * PARSER METHOD
 */
public static void PageScanner() throws IOException {
    System.out.println("Pick a website to scan.");
    System.out.println("Enter a URL, starting with http://");

    do { // This do-while loop allows the user to try again after a mistake
        try {
            url = urlInput.nextLine();
            correct = false;
        } catch (Exception e) {
            System.out.println("Incorrect format for a URL.");
        }
    } while (correct == true);

    // This creates a document out of the HTML on the web page
    Document doc = Jsoup.connect(url).get();
    // This converts the document into a string to be cleaned
    String htmlToClean = doc.toString();
    cleanString = Jsoup.clean(htmlToClean, Whitelist.none());
}}
</code>```

disclaimer: I'm fairly new to programming and I apologize if the answer is obvious or if I posted too much code. I can edit and delete the code if necessary.

答:
Isolating the code helped me narrow down my problem from a big chunk of code to a small block of text. Bill K 's advice on fixing my while clause lead me to focus my attention onto that and eventually lead to the answer. the Jsoup URL connector should have remained in the try-block or else the program would have no way of telling whether or not it is valid. Once that was moved, it began to work perfectly.

In case someone else gets stuck trying to loop jsoup, the solution is here:

```<code>/**
     * PARSER METHOD
     */
    public static void PageScanner() throws IOException {
        System.out.println("Pick a website to scan.");

        // This do-while loop allows the user to try again after a mistake
        do {
            try {
                System.out.println("Enter a URL, starting with http://");
                url = urlInput.nextLine();
                // This creates a document out of the HTML on the web page
                Document doc = Jsoup.connect(url).get();
                // This converts the document into a string to be cleaned
                String htmlToClean = doc.toString();
                cleanString = Jsoup.clean(htmlToClean, Whitelist.none());
                correct = false;
            } catch (Exception e) {
                System.out.println("Incorrect format for a URL. Please try again.");
            }
        } while (correct);
    }
</code>```

Body:
When I tried to run it and check for errors, I noticed that the do-while loop inside one of my methods that allows re-tries after illegal input is not working when the method was called.

My questions are:
1) Why is the do-while loop in the PageScanner() method not working?
2) Can you suggest a better way to organize my code?

This is what it currently looks like:

First class: "BulkSpellChecker" (where I tried to organize the code)

         import java.io.*;

public class BulkSpellChecker extends ParseCleanCheck {

    public static void main(String[] args) throws IOException {
        System.out.println("Let's get started!");

        PageScanner(); // Scan the page and clean it first
        System.out.println("Thanks for using the spell checker!");
    }}

Second Class "ParseCleanCheck" (where all of the ugly happens)

import java.io.*;
import java.util.*;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Whitelist;

public class ParseCleanCheck {

    static Scanner urlInput = new Scanner(System.in);
public static String cleanString = "";
public static String url = "";
public static boolean correct = true;

/**
 * PARSER METHOD
 */
public static void PageScanner() throws IOException {
    System.out.println("Pick a website to scan.");
    System.out.println("Enter a URL, starting with http://");

    do { // This do-while loop allows the user to try again after a mistake
        try {
            url = urlInput.nextLine();
            correct = false;
        } catch (Exception e) {
            System.out.println("Incorrect format for a URL.");
        }
    } while (correct == true);

    // This creates a document out of the HTML on the web page
    Document doc = Jsoup.connect(url).get();
    // This converts the document into a string to be cleaned
    String htmlToClean = doc.toString();
    cleanString = Jsoup.clean(htmlToClean, Whitelist.none());
}}

disclaimer: I'm fairly new to programming and I apologize if the answer is obvious or if I posted too much code. I can edit and delete the code if necessary.

Body:
Isolating the code helped me narrow down my problem from a big chunk of code to a small block of text. Bill K 's advice on fixing my while clause lead me to focus my attention onto that and eventually lead to the answer. the Jsoup URL connector should have remained in the try-block or else the program would have no way of telling whether or not it is valid. Once that was moved, it began to work perfectly.

In case someone else gets stuck trying to loop jsoup, the solution is here:

/**
     * PARSER METHOD
     */
    public static void PageScanner() throws IOException {
        System.out.println("Pick a website to scan.");

        // This do-while loop allows the user to try again after a mistake
        do {
            try {
                System.out.println("Enter a URL, starting with http://");
                url = urlInput.nextLine();
                // This creates a document out of the HTML on the web page
                Document doc = Jsoup.connect(url).get();
                // This converts the document into a string to be cleaned
                String htmlToClean = doc.toString();
                cleanString = Jsoup.clean(htmlToClean, Whitelist.none());
                correct = false;
            } catch (Exception e) {
                System.out.println("Incorrect format for a URL. Please try again.");
            }
        } while (correct);
    }


问:
Number of arrowheads on matplotlib streamplot
Is there anyway to increase the number of arrowheads on a matplotlib streamplot? Right now it appears as if three is only one arrowhead per streamline, which is a problem if I want to change to x/y axes limits to zoom in on the data.</p>

答:
I'm not sure about just increasing the number of arrowheads - but you can increase the density of streamlines with the density parameter in the streamplot function, here's the documentation:

```<code>*density* : float or 2-tuple
    Controls the closeness of streamlines. When `density = 1`, the domain
    is divided into a 30x30 grid---*density* linearly scales this grid.
    Each cell in the grid can have, at most, one traversing streamline.
    For different densities in each direction, use [density_x, density_y].
</code>```

Here is an example:

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

x = np.arange(0,20,1)
y = np.arange(0,20,1)

u=np.random.random((x.shape[0], y.shape[0]))
v=np.random.random((x.shape[0], y.shape[0]))

fig, ax = plt.subplots(2,2)

ax[0,0].streamplot(x,y,u,v,density=1)
ax[0,0].set_title('Original')

ax[0,1].streamplot(x,y,u,v,density=4)
ax[0,1].set_xlim(5,10)
ax[0,1].set_ylim(5,10)
ax[0,1].set_title('Zoomed, higher density')

ax[1,1].streamplot(x,y,u,v,density=1)
ax[1,1].set_xlim(5,10)
ax[1,1].set_ylim(5,10)
ax[1,1].set_title('Zoomed, same density')

ax[1,0].streamplot(x,y,u,v,density=4)
ax[1,0].set_title('Original, higher density')

fig.show()
</code>```

Body:
I'm not sure about just increasing the number of arrowheads - but you can increase the density of streamlines with the density parameter in the streamplot function, here's the documentation:

*density* : float or 2-tuple
    Controls the closeness of streamlines. When `density = 1`, the domain
    is divided into a 30x30 grid---*density* linearly scales this grid.
    Each cell in the grid can have, at most, one traversing streamline.
    For different densities in each direction, use [density_x, density_y].

Here is an example:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,20,1)
y = np.arange(0,20,1)

u=np.random.random((x.shape[0], y.shape[0]))
v=np.random.random((x.shape[0], y.shape[0]))

fig, ax = plt.subplots(2,2)

ax[0,0].streamplot(x,y,u,v,density=1)
ax[0,0].set_title('Original')

ax[0,1].streamplot(x,y,u,v,density=4)
ax[0,1].set_xlim(5,10)
ax[0,1].set_ylim(5,10)
ax[0,1].set_title('Zoomed, higher density')

ax[1,1].streamplot(x,y,u,v,density=1)
ax[1,1].set_xlim(5,10)
ax[1,1].set_ylim(5,10)
ax[1,1].set_title('Zoomed, same density')

ax[1,0].streamplot(x,y,u,v,density=4)
ax[1,0].set_title('Original, higher density')

fig.show()


问:
User authentication against multiple AD groups using tomcat and JNDI
I am hoping someone can help me out with this or at least confirm that it can be done.

Currently, for my web application , when the user submits their login information, I authenticate them against an Active directory using tomcat server.xml JNDI Realm configuration.

This is the current config:

```<code>Realm
alternateURL="ldaps://xxx.yyy.com:ddd"
className="org.apache.catalina.realm.JNDIRealm"
connectionName="CN=ggg,OU=Generic_IDs,OU=Users,OU=hhh,DC=jjj,DC=com"
connectionPassword="pppp"
connectionURL="ldaps://fff.yyy.com:ddd"
roleBase="ou=Managed_Groups,ou=Groups,ou=hhh Inc,dc=jjj,dc=com"
roleName="cn"
roleSearch="(member={0})"
roleSubtree="false"
userBase="ou=hhh,dc=jjj,dc=com"
userRoleName="(member={0})"
userSearch="(&(sAMAccountName={0})(objectClass=user))"
userSubtree="true"
</code>```

My Requirement: Now, we have some users who are set up in another Active Directory, on a separate server. I need a way for the server to first try and autheticate the user against the first AD server and if not succesfull, connect to the second AD and authenticate the user the user against that. If authentiation fails here then display the access denied page.

Is there a way to do this?

Would appreciate the help. Thanks!

答:
I used the next realm tags</p>

```<code><Realm className="org.apache.catalina.realm.CombinedRealm" >
    <Realm className="org.apache.catalina.realm.JNDIRealm"
        connectionURL="ldap://dc01.domain.com:3268"
        useDelegatedCredential="true"
        userBase="cn=Users,dc=domain,dc=com"
        userSearch="(sAMAccountName={0})"
        userRoleName="memberOf"
        roleSubtree="true"
        roleName="cn"
        roleSearch="(member={0})"
        commonRole="test1"
        roleNested="true" />

    <Realm className="org.apache.catalina.realm.JNDIRealm"
        connectionURL="ldap://dc01.domain.com:3268"
        useDelegatedCredential="true"
        userBase="cn=Users,dc=domain,dc=com"
        userSearch="(sAMAccountName={0})"
        userRoleName="memberOf"
        roleSubtree="true"
        roleName="cn"
        roleSearch="(member={0})"
        commonRole="test2"
        roleNested="true" />
</Realm>
</code>```

Body:
I am hoping someone can help me out with this or at least confirm that it can be done.

Currently, for my web application , when the user submits their login information, I authenticate them against an Active directory using tomcat server.xml JNDI Realm configuration.

This is the current config:

Realm
alternateURL="ldaps://xxx.yyy.com:ddd"
className="org.apache.catalina.realm.JNDIRealm"
connectionName="CN=ggg,OU=Generic_IDs,OU=Users,OU=hhh,DC=jjj,DC=com"
connectionPassword="pppp"
connectionURL="ldaps://fff.yyy.com:ddd"
roleBase="ou=Managed_Groups,ou=Groups,ou=hhh Inc,dc=jjj,dc=com"
roleName="cn"
roleSearch="(member={0})"
roleSubtree="false"
userBase="ou=hhh,dc=jjj,dc=com"
userRoleName="(member={0})"
userSearch="(&(sAMAccountName={0})(objectClass=user))"
userSubtree="true"

My Requirement: Now, we have some users who are set up in another Active Directory, on a separate server. I need a way for the server to first try and autheticate the user against the first AD server and if not succesfull, connect to the second AD and authenticate the user the user against that. If authentiation fails here then display the access denied page.

Is there a way to do this?

Would appreciate the help. Thanks!

Body:
I used the next realm tags

<Realm className="org.apache.catalina.realm.CombinedRealm" >
    <Realm className="org.apache.catalina.realm.JNDIRealm"
        connectionURL="ldap://dc01.domain.com:3268"
        useDelegatedCredential="true"
        userBase="cn=Users,dc=domain,dc=com"
        userSearch="(sAMAccountName={0})"
        userRoleName="memberOf"
        roleSubtree="true"
        roleName="cn"
        roleSearch="(member={0})"
        commonRole="test1"
        roleNested="true" />

    <Realm className="org.apache.catalina.realm.JNDIRealm"
        connectionURL="ldap://dc01.domain.com:3268"
        useDelegatedCredential="true"
        userBase="cn=Users,dc=domain,dc=com"
        userSearch="(sAMAccountName={0})"
        userRoleName="memberOf"
        roleSubtree="true"
        roleName="cn"
        roleSearch="(member={0})"
        commonRole="test2"
        roleNested="true" />
</Realm>