问:
With pure JavaScript, is there an easy way to attach an event listener to a class?
I'm looking for the JavaScript equivalent of

```<code>$(".class-name").on(eventName, eventHandler);
</code>```

first I tried

```<code>document.querySelectorAll(".class-name").addEventListener(eventName, eventHandler);
</code>```

but it didn't work. Is there an easy way to do it in JavaScript?

------Update------

Many answers suggested a loop, but originally I was looking for a solution with a single listener to save memory (suppose I had 1000 items in that class).
However, one answer reminded me: does the jQuery version also create 1000 listeners in the memory?

答:
Yes, absolutely!

EDIT: Turns out you want to add it to every element with that class. In that case you should try with

let elements = document.getElementsByClassName("myClass")

After that you could just cycle through them with a for loop and attach the event listener.

Body:
I'm looking for the JavaScript equivalent of

$(".class-name").on(eventName, eventHandler);

first I tried

document.querySelectorAll(".class-name").addEventListener(eventName, eventHandler);

but it didn't work. Is there an easy way to do it in JavaScript?

------Update------

Many answers suggested a loop, but originally I was looking for a solution with a single listener to save memory (suppose I had 1000 items in that class).
However, one answer reminded me: does the jQuery version also create 1000 listeners in the memory?


来源: stackexchange

问:
Phusion Passenger 5.1.11 doesn't recognize --start-timeout option
According to the blog https://blog.phusion.nl/2017/10/16/passenger-5-1-11/

[Standalone] passenger start now accepts the --start-timeout configuration option.

I have passenger gem installed and it has a version: "Phusion Passenger 5.1.11".

But, when I run passenger start --start-timeout 300 it says:
*** ERROR: invalid option: --start-timeout

Is there a way to make --start-timeout option work? Do I miss anything?

答: This is an enterprise-only flag. The release announcement should have been more clear. </p>

ContentLicense: CC BY-SA 3.0


问:
How to query to use sort function for array of dictionary
My data look like below:

```<code>{
  "name":"blah",
  "address":[{
            "city":"abc"
            }]
},
{
  "name":"blah2",
  "address":[{
            "city":"a"
            }]
}
</code>```

Now I want to have sorted data by city of address. how should I write my index and write selector to select all documents?

UPDATE:
I want to sort first by city and then by name.

答:
You can achieve this easily with a standard map:

```<code>function(doc) {
  if (doc && doc.address) {
      emit(doc.address[0].city, 1)
  }
}
</code>```

Get docs ordered by key using

```<code>curl 'https://..../_design/DDOC/_view/VNAME?include_docs=true'
</code>```

EDIT:

If you want to order first by city, and then by name, emit a vector-valued key:

```<code>function(doc) {
   if (doc && doc.address && doc.name) {
      emit([doc.address[0].city, doc.name], 1)
   }
}
</code>```

Body:
My data look like below:

{
  "name":"blah",
  "address":[{
            "city":"abc"
            }]
},
{
  "name":"blah2",
  "address":[{
            "city":"a"
            }]
}

Now I want to have sorted data by city of address. how should I write my index and write selector to select all documents?

UPDATE:
I want to sort first by city and then by name.

Body:
You can achieve this easily with a standard map:

function(doc) {
  if (doc && doc.address) {
      emit(doc.address[0].city, 1)
  }
}

Get docs ordered by key using

curl 'https://..../_design/DDOC/_view/VNAME?include_docs=true'

EDIT:

If you want to order first by city, and then by name, emit a vector-valued key:

function(doc) {
   if (doc && doc.address && doc.name) {
      emit([doc.address[0].city, doc.name], 1)
   }
}


问:
Reference type of JVM
In some Java literature, The statement

The reference type of the Java virtual
  machine is cleverly named
  reference

is widely popular. However, authors tend not to explain more why such statement is valid. Another thing that would make me understand this more is

What does the reference type of the JVM means ? Does the JVM represent itself in the heap ?

Would appreciate a lot an explanation on this statement.

Thank you,

Ashmawy

答:
The word you're looking for here is irony:

the use of words to convey a meaning that is the opposite of its literal meaning

The use of "clever" in that sentence is clearly ironic.  "The reference type of the Java virtual machine is given the clearly really stupidly obvious name 'reference'" is another way to read that sentence.

ContentLicense: CC BY-SA 2.5

Title: Reference type of JVM


问:
Efficient way for replace strings from a vocabulary - Python
I have a vocabulary of phrases and I want to replace words of another file by these words. For example, I have the following vocabulary:

United States,
New York

and I want to replace the following file:

"I work for New York but I don't even live at the United States"

To this:

"I work for New_York but I don't even live at the United_States"

Currently I'm doing at this way:

```<code>import os

def _check_files_and_write_phrases(docs, worker_num):
    print("worker ", worker_num," started!")
    for i, file in enumerate(docs):
        file_path = DOCS_FOLDER + file
        with open(file_path) as f:
            text = f.read()
            for phrase in phrases:
                text = text.replace(phrase, phrase.replace(' ','_'))
            new_doc = PHRASES_DOCS_FOLDER + file[:-4] + '_phrases.txt'
            with open(new_doc, 'w') as nf:
                nf.write(text)

    print("job done on worker ", worker_num)

docs = os.listdir(DOCS_FOLDER)

import threading

threads = []
for i in range(1, 11):
    print(i)
    start = int((len(docs)/10) * (i - 1))
    end = int((len(docs)/10) * (i))
    print(start,end)
    if i != 10:
        t = threading.Thread(target=_check_files_and_write_phrases, args=(docs[start:end], i, ))
    else:
        t = threading.Thread(target=_check_files_and_write_phrases, args=(docs[start:], i, ))
    threads.append(t)
    t.start()

for t in threads:
    t.join()

print("all workers finished!")
</code>```

But it's way too slow! I thought that threads would do the job but I was wrong...

Is there another efficient way of doing this?

答:
All of the phrases could be replaced using a single re.sub() call which could be pre-compiled to further speed things up a bit:

```<code>import re

phrases = {"United States":"United_States", "New York":"New_York"}
re_replace = re.compile(r'\b({})\b'.format('|'.join(re.escape(phrase) for phrase in phrases.keys())))

def _check_files_and_write_phrases(docs, worker_num):
    print("worker {} started!".format(worker_num))

    for i, filename in enumerate(docs):
        file_path = DOCS_FOLDER + filename

        with open(file_path) as f:
            text = f.read()
            text = re_replace.sub(lambda x: phrases[x.group(1)], text)
            new_doc = PHRASES_DOCS_FOLDER + filename[:-4] + '_phrases.txt'

            with open(new_doc, 'w') as nf:
                nf.write(text)

    print("job done on worker ", worker_num)
</code>```

This first creates a regular expression to search on as follows based on a dictionary of phrases:

```<code>\b(United\ States|New\ York)\b
</code>```

The re.sub() function then uses the phrases dictionary to look up the required phrase replacement. It takes two parameters, the replacement and the original text. The replacement can either be a fixed string, or in this case a function is used. The function takes a single argument being the matched object, and returns the replacement text. A lambda function is used to do this, it simply looks up the match object in phrases dictionary.

Instead of doing a dictionary lookup, it could just use a replace() here but the pre-calculated replacement text should be faster. The \b is added to only make replacements which are on word boundaries, so for example MYNew York would be skipped. Adding flags=re.I to the re.compile() could be used to make the search case insensitive if needed.

Body:
I have a vocabulary of phrases and I want to replace words of another file by these words. For example, I have the following vocabulary:

United States,
New York

and I want to replace the following file:

"I work for New York but I don't even live at the United States"

To this:

"I work for New_York but I don't even live at the United_States"

Currently I'm doing at this way:

import os

def _check_files_and_write_phrases(docs, worker_num):
    print("worker ", worker_num," started!")
    for i, file in enumerate(docs):
        file_path = DOCS_FOLDER + file
        with open(file_path) as f:
            text = f.read()
            for phrase in phrases:
                text = text.replace(phrase, phrase.replace(' ','_'))
            new_doc = PHRASES_DOCS_FOLDER + file[:-4] + '_phrases.txt'
            with open(new_doc, 'w') as nf:
                nf.write(text)

    print("job done on worker ", worker_num)

docs = os.listdir(DOCS_FOLDER)

import threading

threads = []
for i in range(1, 11):
    print(i)
    start = int((len(docs)/10) * (i - 1))
    end = int((len(docs)/10) * (i))
    print(start,end)
    if i != 10:
        t = threading.Thread(target=_check_files_and_write_phrases, args=(docs[start:end], i, ))
    else:
        t = threading.Thread(target=_check_files_and_write_phrases, args=(docs[start:], i, ))
    threads.append(t)
    t.start()

for t in threads:
    t.join()

print("all workers finished!")

But it's way too slow! I thought that threads would do the job but I was wrong...

Is there another efficient way of doing this?

Body:
All of the phrases could be replaced using a single re.sub() call which could be pre-compiled to further speed things up a bit:

import re

phrases = {"United States":"United_States", "New York":"New_York"}
re_replace = re.compile(r'\b({})\b'.format('|'.join(re.escape(phrase) for phrase in phrases.keys())))

def _check_files_and_write_phrases(docs, worker_num):
    print("worker {} started!".format(worker_num))

    for i, filename in enumerate(docs):
        file_path = DOCS_FOLDER + filename

        with open(file_path) as f:
            text = f.read()
            text = re_replace.sub(lambda x: phrases[x.group(1)], text)
            new_doc = PHRASES_DOCS_FOLDER + filename[:-4] + '_phrases.txt'

            with open(new_doc, 'w') as nf:
                nf.write(text)

    print("job done on worker ", worker_num)

This first creates a regular expression to search on as follows based on a dictionary of phrases:

\b(United\ States|New\ York)\b

The re.sub() function then uses the phrases dictionary to look up the required phrase replacement. It takes two parameters, the replacement and the original text. The replacement can either be a fixed string, or in this case a function is used. The function takes a single argument being the matched object, and returns the replacement text. A lambda function is used to do this, it simply looks up the match object in phrases dictionary.

Instead of doing a dictionary lookup, it could just use a replace() here but the pre-calculated replacement text should be faster. The \b is added to only make replacements which are on word boundaries, so for example MYNew York would be skipped. Adding flags=re.I to the re.compile() could be used to make the search case insensitive if needed.


问:
Automate loading .env when Hubot starts
I'm developing an app with the Hubot framework, using Heroku.
I have some config vars set on Heroku, and when I deploy my code, my process.env references work fine.

However, I've had trouble getting my local development system set up with the config vars for testing. I have a .env file and have fetched all the config vars from Heroku. However, the .env file does not seem to be loaded when I start my app at the command line.

I've added hubot-env (as suggested at Hubot - load environmental variables from a file) and can load my .env file manually each time I start my app with the command

```<code>hubot env load --filename=[filename]
</code>```

I'd like to automate this, so this command is automatically executed when I start my bot. Where could I configure this?

答:
Regarding this issue as I understood Hubot doesn't read .env file. Instead of exporting variables each time my solution was to create bash-script run.sh file:

```<code>#!/bin/bash

export HUBOT_OWM_APIKEY=MY_OWM_API_KEY;
export HUBOT_WEATHER_UNITS=metric;

HUBOT_SLACK_TOKEN=xoxb-xxxx-MY_SLACK_TOKEN ./bin/hubot --adapter slack
</code>```

then in bash

```<code>$ chmod +x run.sh   # provides the permissions
$ ./run.sh          # starts the bot with necessary variables
</code>```

Title: Automate loading .env when Hubot starts

Body:
I'm developing an app with the Hubot framework, using Heroku.
I have some config vars set on Heroku, and when I deploy my code, my process.env references work fine.

However, I've had trouble getting my local development system set up with the config vars for testing. I have a .env file and have fetched all the config vars from Heroku. However, the .env file does not seem to be loaded when I start my app at the command line.

I've added hubot-env (as suggested at Hubot - load environmental variables from a file) and can load my .env file manually each time I start my app with the command

hubot env load --filename=[filename]

I'd like to automate this, so this command is automatically executed when I start my bot. Where could I configure this?

Body:
Regarding this issue as I understood Hubot doesn't read .env file. Instead of exporting variables each time my solution was to create bash-script run.sh file:

#!/bin/bash

export HUBOT_OWM_APIKEY=MY_OWM_API_KEY;
export HUBOT_WEATHER_UNITS=metric;

HUBOT_SLACK_TOKEN=xoxb-xxxx-MY_SLACK_TOKEN ./bin/hubot --adapter slack

then in bash

$ chmod +x run.sh   # provides the permissions
$ ./run.sh          # starts the bot with necessary variables


问:
rename all files and folder ftp in php language
i want rename all files and folder recursively i written a function that works and rename files but my problem when occurred when i make array of files and folders in a path, its not sort as parent child
so when i rename parent folder first , in next loop when function wants rename child said "No such file or directory" its true Error cause parent folder renamed a couple minutes ago

i changed my code but not help me
code for reading files and folder from ftp :

```<code> if (!self::ftp_is_dir($resource, $thisPath)) {
        // for Files (anything that isnt a readable directory)
        if ($first == TRUE) {
            return array("Path doesn't Exist (" . $thisPath . ")");
        }
        $theList[] = $thisPath;
        return $theList;
    } else {
        $contents = ftp_nlist($resource, $thisPath);

        // For empty folders
        if (count($contents) == 0) {
            $theList[] = $thisPath;
            return $theList;
        } else {
            $theList[] = $thisPath;
        }

        // Recursive Part
        foreach ($contents As $file) {
            $theList = self::ftp_nlistr($resource, $file, $theList, FALSE);
        }

        return $theList;

    }
</code>```

and this return array like this
enter image description here

and this code i used for renaming folder and files

```<code>$replacers = array(" ", "", "  ", "-=", "=-", '©',"!", ";", "#", "@", "'", '<', '>');
    foreach ($paths as $path) {
        if (preg_match('/' . implode('|', $replacers) . '/', $path) != 0) {

            $route = preg_replace('/ftp/', "ftp://ftp.mylocal.co", $path, 1);;
            if (is_dir($route)) {
                $newName = str_replace($replacers, "_", basename($path));
                $directory = pathinfo($path);
                if (ftp_rename($connectionID, $path, $directory['dirname'] . '/' . $newName)) {
                    Logger::setLog('renaming', "Renaming: $path to $newName");
                } else {
                    Logger::setLog('failed to renaming', "Renaming: $path to $newName");
                }
            } else {
                $newName = str_replace($replacers, "_", basename($path));
                $directory = pathinfo($path);

                if (ftp_rename($connectionID, $path, $directory['dirname'] . '/' . $newName)) {
                    Logger::setLog('renaming', "Renaming: $path to $newName");
                } else {
                    Logger::setLog('failed to renaming', "Renaming: $path to $newName");
                }

            }
        }
    }
</code>```

[1]: https://i.stack.imgur.com/xk3kx.png

```<code>public static function ftp_is_dir($conn, $dir)
{
    $cdir = ftp_pwd($conn);
    if (@ftp_chdir($conn, $dir)) {
        ftp_chdir($conn, $cdir);
        return true;
    } else {
        return false;
    }
}
</code>```

答:
If you have:

+ folder
  - file1
  - file2
+ folder with space
  - file with space
```

<p>... you currently first rename <code>/folder with space</code> to <code>/folder_with_space</code>.</p>

<p>And then you try to rename <code>/folder with space/file with space</code> to <code>/folder with space/file_with_space</code>. But that file does not exist anymore.</p>

<p>The easiest solution is to actually first rename children, then parent:</p>

```    $contents = ftp_nlist($resource, $thisPath);

    // Recursive Part
    foreach ($contents As $file) {
        $theList = self::ftp_nlistr($resource, $file, $theList, FALSE);
    }

    $theList[] = $thisPath;

    return $theList;
```

Body:
i want rename all files and folder recursively i written a function that works and rename files but my problem when occurred when i make array of files and folders in a path, its not sort as parent child
so when i rename parent folder first , in next loop when function wants rename child said "No such file or directory" its true Error cause parent folder renamed a couple minutes ago

i changed my code but not help me
code for reading files and folder from ftp :

 if (!self::ftp_is_dir($resource, $thisPath)) {
        // for Files (anything that isnt a readable directory)
        if ($first == TRUE) {
            return array("Path doesn't Exist (" . $thisPath . ")");
        }
        $theList[] = $thisPath;
        return $theList;
    } else {
        $contents = ftp_nlist($resource, $thisPath);

        // For empty folders
        if (count($contents) == 0) {
            $theList[] = $thisPath;
            return $theList;
        } else {
            $theList[] = $thisPath;
        }

        // Recursive Part
        foreach ($contents As $file) {
            $theList = self::ftp_nlistr($resource, $file, $theList, FALSE);
        }

        return $theList;

    }

and this return array like this
enter image description here

and this code i used for renaming folder and files

$replacers = array(" ", "", "  ", "-=", "=-", '©',"!", ";", "#", "@", "'", '<', '>');
    foreach ($paths as $path) {
        if (preg_match('/' . implode('|', $replacers) . '/', $path) != 0) {

            $route = preg_replace('/ftp/', "ftp://ftp.mylocal.co", $path, 1);;
            if (is_dir($route)) {
                $newName = str_replace($replacers, "_", basename($path));
                $directory = pathinfo($path);
                if (ftp_rename($connectionID, $path, $directory['dirname'] . '/' . $newName)) {
                    Logger::setLog('renaming', "Renaming: $path to $newName");
                } else {
                    Logger::setLog('failed to renaming', "Renaming: $path to $newName");
                }
            } else {
                $newName = str_replace($replacers, "_", basename($path));
                $directory = pathinfo($path);

                if (ftp_rename($connectionID, $path, $directory['dirname'] . '/' . $newName)) {
                    Logger::setLog('renaming', "Renaming: $path to $newName");
                } else {
                    Logger::setLog('failed to renaming', "Renaming: $path to $newName");
                }

            }
        }
    }

[1]: https://i.stack.imgur.com/xk3kx.png

public static function ftp_is_dir($conn, $dir)
{
    $cdir = ftp_pwd($conn);
    if (@ftp_chdir($conn, $dir)) {
        ftp_chdir($conn, $cdir);
        return true;
    } else {
        return false;
    }
}

Body:
If you have:

+ folder
  - file1
  - file2
+ folder with space
  - file with space

... you currently first rename /folder with space to /folder_with_space.

And then you try to rename /folder with space/file with space to /folder with space/file_with_space. But that file does not exist anymore.

The easiest solution is to actually first rename children, then parent:

    $contents = ftp_nlist($resource, $thisPath);

    // Recursive Part
    foreach ($contents As $file) {
        $theList = self::ftp_nlistr($resource, $file, $theList, FALSE);
    }

    $theList[] = $thisPath;

    return $theList;


问:
Having javascript apply to multiple elements created by php foreach loop
I have this php foreach loop, which read the videos saved in a folder and load them into my page.
Under the videos I have created a like and dislike button, which i would like to work with javascript.
The problem is that I cant figure out, how to point js to buttons, when i create unique ID's for the buttons, with a counter in my foreach loop.

My php.

```<code>$i=1;
foreach($allfiles as $file) {
if($file != '.' && $file != '..' && $file != video/ini) // sikre den ikke
producere . og .. files
{

echo "<div>
        <div>
                        <video width=\"$videoW\" height=\"$videoH\"
controls>
                          <source src=\"". $dir . $file ."\" type=\"video/mp4\">
                          <source src=\"". $dir . $file ."\" type=\"video/ogg\">
                        </video>
                    </div>

<div><strong> Recorded:</strong> $file </div> </div>";

echo '<img src="/img/like-icon.png" id="like'.$i.'"
style="width:40px;height:40px;">';
echo '<img src="/img/dislike-icon.png" id="dislike'.$i.'"
style="width:40px;height:40px;">';
echo '<p style=display:none; id="text'.$i.'">Submitted!</p>';
$i++;
</code>```

My javascript

```<code><script type='text/javascript'>
      for (var i = 0; i < 100; i++) {

        var button = document.getElementById(like[i]);
        var button2 = document.getElementById(dislike[i]);

        button.onclick = function() {
           var text = document.getElementById(text[i]);
           var like = document.getElementById(like[i]);
           var dislike = document.getElementById(dislike[i]);
           if (text.style.display !== 'none') {
              text.style.display = 'none';

           }
           else {
              text.style.display = 'block';
              like.style.display = 'none';
              dislike.style.display = 'none';
        }
     };

        button2.onclick = function() {
           var text = document.getElementById(text[i]);
           var dislike = document.getElementById(dislike[i]);
           var like = document.getElementById(like[i]);

           if (text.style.display !== 'none') {
              text.style.display = 'none';

           }
           else {
             text.style.display = 'block';
             like.style.display = 'none';
             dislike.style.display = 'none';
        }

     };
  };
</code>```

答:
Your code is very weird... Why are you looping a hundred time to select one element ?

You should look at querySelector and querySelectorAll with which you can select anything using a css selector. For example :

```<code>document.querySelectorAll('.like');
</code>```

Will return a node list (which you can loop over) containing every element with class="like"

In this case you might want to add an event listener over each element. You can imagine something like this :

```<code>var likes = document.querySelectorAll('.like');

for (var i = 0, length = likes.length; i < length; i++) {
     likes[i].addEventListener('event', myFunction);
}
</code>```

If you don't like querySelectors, you still have some other ways to select multiple elements such as :

getElementsByClassName

getElementsByTagName

Also, you shouldn't overwrite style attribute. It's more comfortable to work on project where it is easy to find initial state and changed state. Maybe you should think of a class hidden (for example) which would be like this :

```<code>.hidden {
    display: none;
}
</code>```

So if you want to hide them all, you'd juste have to run :

```<code>var likes = document.querySelectorAll('.like');

for (var i = 0, length = likes.length; i < length; i++) {
     likes[i].classList.add('hidden');
}
</code>```

In case this is resulting of an action :

```<code>var likes = document.querySelectorAll('.like');

for (var i = 0, length = likes.length; i < length; i++) {
     likes[i].addEventListener('event', myFunction);
}

function myFunction() {
     this.classList.toggle('hidden');
}
</code>```

Body:
I have this php foreach loop, which read the videos saved in a folder and load them into my page.
Under the videos I have created a like and dislike button, which i would like to work with javascript.
The problem is that I cant figure out, how to point js to buttons, when i create unique ID's for the buttons, with a counter in my foreach loop.

My php.

$i=1;
foreach($allfiles as $file) {
if($file != '.' && $file != '..' && $file != video/ini) // sikre den ikke
producere . og .. files
{

echo "

                        <video width=\"$videoW\" height=\"$videoH\"
controls>
                          <source src=\"". $dir . $file ."\" type=\"video/mp4\">
                          <source src=\"". $dir . $file ."\" type=\"video/ogg\">
                        </video>

 Recorded: $file

";

echo '';
echo '';
echo '
Submitted!
';
$i++;

My javascript

Body:
Your code is very weird... Why are you looping a hundred time to select one element ?

You should look at querySelector and querySelectorAll with which you can select anything using a css selector. For example :

document.querySelectorAll('.like');

Will return a node list (which you can loop over) containing every element with class="like"

In this case you might want to add an event listener over each element. You can imagine something like this :

var likes = document.querySelectorAll('.like');

for (var i = 0, length = likes.length; i < length; i++) {
     likes[i].addEventListener('event', myFunction);
}

If you don't like querySelectors, you still have some other ways to select multiple elements such as :

getElementsByClassName

getElementsByTagName

Also, you shouldn't overwrite style attribute. It's more comfortable to work on project where it is easy to find initial state and changed state. Maybe you should think of a class hidden (for example) which would be like this :

.hidden {
    display: none;
}

So if you want to hide them all, you'd juste have to run :

var likes = document.querySelectorAll('.like');

for (var i = 0, length = likes.length; i < length; i++) {
     likes[i].classList.add('hidden');
}

In case this is resulting of an action :

var likes = document.querySelectorAll('.like');

for (var i = 0, length = likes.length; i < length; i++) {
     likes[i].addEventListener('event', myFunction);
}

function myFunction() {
     this.classList.toggle('hidden');
}


问:
Mock HttpClient using Moq
I would like to unit test a class that uses HttpClient. We injected the HttpClient object in the class constructor.

```<code>public class ClassA : IClassA
{
    private readonly HttpClient _httpClient;

    public ClassA(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task<HttpResponseMessage> SendRequest(SomeObject someObject)
    {
        //Do some stuff

        var request = new HttpRequestMessage(HttpMethod.Post, "http://some-domain.in");

        //Build the request

        var response = await _httpClient.SendAsync(request);

        return response;
    }
}
</code>```

Now we would like to unit test the ClassA.SendRequest method. We are using Ms Test for unit testing framework and Moq for mocking.

When we tried to mock the HttpClient, it throws NotSupportedException.

```<code>[TestMethod]
public async Task SendRequestAsync_Test()
{
    var mockHttpClient = new Mock<HttpClient>();

    mockHttpClient.Setup(
        m => m.SendAsync(It.IsAny<HttpRequestMessage>()))
    .Returns(() => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)));
}
</code>```

How can we solve this issue?

答:
Propper mocking with HttpClient is hard work as it was written before most people did unit testing in dotnet. Sometimes I setup a stub HTTP server that returns canned responses based on pattern matching the request url, meaning you test real HTTP requests not mocks but to a localhost server. Using WireMock.net makes this really easy and runs fast enough to satisfy most of my unit testing needs.

So instead of http://some-domain.in use a localhost server setup on some port, and then:

```<code>var server = FluentMockServer.Start(/*server and port can be setup here*/);
server.Given(
      Request.Create()
      .WithPath("/").UsingPost()
   )
   .RespondWith(
       Response.Create()
       .WithStatusCode(200)
       .WithHeader("Content-Type", "application/json")
       .WithBody("{'attr':'value'}")
   );
</code>```

You can find a more details and guidance on using wiremock in tests here.

ContentLicense: CC BY-SA 4.0

Title: Mock HttpClient using Moq

Body:
I would like to unit test a class that uses HttpClient. We injected the HttpClient object in the class constructor.

public class ClassA : IClassA
{
    private readonly HttpClient _httpClient;

    public ClassA(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task<HttpResponseMessage> SendRequest(SomeObject someObject)
    {
        //Do some stuff

        var request = new HttpRequestMessage(HttpMethod.Post, "http://some-domain.in");

        //Build the request

        var response = await _httpClient.SendAsync(request);

        return response;
    }
}

Now we would like to unit test the ClassA.SendRequest method. We are using Ms Test for unit testing framework and Moq for mocking.

When we tried to mock the HttpClient, it throws NotSupportedException.

[TestMethod]
public async Task SendRequestAsync_Test()
{
    var mockHttpClient = new Mock<HttpClient>();

    mockHttpClient.Setup(
        m => m.SendAsync(It.IsAny<HttpRequestMessage>()))
    .Returns(() => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)));
}

How can we solve this issue?

Body:
Propper mocking with HttpClient is hard work as it was written before most people did unit testing in dotnet. Sometimes I setup a stub HTTP server that returns canned responses based on pattern matching the request url, meaning you test real HTTP requests not mocks but to a localhost server. Using WireMock.net makes this really easy and runs fast enough to satisfy most of my unit testing needs.

So instead of http://some-domain.in use a localhost server setup on some port, and then:

var server = FluentMockServer.Start(/*server and port can be setup here*/);
server.Given(
      Request.Create()
      .WithPath("/").UsingPost()
   )
   .RespondWith(
       Response.Create()
       .WithStatusCode(200)
       .WithHeader("Content-Type", "application/json")
       .WithBody("{'attr':'value'}")
   );

You can find a more details and guidance on using wiremock in tests here.


问:
C# asp.net build SQL Query dynamically from viewstate
On my C# asp.net webform I have a search page that has roughly 20 elements that "could" be used as part of the search.  There will be more added later.

What I have done is extend the textbox and dropdown listbox to include a few variables:

fieldname: Tablename.columnname
dbtype: DbType.Int32
Joinparam: LEFT Join on otherTable ON x.y = a.b

These are all stored in the viewstate and loaded back in.  The reason I do this is so that I can iterate through all the controls and pull out all the controls that are of my type.  I can then validate them to make sure they have input and are of the right type.  If so I can then pass them off to the database access layer and let the code dynamically generate the SQL statement.

I do not let anything but SELECT statements happen from this.  The fields selected and returned can not be changed and I use the dbparameter to try and avoid sql injection.

My worry is that I put the table and field names that will be used in the search criteria and the JOINS required all in the viewstate.  Is this a real bad idea?

I could obscurify this by just having some int index's into tables that hold this info in the DB but this would still need to be put into the viewstate and just mean they would have an extra layer to figure out.

The reason I went for this approach was that I did not want to have to put tons of IF statements in the DB layer to build the statement there.  It would be ugly as hell and a pain to maintain.

Thanks for any and all advice about this.

Jon

EDIT

Thanks all for the advice.  Thankfully this app is an internal thing only so the damage would be limited.  But I will never use this technique again and will work on the search template idea instead.

Cheers :)

答:
Viewstate is not encrypted, it is base64 encoded. There are utilities readily available that will allow you to decode a page's viewstate.

It is possible to encrypt viewstate for a page or all of your pages however:
http://msdn.microsoft.com/en-us/library/aa479501.aspx

That said, I would not recommend this approach. The best approach for application design is to decouple your UI from your business and data access logic. In this case, you would be closely coupling them for no apparent benefit.

If you did build a more robust ad-hoc query feature into your data access layer, you might be adding value to the back end of your application. You could provide search capabilities via web services, windows forms apps etc. Even if this type of functionality is not something you envision happening in the near future, it can be a huge time (and $$$) saver when you take this approach.

The logic you have built into the UI could easily be built into some type of query engine. Instead of the IFs that you wanted to avoid, you can build a method to assemble a query by dynamically adding criteria to it.

OwnerDisplayName: Jon

LastEditorDisplayName: Jon

OwnerDisplayName: Jim Petkus

LastEditorDisplayName: Jim Petkus


问:
How to write automated integrated tests when using JTA?
I want to write integration tests for the application I'm working on. It uses JTA (multiple resources) and runs inside an application server. What is the best way for writing an automated test for such a scenario? Using an standalone transaction manager like atomikos or somehow leveraging the app server api/tools for transaction handling?</p>

答: Sounds like a good plan, might be a bit complicated satisfying the environment required by all those resources.</p>


问:
VBA 7.1 Backwards Compatibility
I am developing some VBA code using VBA 7.1 with excel 2016 as part of a larger enterprise application (not primarily in excel). The macros are run from a C# application and used to export data in the form of spreadsheets. I am looking for a good guide as to what versions of excel these macros will run properly on, and where I can look for changes that could potentially cause my code to break. I developed it using excel 2016, how backwards compatible will this be?

I would like to make it compatible as far back as the 2010 excel version if possible.

答:
If you need compatibility with VBA6 and VBA7, this is a good example how to achieve it through compiler constants:

```<code>Option Explicit

#If VBA6 Then
    Sub RunTheApp()
        Debug.Print "VBA6"
    End Sub
#ElseIf VBA7 Then
    Sub RunTheApp()
        Debug.Print "VBA7"
    End Sub
#Else
    Sub RunTheApp()
        Debug.Print "You cannot come here from TestMe()"
    End Sub
#End If

Sub TestMe()
    RunTheApp
End Sub
</code>```

Once you try to run the TestMe module, it will print VBA6 or VBA7, depending on your system.

MSDN - Compiler Constants

In general, VBA7 has compability for 64bit environment. Here is the MSDN article for the differences between these two - Compatibility between the 32-bit and 64-bit Versions of Office 2010 It is a good idea to read it, if you are using external functions that are embedded in dynamic linked libraries.

Title: VBA 7.1 Backwards Compatibility

Body:
If you need compatibility with VBA6 and VBA7, this is a good example how to achieve it through compiler constants:

Option Explicit

#If VBA6 Then
    Sub RunTheApp()
        Debug.Print "VBA6"
    End Sub
#ElseIf VBA7 Then
    Sub RunTheApp()
        Debug.Print "VBA7"
    End Sub
#Else
    Sub RunTheApp()
        Debug.Print "You cannot come here from TestMe()"
    End Sub
#End If

Sub TestMe()
    RunTheApp
End Sub

Once you try to run the TestMe module, it will print VBA6 or VBA7, depending on your system.

MSDN - Compiler Constants

In general, VBA7 has compability for 64bit environment. Here is the MSDN article for the differences between these two - Compatibility between the 32-bit and 64-bit Versions of Office 2010 It is a good idea to read it, if you are using external functions that are embedded in dynamic linked libraries.


问:
Errors when trying add a member to MailChimp list via API
I've tweaked the code and I think I'm getting closer to the solution, but still receiving an error.

```<code>public function onPluginsInitialized()
    {
         $this->add_member();
    }

public function add_member() {
    require __DIR__.'/vendor/autoload.php';

    $url = 'url';
    $api_key = 'api_key';
    $list_id = 'list_id';

    $client = new \GuzzleHttp\Client();

    $result = $client->request('POST', $url.'lists/'.$list_id.'/members', [
        'headers' => [
            'Authorization' => 'apikey '.$api_key,
            'json' => [
                'email_address' => $_POST['email'],
                'email_type'    => 'html',
                'status'        => 'subscribed'
            ]
        ],
        'verify' => false,
        'debug' => false
    ]);
}
</code>```

Here's the error I'm getting:

'Undefined index: email' Where shall I define email? How to catch it from the form?

I tried to follow this example. However, my syntax is different. I shall add that the reason for my syntax is dictated by the fact that I'm trying to create a plugin for GRAV, also using Guzzle.

答:
OK, I've finally got it sorted. I'm posting the answer in case someone else will be struggling with that one.

```<code>'headers' => [
            'Authorization' => 'apikey '.$api_key,
],
'json' => [
        'email_address' => $_POST['email'],
        'email_type'    => 'html',
        'status'        => 'subscribed'
]
</code>```

Basically 'json' array should not be in the 'headers'. Also, removed 'debug' and 'verify'.

Body:
I've tweaked the code and I think I'm getting closer to the solution, but still receiving an error.

public function onPluginsInitialized()
    {
         $this->add_member();
    }

public function add_member() {
    require __DIR__.'/vendor/autoload.php';

    $url = 'url';
    $api_key = 'api_key';
    $list_id = 'list_id';

    $client = new \GuzzleHttp\Client();

    $result = $client->request('POST', $url.'lists/'.$list_id.'/members', [
        'headers' => [
            'Authorization' => 'apikey '.$api_key,
            'json' => [
                'email_address' => $_POST['email'],
                'email_type'    => 'html',
                'status'        => 'subscribed'
            ]
        ],
        'verify' => false,
        'debug' => false
    ]);
}

Here's the error I'm getting:

'Undefined index: email' Where shall I define email? How to catch it from the form?

I tried to follow this example. However, my syntax is different. I shall add that the reason for my syntax is dictated by the fact that I'm trying to create a plugin for GRAV, also using Guzzle.

Body:
OK, I've finally got it sorted. I'm posting the answer in case someone else will be struggling with that one.

'headers' => [
            'Authorization' => 'apikey '.$api_key,
],
'json' => [
        'email_address' => $_POST['email'],
        'email_type'    => 'html',
        'status'        => 'subscribed'
]

Basically 'json' array should not be in the 'headers'. Also, removed 'debug' and 'verify'.


答:
jQuery will assign the event handler passed to on to all the elements that match the selector. Vanilla JS does not do this. document.querySelectorAll returns a NodeList and so you'll need to select the specific node you want and assign the event listeners to it. If you want to assign the event listener to all the nodes in the list, then you may iterate over the NodeList like so:

```<code>var nodes = document.querySelectorAll(".class-name");
for (var node in nodes) {
    node.addEventListener(event, handler);
}
</code>```

Title: With pure JavaScript, is there an easy way to attach an event listener to a class?

Body:
jQuery will assign the event handler passed to on to all the elements that match the selector. Vanilla JS does not do this. document.querySelectorAll returns a NodeList and so you'll need to select the specific node you want and assign the event listeners to it. If you want to assign the event listener to all the nodes in the list, then you may iterate over the NodeList like so:

var nodes = document.querySelectorAll(".class-name");
for (var node in nodes) {
    node.addEventListener(event, handler);
}


问:
Upload iOS app to AppStore (An error occurred uploading to the App Store.)
I can't upload new version of app to appstore after full OS update. Try install java version 9+ and 8+, doesn't work. In Application Loader I get this log:

```<code>java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.apple.transporter.launcher.Application.start(Application.java:206)
    at com.apple.transporter.launcher.Application.main(Application.java:519)
Caused by: java.lang.IllegalStateException: could not find needed OSGiFramework
    at com.apple.transporter.osgi.BootstrapHelper.setupClassLoader(BootstrapHelper.java:120)
    at com.apple.transporter.osgi.FelixOSGiBootstrapper.bootstrap(FelixOSGiBootstrapper.java:9)
</code>```

XCode 9.2, java version "1.8.0_151"

答:
Same error here. XCode(9.2) and java(9.0.1).

This command line solve my problem :

```<code>rm -R ~/.itmstransporter
</code>```

Regards

Body:
I can't upload new version of app to appstore after full OS update. Try install java version 9+ and 8+, doesn't work. In Application Loader I get this log:

java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.apple.transporter.launcher.Application.start(Application.java:206)
    at com.apple.transporter.launcher.Application.main(Application.java:519)
Caused by: java.lang.IllegalStateException: could not find needed OSGiFramework
    at com.apple.transporter.osgi.BootstrapHelper.setupClassLoader(BootstrapHelper.java:120)
    at com.apple.transporter.osgi.FelixOSGiBootstrapper.bootstrap(FelixOSGiBootstrapper.java:9)

XCode 9.2, java version "1.8.0_151"

Body:
Same error here. XCode(9.2) and java(9.0.1).

This command line solve my problem :

rm -R ~/.itmstransporter

Regards


问:
Emoji Encoding and Decoding erlang from list to binary

I want this string to be parsed for VOIP Notification for iOS to binary string:

```<code>"{\"data\":{\"text\":\"❤\"}}"
</code>```

I expected the data printed on the Erlang shell to be:

```<code><<"{\"data\":{\"text\":\"❤\"}}">>
</code>```

But when printed it shows:

```<code>{"data",[{"text",[10084,65039]}]}
</code>```

I tried the solution from Encoding emoji in Erlang but it just gives me a bit string of the emoji which is:

```<code>{<<"data">>,{[{<<"text">>,<<100,39,15,254>>}]}}
</code>```

How do I properly show it in Unicode in the Erlang shell?

答:
In the first example you provide it is properly encoded, but it is not properly displayed. When you define strings using double quotes the string is actually stored as a list of character codes. In the case of the heart emoji [10084,65039] are the character codes. The Erlang shell isn't printing out the emoji itself, but rather the values of the bytes that represent the emoji.

In the second case, a binary string, you shouldn't need to do any special encoding of the binary, but you will need to tell Erlang to treat it as a UTF8 string. You can do that by specifying /utf8 at the end before the closing >>:

```<code><<"{\"data\":{\"text\":\"❤\"}}"/utf8>>.
</code>```

If you want to see the emoji stored in strings and binaries like these displayed in the shell as actual emoji and not character codes, you will need to use the +pc option when starting the shell so it treats all unicode characters as printable characters:

```<code>erl +pc unicode
</code>```

Setting it to unicode will cause emoji printed in the shell like this:

http://erlang.org/doc/man/erl.html#id201195

Body:
I want this string to be parsed for VOIP Notification for iOS to binary string:

"{\"data\":{\"text\":\"❤\"}}"

I expected the data printed on the Erlang shell to be:

<<"{\"data\":{\"text\":\"❤\"}}">>

But when printed it shows:

{"data",[{"text",[10084,65039]}]}

I tried the solution from Encoding emoji in Erlang but it just gives me a bit string of the emoji which is:

{<<"data">>,{[{<<"text">>,<<100,39,15,254>>}]}}

How do I properly show it in Unicode in the Erlang shell?

Body:
In the first example you provide it is properly encoded, but it is not properly displayed. When you define strings using double quotes the string is actually stored as a list of character codes. In the case of the heart emoji [10084,65039] are the character codes. The Erlang shell isn't printing out the emoji itself, but rather the values of the bytes that represent the emoji.

In the second case, a binary string, you shouldn't need to do any special encoding of the binary, but you will need to tell Erlang to treat it as a UTF8 string. You can do that by specifying /utf8 at the end before the closing >>:

<<"{\"data\":{\"text\":\"❤\"}}"/utf8>>.

If you want to see the emoji stored in strings and binaries like these displayed in the shell as actual emoji and not character codes, you will need to use the +pc option when starting the shell so it treats all unicode characters as printable characters:

erl +pc unicode

Setting it to unicode will cause emoji printed in the shell like this:

http://erlang.org/doc/man/erl.html#id201195


问:
Memory Leak on the phonegap-plugin-barcodescanner for Windows Phone 8.1 devices
this issue is not new, I know and there are different threats around the Internet although I still have the same issue where the App crashes after tried a few scans.

Testing the App on:
Lumia 625 and 520

I have a cordova project with the following:
cordova 7.1.0
node 6.7.0
phonegap 7.0.1

After created the project I add the plugin:
cordova plugin add phonegap-plugin-barcodescanner@6.0.4 (6.0.4 seeems to be the more stable)

and then I add the platform:
cordova platform add windows

when I go and try my app, as soon as I try to scan a QR code, the phone's screen became green and crashes eventually :(

I have tried to apply the changes mentioned here:
https://github.com/phonegap/phonegap-plugin-barcodescanner/issues/55
but no luck.

This is the code:

```<code>function runBarCodeScanner(){
    $cordovaBarcodeScanner
        .scan()
        .then(barcodeScanComplete, barcodeScanError);
  }
</code>```

Any version of the barcodescanner above 6.0.4 will crash straight away although I was hoping the issue would have been fixed by then!

Any suggestions?

Please let me know if you need further details to help

答: I have solved the problem at the end. Using the knowledge shared under https://github.com/phonegap/phonegap-plugin-barcodescanner/issues/55 after a few attempts is seems like the scanner stopped crashing my app :)</p>

Body:
this issue is not new, I know and there are different threats around the Internet although I still have the same issue where the App crashes after tried a few scans.

Testing the App on:
Lumia 625 and 520

I have a cordova project with the following:
cordova 7.1.0
node 6.7.0
phonegap 7.0.1

After created the project I add the plugin:
cordova plugin add phonegap-plugin-barcodescanner@6.0.4 (6.0.4 seeems to be the more stable)

and then I add the platform:
cordova platform add windows

when I go and try my app, as soon as I try to scan a QR code, the phone's screen became green and crashes eventually :(

I have tried to apply the changes mentioned here:
https://github.com/phonegap/phonegap-plugin-barcodescanner/issues/55
but no luck.

This is the code:

function runBarCodeScanner(){
    $cordovaBarcodeScanner
        .scan()
        .then(barcodeScanComplete, barcodeScanError);
  }

Any version of the barcodescanner above 6.0.4 will crash straight away although I was hoping the issue would have been fixed by then!

Any suggestions?

Please let me know if you need further details to help


问:
Web Api 2 custom IHttpActionResult CORS. No 'Access-Control-Allow-Origin' header is present on the requested resource
I have a problem with CORS from my WEB API 2 to Angular application.
Everything is working fine till now and all the response headers are receiving the following:

```<code>Access-Control-Allow-Origin:*
Cache-Control:no-cache
Content-Length:24
Content-Type:application/json; charset=utf-8
Date:Mon, 13 Nov 2017 08:15:32 GMT
Expires:-1
Pragma:no-cache
Server:Microsoft-IIS/10.0
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?...
</code>```

Now I created a custom IHttpActionResult like this:

```<code>public class ZipFileActionResult : IHttpActionResult
{
    private const long BufferLength = 65536;
    public ZipFileActionResult(string file)
    {
        this.Filepath = file;
    }

    public string Filepath { get; private set; }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        HttpResponseMessage result = new HttpResponseMessage();

        var zipf = new FilesStream(this.Filepath);
        Action<Stream, HttpContent, TransportContext> writeToStream = zipf.WriteToStream;
        result.Content = new PushStreamContent(writeToStream, new MediaTypeHeaderValue("application/" + "zip"));

        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = "filename.zip"
        };

        return Task.FromResult(result);
    }

    private async void OnStreamConnected(Stream outputStream, HttpContent content, TransportContext context)
    {
        try
        {
            var buffer = new byte[BufferLength];

            using (var nypdVideo = File.Open(this.Filepath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                var videoLength = (int)nypdVideo.Length;
                var videoBytesRead = 1;

                while (videoLength > 0 && videoBytesRead > 0)
                {
                    videoBytesRead = nypdVideo.Read(buffer, 0, Math.Min(videoLength, buffer.Length));
                    await outputStream.WriteAsync(buffer, 0, videoBytesRead);
                    videoLength -= videoBytesRead;
                }
            }
        }
        catch (HttpException ex)
        {
            return;
        }
        finally
        {
            // Close output stream as we are done
            outputStream.Close();
        }
    }
}
</code>```

and I use this in my DownloadCOntroller like this:

```<code>    [HttpPost]
    [Route("PaperCuts")]
    public IHttpActionResult PaperCuts(List<SelectionObject> selections)
    {
        try
        {
                string sFileName = <filename> + ".zip";

                return new ZipFileActionResult(sFileName);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
</code>```

I'm receiving the following error when I call this function correctly:

No 'Access-Control-Allow-Origin' header is present on the requested resource.

And I'm receiving this as response header:

```<code>HTTP/1.1 500 Internal Server Error
Cache-Control: private
Transfer-Encoding: chunked
Content-Type: text/html; charset=utf-8
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?RDpcUHJvamVjdHNcS25pcHNlbGtyYW50XEtuaXBzZWxrcmFudEFQSVxLbmlwc2Vsa3JhbnRBUElcYXBpXGRvd25sb2FkXFBhcGVyQ3V0cw==?=
X-Powered-By: ASP.NET
Date: Mon, 13 Nov 2017 08:35:33 GMT
</code>```

I also have this stated in my WebApiConfig.cs (It works for all my other requests except for this one).

```<code>        var corsAttr = new EnableCorsAttribute("*", "*", "*");
        config.EnableCors(corsAttr);
</code>```

So the problem is that the Access-Control-Allow-Origin header etc are not same as in ALL the other requests. So how is this possible and how can I fix this?
I hope I provided enough information for my question.

Kind regards,

D.

答:
I found the answer and got reminded by @ICantSeeSharp

I added following code in my global exception handler:

```<code>public override bool ShouldHandle(ExceptionHandlerContext context)
{
    return true;
}
</code>```

Body:
I have a problem with CORS from my WEB API 2 to Angular application.
Everything is working fine till now and all the response headers are receiving the following:

Access-Control-Allow-Origin:*
Cache-Control:no-cache
Content-Length:24
Content-Type:application/json; charset=utf-8
Date:Mon, 13 Nov 2017 08:15:32 GMT
Expires:-1
Pragma:no-cache
Server:Microsoft-IIS/10.0
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?...

Now I created a custom IHttpActionResult like this:

public class ZipFileActionResult : IHttpActionResult
{
    private const long BufferLength = 65536;
    public ZipFileActionResult(string file)
    {
        this.Filepath = file;
    }

    public string Filepath { get; private set; }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        HttpResponseMessage result = new HttpResponseMessage();

        var zipf = new FilesStream(this.Filepath);
        Action<Stream, HttpContent, TransportContext> writeToStream = zipf.WriteToStream;
        result.Content = new PushStreamContent(writeToStream, new MediaTypeHeaderValue("application/" + "zip"));

        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = "filename.zip"
        };

        return Task.FromResult(result);
    }

    private async void OnStreamConnected(Stream outputStream, HttpContent content, TransportContext context)
    {
        try
        {
            var buffer = new byte[BufferLength];

            using (var nypdVideo = File.Open(this.Filepath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                var videoLength = (int)nypdVideo.Length;
                var videoBytesRead = 1;

                while (videoLength > 0 && videoBytesRead > 0)
                {
                    videoBytesRead = nypdVideo.Read(buffer, 0, Math.Min(videoLength, buffer.Length));
                    await outputStream.WriteAsync(buffer, 0, videoBytesRead);
                    videoLength -= videoBytesRead;
                }
            }
        }
        catch (HttpException ex)
        {
            return;
        }
        finally
        {
            // Close output stream as we are done
            outputStream.Close();
        }
    }
}

and I use this in my DownloadCOntroller like this:

    [HttpPost]
    [Route("PaperCuts")]
    public IHttpActionResult PaperCuts(List<SelectionObject> selections)
    {
        try
        {
                string sFileName = <filename> + ".zip";

                return new ZipFileActionResult(sFileName);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

I'm receiving the following error when I call this function correctly:

No 'Access-Control-Allow-Origin' header is present on the requested resource.

And I'm receiving this as response header:

HTTP/1.1 500 Internal Server Error
Cache-Control: private
Transfer-Encoding: chunked
Content-Type: text/html; charset=utf-8
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?RDpcUHJvamVjdHNcS25pcHNlbGtyYW50XEtuaXBzZWxrcmFudEFQSVxLbmlwc2Vsa3JhbnRBUElcYXBpXGRvd25sb2FkXFBhcGVyQ3V0cw==?=
X-Powered-By: ASP.NET
Date: Mon, 13 Nov 2017 08:35:33 GMT

I also have this stated in my WebApiConfig.cs (It works for all my other requests except for this one).

        var corsAttr = new EnableCorsAttribute("*", "*", "*");
        config.EnableCors(corsAttr);

So the problem is that the Access-Control-Allow-Origin header etc are not same as in ALL the other requests. So how is this possible and how can I fix this?
I hope I provided enough information for my question.

Kind regards,

D.

Body:
I found the answer and got reminded by @ICantSeeSharp

I added following code in my global exception handler:

public override bool ShouldHandle(ExceptionHandlerContext context)
{
    return true;
}


问:
Automate Facebook Signup not able to select female radio button
I am trying to create new account on FB but I am not able to select radio buttons and signup button

```<code>public void f() {
      driver.findElement(By.id("u_0_g")).sendKeys("Anamika");
      driver.findElement(By.id("u_0_i")).sendKeys("Singh");
      driver.findElement(By.id("u_0_l")).sendKeys("9718257931");
      driver.findElement(By.id("u_0_s")).sendKeys("P@ssw0rd1");
      WebElement add=driver.findElement(By.id("day"));
      Select dropDown=new Select(add);

      dropDown.selectByIndex(6);
      add=driver.findElement(By.id("month"));
      dropDown=new Select(add);
      dropDown.selectByIndex(4);
      add=driver.findElement(By.id("year"));
      dropDown=new Select(add);
      dropDown.selectByIndex(6);

      driver.findElement(By.cssSelector("[id=u_0_j]")).click();
      driver.findElement(By.cssSelector("[id=u_0_n]")).click();
      //WebElement lstitem=driver.findElement(By.id("u_0_6"));
      //driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
      //if(elem.isSelected())

      //driver.findElement(By.id("u_0_10")).click();
      //else
          //System.out.println("Button not selected");
  }
  @BeforeMethod
  public void beforeMethod() {
      driver=new FirefoxDriver();
            driver.get("https://www.facebook.com/");//get to hit the URL

  }

  @AfterMethod
  public void afterMethod() {
      //driver.quit();
  }

}
</code>```

Getting Following error:

org.openqa.selenium.ElementNotInteractableException:

答:
You can try CSS selectors:

Female radio button:

```<code>input[type='radio'][value='1']
</code>```

Male radio button:

```<code>input[type='radio'][value='2']
</code>```

I already have automated this using Selenium Page Object Model, you can find this on github: https://github.com/prat3ik/Facebook_SignUp_Selenium

Path: /src/test/java/

Body:
I am trying to create new account on FB but I am not able to select radio buttons and signup button

public void f() {
      driver.findElement(By.id("u_0_g")).sendKeys("Anamika");
      driver.findElement(By.id("u_0_i")).sendKeys("Singh");
      driver.findElement(By.id("u_0_l")).sendKeys("9718257931");
      driver.findElement(By.id("u_0_s")).sendKeys("P@ssw0rd1");
      WebElement add=driver.findElement(By.id("day"));
      Select dropDown=new Select(add);

      dropDown.selectByIndex(6);
      add=driver.findElement(By.id("month"));
      dropDown=new Select(add);
      dropDown.selectByIndex(4);
      add=driver.findElement(By.id("year"));
      dropDown=new Select(add);
      dropDown.selectByIndex(6);

      driver.findElement(By.cssSelector("[id=u_0_j]")).click();
      driver.findElement(By.cssSelector("[id=u_0_n]")).click();
      //WebElement lstitem=driver.findElement(By.id("u_0_6"));
      //driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
      //if(elem.isSelected())

      //driver.findElement(By.id("u_0_10")).click();
      //else
          //System.out.println("Button not selected");
  }
  @BeforeMethod
  public void beforeMethod() {
      driver=new FirefoxDriver();
            driver.get("https://www.facebook.com/");//get to hit the URL

  }

  @AfterMethod
  public void afterMethod() {
      //driver.quit();
  }

}

Getting Following error:

org.openqa.selenium.ElementNotInteractableException:

Body:
You can try CSS selectors:

Female radio button:

input[type='radio'][value='1']

Male radio button:

input[type='radio'][value='2']

I already have automated this using Selenium Page Object Model, you can find this on github: https://github.com/prat3ik/Facebook_SignUp_Selenium

Path: /src/test/java/


问:
CSS Flexbox - spacing between elements when using flex wrap and flex grow properties
I am using CSS flexbox for grid based navigation which has 3 columns in row and 'n' no of rows in the grid. The width of the grid-child calculated based on the parent container width (i.e. 100%).

I set margin-right:10px; and margin-bottom:10px; for each 3rd of the grid-child i had set 0px for margin-rightto force the grid-child at the right edge of the parent container.

Everything works fine if a the column equally divided by 3. (i.e. 3 columns per row).

Here the problem is, if last row has only 2 columns then we have 10px space between grid and the grid-child.

Is there any possible solution to get rid of the remaining space.

Please find the below codepen link for better understanding:
https://codepen.io/yesvin/pen/xXwBqa

HTML code block:

```<code><div class="menu-wrapper">
    <div class="menu">
      <div class="menu-icon">
        <img src="http://via.placeholder.com/80x80"/>
      </div>
      <div class="menu-name">
        <p>Txt</p>
      </div>
    </div>
    <div class="menu">
      <div class="menu-icon">
        <img src="http://via.placeholder.com/80x80"/>
      </div>
      <div class="menu-name">
        <p>Txt</p>
      </div>
    </div>
    <div class="menu">
      <div class="menu-icon">
        <img src="http://via.placeholder.com/80x80"/>
      </div>
      <div class="menu-name">
        <p>Txt</p>
      </div>
    </div>
    <div class="menu">
      <div class="menu-icon">
        <img src="http://via.placeholder.com/80x80"/>
      </div>
      <div class="menu-name">
        <p>Txt</p>
      </div>
    </div>
    <div class="menu">
      <div class="menu-icon">
        <img src="http://via.placeholder.com/80x80"/>
      </div>
      <div class="menu-name">
        <p>Txt</p>
      </div>
    </div>
    <div class="menu">
      <div class="menu-icon">
        <img src="http://via.placeholder.com/80x80"/>
      </div>
      <div class="menu-name">
       <p>Txt</p>
      </div>
    </div>
    <div class="menu">
      <div class="menu-icon">
        <img src="http://via.placeholder.com/80x80"/>
      </div>
      <div class="menu-name">
        <p>Txt</p>
      </div>
    </div>
    <div class="menu">
      <div class="menu-icon">
        <img src="http://via.placeholder.com/80x80"/>
      </div>
      <div class="menu-name">
        <p>Txt</p>
      </div>
    </div>
</div>
</code>```

CSS code block:

```<code>.menu-wrapper {
  width:100%;
  height:100%;
  display: flex;
  flex-wrap:wrap;
  margin:0px;

  .menu {
    display: inline-block;
    border:solid 1px #ccc;
    margin:0 10px 10px 0;
    flex-grow: 1;
    width: calc(33% - 10px);
  }
  .menu:nth-child(3n) {
    margin-right:0;
  }
  .menu-icon {
    text-align:center;
  }
  .menu-name {
    width:80%;
    margin:0 auto;
    text-align:center;
  }
}
</code>```

Problem:

Required result

Thanks in advance.

NOTE:
It is possible to achieve the similar effect by split the each row in a separate flexbox styling. But, I don't want that, because, the 'n' no. of menus are dynamically appending inside the menu-wrapper.

答:
Simply add margin-right:0 to the last child to remove this space :

```<code>.menu-wrapper .menu:last-child {
    margin-right: 0;
}
</code>```

This will work in any case :

if you already have 3 it's already 0

if you have one or two it will remove the undesired space.

Full code with 1 items in the last row :

.menu-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  flex-wrap: wrap;
  margin: 0px;
}

.menu-wrapper .menu {
  display: inline-block;
  border: solid 1px #ccc;
  margin: 0 10px 10px 0;
  flex-grow: 1;
  width: calc(33% - 10px);
}

.menu-wrapper .menu:nth-child(3n),
.menu-wrapper .menu:last-child {
  margin-right: 0;
}

.menu-wrapper .menu-icon {
  text-align: center;
}

.menu-wrapper .menu-name {
  width: 80%;
  margin: 0 auto;
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="menu-wrapper">
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>

</div></code>```

Full code with 2 items in the last row :

.menu-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  flex-wrap: wrap;
  margin: 0px;
}

.menu-wrapper .menu {
  display: inline-block;
  border: solid 1px #ccc;
  margin: 0 10px 10px 0;
  flex-grow: 1;
  width: calc(33% - 10px);
}

.menu-wrapper .menu:nth-child(3n),
.menu-wrapper .menu:last-child {
  margin-right: 0;
}

.menu-wrapper .menu-icon {
  text-align: center;
}

.menu-wrapper .menu-name {
  width: 80%;
  margin: 0 auto;
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="menu-wrapper">
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
   <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>

</div></code>```

Full code with 3 items in the last row :

.menu-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  flex-wrap: wrap;
  margin: 0px;
}

.menu-wrapper .menu {
  display: inline-block;
  border: solid 1px #ccc;
  margin: 0 10px 10px 0;
  flex-grow: 1;
  width: calc(33% - 10px);
}

.menu-wrapper .menu:nth-child(3n),
.menu-wrapper .menu:last-child {
  margin-right: 0;
}

.menu-wrapper .menu-icon {
  text-align: center;
}

.menu-wrapper .menu-name {
  width: 80%;
  margin: 0 auto;
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="menu-wrapper">
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
   <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>

</div></code>```

Body:
I am using CSS flexbox for grid based navigation which has 3 columns in row and 'n' no of rows in the grid. The width of the grid-child calculated based on the parent container width (i.e. 100%).

I set margin-right:10px; and margin-bottom:10px; for each 3rd of the grid-child i had set 0px for margin-rightto force the grid-child at the right edge of the parent container.

Everything works fine if a the column equally divided by 3. (i.e. 3 columns per row).

Here the problem is, if last row has only 2 columns then we have 10px space between grid and the grid-child.

Is there any possible solution to get rid of the remaining space.

Please find the below codepen link for better understanding:
https://codepen.io/yesvin/pen/xXwBqa

HTML code block:

Txt

Txt

Txt

Txt

Txt

Txt

Txt

Txt

CSS code block:

.menu-wrapper {
  width:100%;
  height:100%;
  display: flex;
  flex-wrap:wrap;
  margin:0px;

  .menu {
    display: inline-block;
    border:solid 1px #ccc;
    margin:0 10px 10px 0;
    flex-grow: 1;
    width: calc(33% - 10px);
  }
  .menu:nth-child(3n) {
    margin-right:0;
  }
  .menu-icon {
    text-align:center;
  }
  .menu-name {
    width:80%;
    margin:0 auto;
    text-align:center;
  }
}

Problem:

Required result

Thanks in advance.

NOTE:
It is possible to achieve the similar effect by split the each row in a separate flexbox styling. But, I don't want that, because, the 'n' no. of menus are dynamically appending inside the menu-wrapper.

Body:
Simply add margin-right:0 to the last child to remove this space :

.menu-wrapper .menu:last-child {
    margin-right: 0;
}

This will work in any case :

if you already have 3 it's already 0

if you have one or two it will remove the undesired space.

Full code with 1 items in the last row :

.menu-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  flex-wrap: wrap;
  margin: 0px;
}

.menu-wrapper .menu {
  display: inline-block;
  border: solid 1px #ccc;
  margin: 0 10px 10px 0;
  flex-grow: 1;
  width: calc(33% - 10px);
}

.menu-wrapper .menu:nth-child(3n),
.menu-wrapper .menu:last-child {
  margin-right: 0;
}

.menu-wrapper .menu-icon {
  text-align: center;
}

.menu-wrapper .menu-name {
  width: 80%;
  margin: 0 auto;
  text-align: center;
}

<div class="menu-wrapper">
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>

</div>

Full code with 2 items in the last row :

.menu-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  flex-wrap: wrap;
  margin: 0px;
}

.menu-wrapper .menu {
  display: inline-block;
  border: solid 1px #ccc;
  margin: 0 10px 10px 0;
  flex-grow: 1;
  width: calc(33% - 10px);
}

.menu-wrapper .menu:nth-child(3n),
.menu-wrapper .menu:last-child {
  margin-right: 0;
}

.menu-wrapper .menu-icon {
  text-align: center;
}

.menu-wrapper .menu-name {
  width: 80%;
  margin: 0 auto;
  text-align: center;
}

<div class="menu-wrapper">
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
   <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>

</div>

Full code with 3 items in the last row :

.menu-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  flex-wrap: wrap;
  margin: 0px;
}

.menu-wrapper .menu {
  display: inline-block;
  border: solid 1px #ccc;
  margin: 0 10px 10px 0;
  flex-grow: 1;
  width: calc(33% - 10px);
}

.menu-wrapper .menu:nth-child(3n),
.menu-wrapper .menu:last-child {
  margin-right: 0;
}

.menu-wrapper .menu-icon {
  text-align: center;
}

.menu-wrapper .menu-name {
  width: 80%;
  margin: 0 auto;
  text-align: center;
}

<div class="menu-wrapper">
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
   <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>
  <div class="menu">
    <div class="menu-icon">
      <img src="http://via.placeholder.com/80x80" />
    </div>
    <div class="menu-name">
      <p>Txt</p>
    </div>
  </div>

</div>


问:
Is good idea to use gerrit to host the git repository instead of gitolite or gitosis?
Originally I try to use gitosis to manage the git repositories in the company, and later notice gitolite is kind of enhancement of gitosis.

And also I heard gerrit could be used for the same purpose, but from the description, gerrit is mainly used for code review.

So which is the best way for setting up git server

using gitolite (for git repo) AND gerrit (for code review) together

using gerrit ONLY to manage git repository and codereview

Can you give some suggestion ?

BTW: http://gitorious.org/ is considered in the future

答:
If you're going to use gerrit at all, you might as well use it for hosting as well as code review -- the workflow is easier that way, as gerrit will manage merging your reviewed code into its repository, and that's what you want to be publishing -- if you host elsewhere, you're going to have to either set up a method for automatically pulling from gerrit or you're going to have a way for your developers to bypass the code review by pushing their changes straight to the hosted repositories and ignoring gerrit altogether.

Recent versions of gerrit can integrate gitweb, giving you the nice web interface to browse with, but protected by the ACLs you've set up.


问:
Merge two datasets in Python
I have two sets of x-y data, whose x values should be merged. To illustrate, the first set looks something like this:

```<code>0.5;3.4
0.8;3.8
0.9;1.2
1.3;1.1
1.9;2.3
</code>```

And the second set like this:

```<code>0.3;-0.2
0.8;-0.9
1.0;0.1
1.5;1.2
1.6;6.3
</code>```

The data is in two separate csv files. I would like to merge both files into one, so that the x values are in order, and the y values appear in two columns with their (linearly) interpolated values (y1 and y2) completed. The second column contains the y values of the first dataset (plus interpolated values) and the third column the y values of the second dataset.

```<code>0.3;y1;-0.2
0.5;3.4;y2
0.8;3.8;-0.9
0.9;1.2;y2
1.0;y1;0.1
1.3;1.1;y2
1.5;y1;1.2
1.6;y1;6.3
1.9;2.3;y2
</code>```

My only idea so far would be to read the data into numpy arrays, join them together, sort the values and calculate the average of preceding and following values, in case the value is empty.

Is there a more elegant way to do this in Python?

Edit: Here is my attempt. It works and delivers the result I imagined, although the script is quite long.

```<code>#-*- coding: utf-8 -*-

import numpy as np
from matplotlib import pyplot as plt
from scipy.interpolate import interp1d
import csv

# Read data files and turn them into numpy array for further processing
def read_datafile(file_name):
    data = np.loadtxt(file_name, delimiter=";")
    return data

data1 = read_datafile("testcsv1.csv")
data2 = read_datafile("testcsv2.csv")

# Add empty column at the appropriate position
emptycol1 = np.empty((len(data1), 3))
emptycol1[:] = np.nan
emptycol2 = np.empty((len(data2), 3))
emptycol2[:] = np.nan
emptycol1[:,:-1] = data1
emptycol2[:,[0, 2]] = data2

# Merge and sort the data sets. Create empty array to add final results
merged_temp = np.concatenate((emptycol1, emptycol2))
merged_temp = np.array(sorted(merged_temp, key = lambda x: float(x[0])))
merged = np.empty((1, 3))

# Check for entries where the x values already match. Merge those into one row
i = 0
while i < len(merged_temp)-1:
    if merged_temp[i, 0] == merged_temp[i+1, 0]:
        newrow = np.array([merged_temp[i, 0], merged_temp[i, 1], merged_temp[i+1, 2]])
        merged = np.vstack((merged, newrow))
        i += 2
    else:
        newrow = np.array([merged_temp[i, 0], merged_temp[i, 1], merged_temp[i, 2]])
        merged = np.vstack((merged, newrow))
        i += 1

# Check for so far undefined values (gaps in the data). Interpolate between them (linearly)
for i in range(len(merged)-1):
    # First y column
    if np.isnan(merged[i, 1]) == True:
        # If only one value is missing (maybe not necessary to separate this case)
        if (np.isnan(merged[i-1, 1]) == False) and (np.isnan(merged[i+1, 1]) == False):
            merged[i, 1] = (merged[i-1, 1] + merged[i+1, 1])/2
        # If two or more values are missing
        elif np.isnan(merged[i, 1]) == True:
            l = 0
            while (np.isnan(merged[i+l, 1]) == True) and (i+l != len(merged)-1):
                l += 1
            x1 = np.array([i-1, i+l])                       # endpoints
            x = np.linspace(i, i+l-1, l, endpoint=True)     # missing points
            y = np.array([merged[i-1, 1], merged[i+l, 1]])  # values at endpoints
            f = interp1d(x1, y)                             # linear interpolation
            for k in x:
                merged[k, 1] = f(k)
    # Second y column
    if np.isnan(merged[i, 2]) == True:
        # If only one value is missing
        if (np.isnan(merged[i-1, 2]) == False) and (np.isnan(merged[i+1, 2]) == False):
            merged[i, 2] = (merged[i-1, 2] + merged[i+1, 2])/2
        # If two or more values are missing
        elif np.isnan(merged[i, 2]) == True:
            l = 0
            while (np.isnan(merged[i+l, 2]) == True) and (i+l != len(merged)-1):
                l += 1
            x1 = np.array([i-1, i+l])                       # endpoints
            x = np.linspace(i, i+l-1, l, endpoint=True)     # missing points
            y = np.array([merged[i-1, 2], merged[i+l, 2]])  # values at endpoints
            f = interp1d(x1, y)                             # linear interpolation
            for k in x:
                merged[k, 2] = f(k)

# Remove lines which still have "nan" values (beginning and end). This could be prevented by an extrapolation
merged = merged[~np.isnan(merged).any(axis=1)]
merged = np.delete(merged, (0), axis=0)

# Write table to new csv file in the same directory
with open("testcsv_merged.csv", "w") as mergedfile:
    writer = csv.writer(mergedfile)
    [writer.writerow(r) for r in merged]
</code>```

Title: Merge two datasets in Python

Body:
I have two sets of x-y data, whose x values should be merged. To illustrate, the first set looks something like this:

0.5;3.4
0.8;3.8
0.9;1.2
1.3;1.1
1.9;2.3

And the second set like this:

0.3;-0.2
0.8;-0.9
1.0;0.1
1.5;1.2
1.6;6.3

The data is in two separate csv files. I would like to merge both files into one, so that the x values are in order, and the y values appear in two columns with their (linearly) interpolated values (y1 and y2) completed. The second column contains the y values of the first dataset (plus interpolated values) and the third column the y values of the second dataset.

0.3;y1;-0.2
0.5;3.4;y2
0.8;3.8;-0.9
0.9;1.2;y2
1.0;y1;0.1
1.3;1.1;y2
1.5;y1;1.2
1.6;y1;6.3
1.9;2.3;y2

My only idea so far would be to read the data into numpy arrays, join them together, sort the values and calculate the average of preceding and following values, in case the value is empty.

Is there a more elegant way to do this in Python?

Edit: Here is my attempt. It works and delivers the result I imagined, although the script is quite long.

#-*- coding: utf-8 -*-

import numpy as np
from matplotlib import pyplot as plt
from scipy.interpolate import interp1d
import csv

# Read data files and turn them into numpy array for further processing
def read_datafile(file_name):
    data = np.loadtxt(file_name, delimiter=";")
    return data

data1 = read_datafile("testcsv1.csv")
data2 = read_datafile("testcsv2.csv")

# Add empty column at the appropriate position
emptycol1 = np.empty((len(data1), 3))
emptycol1[:] = np.nan
emptycol2 = np.empty((len(data2), 3))
emptycol2[:] = np.nan
emptycol1[:,:-1] = data1
emptycol2[:,[0, 2]] = data2

# Merge and sort the data sets. Create empty array to add final results
merged_temp = np.concatenate((emptycol1, emptycol2))
merged_temp = np.array(sorted(merged_temp, key = lambda x: float(x[0])))
merged = np.empty((1, 3))

# Check for entries where the x values already match. Merge those into one row
i = 0
while i < len(merged_temp)-1:
    if merged_temp[i, 0] == merged_temp[i+1, 0]:
        newrow = np.array([merged_temp[i, 0], merged_temp[i, 1], merged_temp[i+1, 2]])
        merged = np.vstack((merged, newrow))
        i += 2
    else:
        newrow = np.array([merged_temp[i, 0], merged_temp[i, 1], merged_temp[i, 2]])
        merged = np.vstack((merged, newrow))
        i += 1

# Check for so far undefined values (gaps in the data). Interpolate between them (linearly)
for i in range(len(merged)-1):
    # First y column
    if np.isnan(merged[i, 1]) == True:
        # If only one value is missing (maybe not necessary to separate this case)
        if (np.isnan(merged[i-1, 1]) == False) and (np.isnan(merged[i+1, 1]) == False):
            merged[i, 1] = (merged[i-1, 1] + merged[i+1, 1])/2
        # If two or more values are missing
        elif np.isnan(merged[i, 1]) == True:
            l = 0
            while (np.isnan(merged[i+l, 1]) == True) and (i+l != len(merged)-1):
                l += 1
            x1 = np.array([i-1, i+l])                       # endpoints
            x = np.linspace(i, i+l-1, l, endpoint=True)     # missing points
            y = np.array([merged[i-1, 1], merged[i+l, 1]])  # values at endpoints
            f = interp1d(x1, y)                             # linear interpolation
            for k in x:
                merged[k, 1] = f(k)
    # Second y column
    if np.isnan(merged[i, 2]) == True:
        # If only one value is missing
        if (np.isnan(merged[i-1, 2]) == False) and (np.isnan(merged[i+1, 2]) == False):
            merged[i, 2] = (merged[i-1, 2] + merged[i+1, 2])/2
        # If two or more values are missing
        elif np.isnan(merged[i, 2]) == True:
            l = 0
            while (np.isnan(merged[i+l, 2]) == True) and (i+l != len(merged)-1):
                l += 1
            x1 = np.array([i-1, i+l])                       # endpoints
            x = np.linspace(i, i+l-1, l, endpoint=True)     # missing points
            y = np.array([merged[i-1, 2], merged[i+l, 2]])  # values at endpoints
            f = interp1d(x1, y)                             # linear interpolation
            for k in x:
                merged[k, 2] = f(k)

# Remove lines which still have "nan" values (beginning and end). This could be prevented by an extrapolation
merged = merged[~np.isnan(merged).any(axis=1)]
merged = np.delete(merged, (0), axis=0)

# Write table to new csv file in the same directory
with open("testcsv_merged.csv", "w") as mergedfile:
    writer = csv.writer(mergedfile)
    [writer.writerow(r) for r in merged]

Body:
A one liner : dfi = pd.merge(df1,df2,'outer',0).set_index(0).sort_index().interpolate()

In [383]: dfi
Out[383]:
      1_x   1_y
0
0.3   NaN -0.20
0.5  3.40 -0.55
0.8  3.80 -0.90
0.9  1.20 -0.40
1.0  1.15  0.10
1.3  1.10  0.65
1.5  1.50  1.20
1.6  1.90  6.30
1.9  2.30  6.30

A complete pandas version + numpy interpolate for better tuning at the edges :

#df1 = pd.read_clipboard(header=None,sep=';')
#df2 = pd.read_clipboard(header=None,sep=';')

import pylab as pl

df = pd.merge(df1,df2,'outer',0).sort_values(0)
df['y1']=scipy.interpolate.interp1d(*df1.values.T,fill_value='extrapolate')(df[0])
df['y2']=scipy.interpolate.interp1d(*df2.values.T,fill_value='extrapolate')(df[0])

ax=pl.gca()
df1.set_index(0).plot(lw=0,marker='o',ax=ax)
df2.set_index(0).plot(lw=0,marker='o',ax=ax)
df.set_index(0).loc[:,['y1','y2']].plot(ax=ax)
pl.show()

plots :

data :

In [344]: df1
Out[344]:
     0    1
0  0.5  3.4
1  0.8  3.8
2  0.9  1.2
3  1.3  1.1
4  1.9  2.3

In [345]: df2
Out[345]:
     0    1
0  0.3 -0.2
1  0.8 -0.9
2  1.0  0.1
3  1.5  1.2
4  1.6  6.3

In [346]: df
Out[346]:
     0  1_x  1_y         y1         y2
5  0.3  NaN -0.2 -20.713281  -0.200000
0  0.5  3.4  NaN   3.400000  -3.021563
1  0.8  3.8 -0.9   3.800000  -0.900000
2  0.9  1.2  NaN   1.200000  -0.092830
6  1.0  NaN  0.1  -0.265527   0.100000
3  1.3  1.1  NaN   1.100000  -1.960323
7  1.5  NaN  1.2   3.760937   1.200000
8  1.6  NaN  6.3   4.701230   6.300000
4  1.9  2.3  NaN   2.300000  44.318059


问:
SqlBulkCopy and SQL Server trigger Issues
I have following code in my application. I use SqlBulkCopy to upload Excel data into a SQL Server table. Now, I have a trigger on that table. I have changed my existing code like this but I am getting an error.

The error is

Argument 1: cannot convert from 'System.Data.SqlClient.SqlConnection' to 'string'

I changed the code as

```<code>oSqlBulk = new SqlBulkCopy("cn", SqlBulkCopyOptions.FireTriggers);
</code>```

Then I am getting an error

Format of the initialization string does not conform to specification starting at index 0.

Please check my code:

```<code>public static string ExecuteBulkCopy(string connectionString, string TableName, string Paths)
{
    SqlBulkCopy oSqlBulk = null;
    string error = null;

    OleDbConnection myExcelConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; " +
                       "Data Source=" + Paths +
                       ";Extended Properties=Excel 12.0;");

    try
    {
        myExcelConn.Open();

        // GET DATA FROM EXCEL SHEET.
        OleDbCommand objOleDB = new OleDbCommand("SELECT *FROM [Sheet1$]", myExcelConn);

        // READ THE DATA EXTRACTED FROM THE EXCEL FILE.
        OleDbDataReader objBulkReader = null;
        objBulkReader = objOleDB.ExecuteReader();

        using (SqlConnection cn = new SqlConnection(connectionString))
        {
            // cn.Open();
            oSqlBulk = new SqlBulkCopy(cn,SqlBulkCopyOptions.FireTriggers);

            oSqlBulk.DestinationTableName = TableName; // TABLE NAME.
            oSqlBulk.WriteToServer(objBulkReader);
            // return 1;

            //call the overload that takes a connection in place of the connection string
            // return ExecuteNonQuery(cn, commandType, commandText, commandParameters);
        }
    }
    catch (Exception ex)
    {
        error = ex.Message;
    }
    finally
    {
        oSqlBulk.Close();
        oSqlBulk = null;
        myExcelConn.Close();
        myExcelConn = null;
    }

    return error;
}
</code>```

答:
I have done following changes.It works now</p>

```<code> using (SqlConnection cn = new SqlConnection(connectionString))
                {

                    cn.Open();
                    oSqlBulk = new SqlBulkCopy(connectionString,SqlBulkCopyOptions.FireTriggers);
</code>```

Body:
I have following code in my application. I use SqlBulkCopy to upload Excel data into a SQL Server table. Now, I have a trigger on that table. I have changed my existing code like this but I am getting an error.

The error is

Argument 1: cannot convert from 'System.Data.SqlClient.SqlConnection' to 'string'

I changed the code as

oSqlBulk = new SqlBulkCopy("cn", SqlBulkCopyOptions.FireTriggers);

Then I am getting an error

Format of the initialization string does not conform to specification starting at index 0.

Please check my code:

public static string ExecuteBulkCopy(string connectionString, string TableName, string Paths)
{
    SqlBulkCopy oSqlBulk = null;
    string error = null;

    OleDbConnection myExcelConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; " +
                       "Data Source=" + Paths +
                       ";Extended Properties=Excel 12.0;");

    try
    {
        myExcelConn.Open();

        // GET DATA FROM EXCEL SHEET.
        OleDbCommand objOleDB = new OleDbCommand("SELECT *FROM [Sheet1$]", myExcelConn);

        // READ THE DATA EXTRACTED FROM THE EXCEL FILE.
        OleDbDataReader objBulkReader = null;
        objBulkReader = objOleDB.ExecuteReader();

        using (SqlConnection cn = new SqlConnection(connectionString))
        {
            // cn.Open();
            oSqlBulk = new SqlBulkCopy(cn,SqlBulkCopyOptions.FireTriggers);

            oSqlBulk.DestinationTableName = TableName; // TABLE NAME.
            oSqlBulk.WriteToServer(objBulkReader);
            // return 1;

            //call the overload that takes a connection in place of the connection string
            // return ExecuteNonQuery(cn, commandType, commandText, commandParameters);
        }
    }
    catch (Exception ex)
    {
        error = ex.Message;
    }
    finally
    {
        oSqlBulk.Close();
        oSqlBulk = null;
        myExcelConn.Close();
        myExcelConn = null;
    }

    return error;
}

Body:
I have done following changes.It works now

 using (SqlConnection cn = new SqlConnection(connectionString))
                {

                    cn.Open();
                    oSqlBulk = new SqlBulkCopy(connectionString,SqlBulkCopyOptions.FireTriggers);


问:
How can i pass parameter to this method
This is the method:

```<code>getUsersList(ref List<RealBioSDKUser> userList,
             int groupId = -1,
             [DateTimeConstant(0), Optional] DateTime fromDate)
</code>```

When I pass the parameters like this :

```<code>List<RealBioSDKUser> tempUserList=new List<RealBioSDKUser>();
BioClient.getUsersList(ref tempUserList,0, "1900-01-01");
</code>```

is shows this error:

the best overloaded method match for collections.generic.list like this.

答:
When invoking, provide DateTime (i.e. new DateTime(1900, 1, 1)) instance, not String ("1900-01-01") one:

```<code>getUsersList(ref List<RealBioSDKUser> userList,
             int groupId = -1,
            [DateTimeConstant(0), Optional] DateTime fromDate) // <- DateTime

...

List<RealBioSDKUser> tempUserList = new List<RealBioSDKUser>();

BioClient.getUsersList(ref tempUserList, 0, new DateTime(1900, 1, 1)); // <- DateTime
</code>```

Title: How can i pass parameter to this method

Body:
This is the method:

getUsersList(ref List<RealBioSDKUser> userList,
             int groupId = -1,
             [DateTimeConstant(0), Optional] DateTime fromDate)

When I pass the parameters like this :

List<RealBioSDKUser> tempUserList=new List<RealBioSDKUser>();
BioClient.getUsersList(ref tempUserList,0, "1900-01-01");

is shows this error:

the best overloaded method match for collections.generic.list like this.

Body:
When invoking, provide DateTime (i.e. new DateTime(1900, 1, 1)) instance, not String ("1900-01-01") one:

getUsersList(ref List<RealBioSDKUser> userList,
             int groupId = -1,
            [DateTimeConstant(0), Optional] DateTime fromDate) // <- DateTime

...

List<RealBioSDKUser> tempUserList = new List<RealBioSDKUser>();

BioClient.getUsersList(ref tempUserList, 0, new DateTime(1900, 1, 1)); // <- DateTime


问:
cxGrid new record on last field Enter
I'm struggling to make a TcxGrid to append a new record whenever the user presses Enter key on last field of the current record, however I didn't find any property that might help me achieve this.

I tried setting the OnKeyDown event of the grid view(TcxGridDBTableView), with the following code

```<code>if Key = VK_RETURN then
  if PaymentViewBetragNetto.Focused then
    PaymentView.DataController.AppendRecord;
</code>```

however the code is not executed for some reason...

Any idea on how to append record on last field OnEnter event would be highly appreciated.

Thank you.

答:
It seems that the way to solve this is to set the OnEditKeyDown/Up/Press of the grid view in order to handle this type of functionality, therefore:</p>

```<code>procedure XXX.PaymentViewEditKeyUp(Sender: TcxCustomGridTableView;
  AItem: TcxCustomGridTableItem; AEdit: TcxCustomEdit; var Key: Word;
  Shift: TShiftState);
begin
  if Key = VK_RETURN then
    if PaymentViewBetragNetto.Focused then begin
      ADataModule.ATable.Append;
      PaymentViewAccount.FocusWithSelection;
    end; // if PaymentViewBetragNetto.Focused then begin
end;
</code>```

Title: cxGrid new record on last field Enter

Body:
I'm struggling to make a TcxGrid to append a new record whenever the user presses Enter key on last field of the current record, however I didn't find any property that might help me achieve this.

I tried setting the OnKeyDown event of the grid view(TcxGridDBTableView), with the following code

if Key = VK_RETURN then
  if PaymentViewBetragNetto.Focused then
    PaymentView.DataController.AppendRecord;

however the code is not executed for some reason...

Any idea on how to append record on last field OnEnter event would be highly appreciated.

Thank you.

Body:
It seems that the way to solve this is to set the OnEditKeyDown/Up/Press of the grid view in order to handle this type of functionality, therefore:

procedure XXX.PaymentViewEditKeyUp(Sender: TcxCustomGridTableView;
  AItem: TcxCustomGridTableItem; AEdit: TcxCustomEdit; var Key: Word;
  Shift: TShiftState);
begin
  if Key = VK_RETURN then
    if PaymentViewBetragNetto.Focused then begin
      ADataModule.ATable.Append;
      PaymentViewAccount.FocusWithSelection;
    end; // if PaymentViewBetragNetto.Focused then begin
end;