text:
Q: Removing event listener which was added with bind In JavaScript, what is the best way to remove a function added as an event listener using bind()?
Example
(function(){

    // constructor
    MyClass = function() {
        this.myButton = document.getElementById("myButtonID");
        this.myButton.addEventListener("click", this.clickListener.bind(this));
    };

    MyClass.prototype.clickListener = function(event) {
        console.log(this); // must be MyClass
    };

    // public method
    MyClass.prototype.disableButton = function() {
        this.myButton.removeEventListener("click", ___________);
    };

})();

The only way I can think of is to keep track of every listener added with bind.
Above example with this method:
(function(){

    // constructor
    MyClass = function() {
        this.myButton = document.getElementById("myButtonID");
        this.clickListenerBind = this.clickListener.bind(this);
        this.myButton.addEventListener("click", this.clickListenerBind);
    };

    MyClass.prototype.clickListener = function(event) {
        console.log(this); // must be MyClass
    };

    // public method
    MyClass.prototype.disableButton = function() {
        this.myButton.removeEventListener("click", this.clickListenerBind);
    };

})();

Are there any better ways to do this?

A: For those who have this problem while registering/removing listener of React component to/from Flux store, add the lines below to the constructor of your component:

class App extends React.Component {
  constructor(props){
    super(props);
    // it's a trick! needed in order to overcome the remove event listener
    this.onChange = this.onChange.bind(this);
  }
  // then as regular...
  componentDidMount (){
    AppStore.addChangeListener(this.onChange);
  }

  componentWillUnmount (){
    AppStore.removeChangeListener(this.onChange);
  }

  onChange () {
    let state = AppStore.getState();
    this.setState(state);
  }

  render() {
    // ...
  }

}

A: Although what @machineghost said was true, that events are added and removed the same way, the missing part of the equation was this:

A new function reference is created after .bind() is called.

See Does bind() change the function reference? | How to set permanently?
So, to add or remove it, assign the reference to a variable:
var x = this.myListener.bind(this);
Toolbox.addListener(window, 'scroll', x);
Toolbox.removeListener(window, 'scroll', x);

This works as expected for me.

A: It doesn't matter whether you use a bound function or not; you remove it the same way as any other event handler.  If your issue is that the bound version is its own unique function, you can either keep track of the bound versions, or use the removeEventListener signature that doesn't take a specific handler (although of course that will remove other event handlers of the same type).
(As a side note, addEventListener doesn't work in all browsers; you really should use a library like jQuery to do your event hook-ups in a cross-browser way for you.  Also, jQuery has the concept of namespaced events, which allow you to bind to "click.foo"; when you want to remove the event you can tell jQuery "remove all foo events" without having to know the specific handler or removing other handlers.)

A: jQuery solution:
let object = new ClassName();
let $elem = $('selector');

$elem.on('click', $.proxy(object.method, object));

$elem.off('click', $.proxy(object.method, object));

A: We had this problem with a library we could not change. Office Fabric UI, which meant we could not change the way event handlers were added. The way we solved it was to overwrite the addEventListener on the EventTarget prototype.
This will add a new function on objects element.removeAllEventListers("click")
(original post: Remove Click handler from fabric dialog overlay)
        <script>
            (function () {
                "use strict";

                var f = EventTarget.prototype.addEventListener;

                EventTarget.prototype.addEventListener = function (type, fn, capture) {
                    this.f = f;
                    this._eventHandlers = this._eventHandlers || {};
                    this._eventHandlers[type] = this._eventHandlers[type] || [];
                    this._eventHandlers[type].push([fn, capture]);
                    this.f(type, fn, capture);
                }

                EventTarget.prototype.removeAllEventListeners = function (type) {
                    this._eventHandlers = this._eventHandlers || {};
                    if (type in this._eventHandlers) {
                        var eventHandlers = this._eventHandlers[type];
                        for (var i = eventHandlers.length; i--;) {
                            var handler = eventHandlers[i];
                            this.removeEventListener(type, handler[0], handler[1]);
                        }
                    }
                }

                EventTarget.prototype.getAllEventListeners = function (type) {
                    this._eventHandlers = this._eventHandlers || {};
                    this._eventHandlers[type] = this._eventHandlers[type] || [];
                    return this._eventHandlers[type];
                }

            })();
        </script>

A: Here is the solution:
var o = {
  list: [1, 2, 3, 4],
  add: function () {
    var b = document.getElementsByTagName('body')[0];
    b.addEventListener('click', this._onClick());

  },
  remove: function () {
    var b = document.getElementsByTagName('body')[0];
    b.removeEventListener('click', this._onClick());
  },
  _onClick: function () {
    this.clickFn = this.clickFn || this._showLog.bind(this);
    return this.clickFn;
  },
  _showLog: function (e) {
    console.log('click', this.list, e);
  }
};

// Example to test the solution
o.add();

setTimeout(function () {
  console.log('setTimeout');
  o.remove();
}, 5000);

A: As others have said, bind creates a new function instance and thus the event listener cannot be removed unless it is recorded in some way.
For a more beautiful code style, you can make the method function a lazy getter so that it's automatically replaced with the bound version when accessed for the first time:
class MyClass {
  activate() {
    window.addEventListener('click', this.onClick);
  }

  deactivate() {
    window.removeEventListener('click', this.onClick);
  }

  get onClick() {
    const func = (event) => {
      console.log('click', event, this);
    };
    Object.defineProperty(this, 'onClick', {value: func});
    return func;
  }
}

If ES6 arrow function is not supported, use const func = (function(event){...}).bind(this) instead of const func = (event) => {...}.
Raichman Sergey's approach is also good, especially for classes. The advantage of this approach is that it's more self-complete and has no separated code other where. It also works for an object which doesn't have a constructor or initiator.

A: It's been awhile but MDN has a super explanation on this. That helped me more than the stuff here.
MDN :: EventTarget.addEventListener - The value of "this" within the handler
It gives a great alternative to the handleEvent function.
This is an example with and without bind:
var Something = function(element) {
  this.name = 'Something Good';
  this.onclick1 = function(event) {
    console.log(this.name); // undefined, as this is the element
  };
  this.onclick2 = function(event) {
    console.log(this.name); // 'Something Good', as this is the binded Something object
  };
  element.addEventListener('click', this.onclick1, false);
  element.addEventListener('click', this.onclick2.bind(this), false); // Trick
}

A problem in the example above is that you cannot remove the listener with bind. Another solution is using a special function called handleEvent to catch any events:

A: If you want to use 'onclick', as suggested above, you could try this:
(function(){
    var singleton = {};

    singleton = new function() {
        this.myButton = document.getElementById("myButtonID");

        this.myButton.onclick = function() {
            singleton.clickListener();
        };
    }

    singleton.clickListener = function() {
        console.log(this); // I also know who I am
    };

    // public function
    singleton.disableButton = function() {
        this.myButton.onclick = "";
    };
})();

I hope it helps.

A: can use about ES7:
class App extends React.Component {
  constructor(props){
    super(props);
  }
  componentDidMount (){
    AppStore.addChangeListener(this.onChange);
  }

  componentWillUnmount (){
    AppStore.removeChangeListener(this.onChange);
  }

  onChange = () => {
    let state = AppStore.getState();
    this.setState(state);
  }

  render() {
    // ...
  }

}


text:
Q: Extract all the values of a key based on the primary key id in a list of dictionaries I have a list of Ordered dictionary like below:
l = [OrderedDict([(u'id', u'5'), (u'name', u'Jack')]), OrderedDict([(u'id',
u'6'), (u'name', u'Steve')]),...]

where id is the primary key. For every dicitonary in the list I want to extract and store only the name items corresponding to each id, how to do it?
with the below code:
li = []
for item in l:
    res = li.append(item['name'])
    print res

It results None
Edit:
Expected result:
['Jack', 'Steve',...]

'Jack' should be corresponding to id=5, 'Steve' for id=6 and so on

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why did I lose my Xbox achievements? When I first got my Xbox, 5 or so years ago, I didn't have an Xbox Live account. I wasn't even registered for a free Silver Membership.
I played games on it; then, a few months ago, I got a Gold Membership. When I did that I lost quite a few achievements and gamerscore. I have tried going back and playing the games again, but I can't even re-acquire the achievements. When I go into the game that the achievements were lost on, it shows the picture for the achievements that I lost, rather than the "locked" symbol, so my box knows I got the achievements but won't give me credit for it.
I have tried e-mailing Xbox Support, but they were not helpful. Hopefully someone here has some helpful advice.

A: There are three types of Xbox accounts: local, free, and Gold. (Gold Family accounts work the same as individual Gold accounts for purposes of this question.)
With a local account, you can track your progress locally and move your profile from console to console using a USB stick (or memory card if you have an older console that uses them), but you cannot play online, and if something happens to your profile locally, it's gone. This is the account under which you initially obtained those achievements.
With an Xbox Live free account (formerly called Silver) or a Gold account, you track your progress locally as before, but your profile is also synched with Microsoft's servers, so you can recover it to other consoles without using a memory device, and any achievements that are synched to the servers will be saved, even if your console dies.
Microsoft doesn't say anything officially about upgrading a local account to an Xbox Live account, but there are suggestions elsewhere that it can be done. The best suggestion seems to be to sign into your local (offline) profile and then sign up for Xbox Live there. If your gamertag isn't already used by another Xbox Live member, then this should convert your gamertag to an XBL profile and retain your achievements. (Note that achievements earned when offline will not have a date stamp; this applies whether or not they are associated with an XBL profile.)
It may be possible that Xbox Support could give you instructions to merge your offline and online profiles after the fact, but that would most likely require you to upgrade the offline profile and then have Xbox Support merge the two online profiles ... that is not a process I would recommend, as it could go wrong in any number of ways, like making you pay for two Xbox Live Gold profiles and not giving you a refund once they fail to merge the two, or merging them in the wrong direction and overwriting the achievements you had.
As TZHX suggests, the locked achievements are most likely the result of those games storing your progress locally and assuming that you were credited with the achievement when you reached that point in the game. Deleting the saves for those games should fix the problem, because you got them with an offline profile and thus there is nothing online for them to be incompletely synched with. Note that you may have to sign in with the offline profile to delete the saves.

A: When you didn't have an XBL account, you were earning achievements somewhere on a different entity. Moving onto a different gamer tag (joining Xbox Live) loses those achievements. Depending on the games you play, I'd guess it's the game getting confused and thinking you've already unlocked the achievement based on your saved games. So I'd try deleting all local content you have for those games, clearing your system's cache and starting from scratch with those particular games.

A: It may be that they thought you were cheating, and reset your gamerscore. In that case, you can't ever get gamerscore again.


text:
Q: When running a program from within a program using system() in stdlib.h, how do I simulate typing to feed the sub-program's scanf call? I am writing a program to run a different program over and over, giving it different input to a question each time, checking the output.  system("the_program") accomplishes this, but how do I give that program input when it runs scanf()?

A: The simplest way is to write a file, and pass it to the child using redirection (system("the_program < the_file")).
But, and this is much better, you can make a pipe between your program and the child. The child needs to have its standard input (file descriptor 0) connected to the reading side of the pipe. system is synchronous, so besides pipe and dup2 you need the fork and execve system calls. Luckily, there is a wrapper for this process: popen("the_program", "w"). It returns a FILE* that you can write to. Close the FILE* with pclose, and be sure to read the manual because it is different from fclose!

A: In the case where you are writing both parent and child programs, there is no need to a solve a problem arising by simulating something else, when we can just pass in arguments:
system('./the_program the_scanf_input')
And of course the_program:
var = argv[1] //this was var = scanf('%', &var)


text:
Q: How to include files and folders in the deployment of a visual studio, C# project? I am working on a C# application.  Inside this program it looks through a directory and uses files in the same directory containing the exe files in the debug folder.  I added a setup project, for deployment, to the solution for the application.  I tend to be naive and figured I could just drop the files and folders into the installation folder after I install it on another computer.  I know there is a way to add these files and folders to the projects and set it up to have the installer install these files at the time of installation.

A: I assume you are working with Visual Studio 2010, and using Visual Studio Installer Setup Project to create an MSI output file.
Right click on the Setup project, select View menu, and select File System.
In there you are able to define files and folders to be installed.


text:
Q: RuntimeError: Queue objects should only be shared between processes through inheritance I'm having some trouble with ProcessPoolExecutor.
The following code is trying to find the shortest path in a WikiRace game, it gets 2 titles and navigates between one to another.
Here is my code:
class AsyncSearch:
    def __init__(self, start, end):
        self.start = start
        self.end = end
        # self.manager = multiprocessing.Manager()
        self.q = multiprocessing.Queue()
        # self.q = self.manager.Queue()

    def _add_starting_node_page_to_queue(self):
        start_page = WikiGateway().page(self.start)
        return self._check_page(start_page)

    def _is_direct_path_to_end(self, page):
        return (page.title == self.end) or (page.links.get(self.end) is not None)

    def _add_tasks_to_queue(self, pages):
        for page in pages:
            self.q.put(page)

    def _check_page(self, page):
        global PATH_WAS_FOUND_FLAG
        logger.info('Checking page "{}"'.format(page.title))
        if self._is_direct_path_to_end(page):
            logger.info('##########\n\tFound a path!!!\n##########')
            PATH_WAS_FOUND_FLAG = True
            return True
        else:
            links = page.links
            logger.info("Couldn't find a direct path form \"{}\", "
                        "adding {} pages to the queue.".format(page.title, len(links)))
            self._add_tasks_to_queue(links.values())
            return "Couldn't find a direct path form " + page.title

    def start_search(self):
        global PATH_WAS_FOUND_FLAG
        threads = []
        logger.debug(f'Running with concurrent processes!')
        if self._add_starting_node_page_to_queue() is True:
            return True
        with concurrent.futures.ProcessPoolExecutor(max_workers=AsyncConsts.PROCESSES) as executor:
            threads.append(executor.submit(self._check_page, self.q.get()))

I'm getting the following exception:
Traceback (most recent call last):
  File "c:\users\tomer smadja\appdata\local\programs\python\python36-32\lib\multiprocessing\queues.py", line 241, in _feed
    obj = _ForkingPickler.dumps(obj)
  File "c:\users\tomer smadja\appdata\local\programs\python\python36-32\lib\multiprocessing\reduction.py", line 51, in dumps
    cls(buf, protocol).dump(obj)
  File "c:\users\tomer smadja\appdata\local\programs\python\python36-32\lib\multiprocessing\queues.py", line 58, in __getstate__
    context.assert_spawning(self)
  File "c:\users\tomer smadja\appdata\local\programs\python\python36-32\lib\multiprocessing\context.py", line 356, in assert_spawning
    ' through inheritance' % type(obj).__name__
RuntimeError: Queue objects should only be shared between processes through inheritance

It's weird since I'm using multiprocessing.Queue() that should be shared between the processes as mentioned by the exception.
I found this similar question but couldn't found the answer there.
I tried to use self.q = multiprocessing.Manager().Queue() instead of self.q = multiprocessing.Queue(), I'm not sure if this takes me anywhere but the exception I'm getting is different:
Traceback (most recent call last):
  File "c:\users\tomer smadja\appdata\local\programs\python\python36-32\lib\multiprocessing\queues.py", line 241, in _feed
    obj = _ForkingPickler.dumps(obj)
  File "c:\users\tomer smadja\appdata\local\programs\python\python36-32\lib\multiprocessing\reduction.py", line 51, in dumps
    cls(buf, protocol).dump(obj)
  File "c:\users\tomer smadja\appdata\local\programs\python\python36-32\lib\multiprocessing\process.py", line 282, in __reduce__
    'Pickling an AuthenticationString object is '
TypeError: Pickling an AuthenticationString object is disallowed for security reasons

Also, when I'm trying to use multiprocessing.Process() instead of ProcessPoolExecutor, I'm unable to finish the process once I do find a path. I set up a global variable to stop PATH_WAS_FOUND_FLAG to stop the process initiation but still with no success. What I'm missing here?

A: ProcessPoolExecutor.submit(...) will not pickle multiprocessing.Queue instances as well other shared multiprocessing.* class instances. You can do two things: One is to use SyncManager, or you can initialize the worker with the multiprocessing.Queue instance at ProcessPoolExecutor construction time. Both are shown below.
Following is your original variation with a couple of fixes applied (see note at end)... with this variation, multiprocessing.Queue operations are slightly faster than below SyncManager variation...
global_page_queue = multiprocessing.Queue()
def set_global_queue(q):
    global global_page_queue
    global_page_queue = q

class AsyncSearch:
    def __init__(self, start, end):
        self.start = start
        self.end = end
        #self.q = multiprocessing.Queue()
    ...
    def _add_tasks_to_queue(self, pages):
        for page in pages:
            #self.q.put(page)
            global_page_queue.put(page)

    @staticmethod
    def _check_page(self, page):
        ...

    def start_search(self):
        ...
        print(f'Running with concurrent processes!')
        with concurrent.futures.ProcessPoolExecutor(
                max_workers=5,
                initializer=set_global_queue,
                initargs=(global_page_queue,)) as executor:
            f = executor.submit(AsyncSearch._check_page, self, global_page_queue.get())
            r = f.result()
            print(f"result={r}")

Following is SyncManager variation where queue operations are slightly slower than above multiprocessing.Queue variation...
import multiprocessing
import concurrent.futures

class AsyncSearch:
    def __init__(self, start, end):
        self.start = start
        self.end = end
        self.q = multiprocessing.Manager().Queue()
    ...
    @staticmethod
    def _check_page(self, page):
        ...

    def start_search(self):
        global PATH_WAS_FOUND_FLAG
        worker_process_futures = []
        print(f'Running with concurrent processes!')
        with concurrent.futures.ProcessPoolExecutor(max_workers=5) as executor:
            worker_process_futures.append(executor.submit(AsyncSearch._check_page, self, self.q.get()))
            r = worker_process_futures[0].result()
            print(f"result={r}")

Note, for some shared objects, SyncManager can be anywhere from slightly to noticeably slower compared to multiprocessing.* variations. For example, a multiprocessing.Value is in shared memory whereas a SyncManager.Value is in the sync manager processes, requiring overhead to interact with it.
An aside, unrelated to your ask, your original code was passing _check_page with incorrect parameters, where you were passing dequeued item to self, leaving the page parameter None. I resolved this by changing _check_page to a static method and passing self.


text:
Q: Upgrading Debian from 4.0, but apt mirrors give 404 I have an old Buffalo HS-DH500GL NAS.  I bought it years ago (2007 I think) when I heard it could be upgraded to run Debian 4.0.  I followed some random tutorial (long forgotten where I found it) to install Debian, and the box has been running fine on my shelf for years.  I have hardly used it, but I would like to start using it more and have found that everything is out of date on it.  I decided to try to get it all up-to-date, but when I run aptitude to update everything, I'm getting all kinds of 404 errors.  I'm guessing everything has been moved to the archive servers.
What I would LIKE to do is start from scratch, wipe everything, and install a fresh (and up to date) OS.  I only have access to it via SSH (no serial port).  Any ideas how to go about this?  Would it be possible/feasible to take the HDD out of the NAS, and on another computer copy over some install of a new OS?

A: Taking the hard drive out to put into another machine in order to freshly install debian is often a very workable solution, however, in your case, where you are unlikely to have another machine of the same architecture to drop the hard drive into, this is a lot less convenient.  This is still possible using debootstrap, but debootstrap doesn't do a full installation.  it just installs some packages,  you are left to do a lot of the renaming stuff that the installer would do, like setting up /etc/network/interfaces, /etc/hosts, /etc/resolv.conf, /etc/hostname, installing a bootloader, and kernel.
Upgrading from etch to squeeze is a definite possibility.  Just note that there was a lenny release which you should not skip on your way from etch to squeeze.
here's what I'd recommend:
Note first that the current etch repositories have moved, since, it is so far beyond end-of-life. the current etch respoitory is this:
deb http://archive.debian.org/debian etch main

use just that, then apt-get update and apt-get upgrade then apt-get dist-upgrade to make sure you are up to date with the latest etch.  Then upgrade to lenny by following chapter 4 of the lenny release notes. Keeping in mind that also lenny is past end-of-life, so the repository for lenny is now:
deb http://archive.debian.org/debian lenny main

So use the above repository when you get to section 4.4 of the lenny release notes.  After upgrading to lenny, you should be able to upgrade to squeeze by following chapter 4 of the squeeze release notes.
These instructions in the release notes might seem much more complicated when compared to some advice you'll get to just "change sources and dist-upgrade", but we've arrived at these instructions through lots of independent testing, and these instructions should have a much greater probability of actually leaving you with a working install.

A: Sounds like your aptitude sources are not loading properly. Edit the file /etc/apt/sources.list and make sure they are using the correct repositories for Debian 4.0 "Etch" which should looks something like this:

deb http://archive.debian.org/debian/ etch main contrib non-free
deb-src http://archive.debian.org/debian/ etch main contrib non-free

deb http://security.debian.org/ etch/updates main contrib non-free
deb-src http://security.debian.org/ etch/updates main contrib non-free

Notice I included the non-free option, this is of course, your prerogative. After editing this file run the commands apt-get update to update the repositories and then apt-get upgrade to run the upgrades on your system for all packages.
Otherwise, a quick Googling seems to indicate that your device would handle Debian 6 "squeeze" and so you might choose to go that far. In which case, replace the repositories in the file where it says etch to squeeze and run apt-get update and then apt-get dist-upgrade to upgrade your distro to 6.
Note, moving from "etch" to "squeeze" (meaning you're skipping the 5 distro "lenny" in between) could be more intense, while at the same time, depending on the software and packages you have installed, could be no problem at all. So in the case of running into trouble or if you're being extra cautious check out a tutorial such as this: http://www.cyberciti.biz/tips/howto-upgrade-debian-linux-4etch-to-5lenny-server.html that has good pointer on upgrades.


text:
Q: Python: Having issues returning the whole dictionary I'm having issues returning the whole dictionary from my code.  I currently have not worked on the second function so that can be ignored.  I'm just trying to make sure the first function works first.
This is what I have for my code right now.
def disease_to_code_dictionary(  ) :
    """ Function returns a dictionary with disease names as keys and
      ICD 10 codes as values. """

    diseases = {}

    infile = open("ICD10.txt","r")
    header_row = infile.readline() # skip the header row

    for line in infile :

        cells = line.split("\t") # split by the tab character
        if len(cells) >= 2 : # only if the line had a tab
            code = cells[0]
            disease = cells[1]
            disease = disease.lower() # lowercase
            disease = disease.replace("\"","") # remove all double quotes

            diseases[disease] = code

            return diseases

    infile.close()

    return list(diseases.items())

    # The program should give the code if the disease name exists
    # otherwise say "Disease name does not exist.".
    def query_disease_to_code() :
        """ Interactive function to query code from disease name. """
        d = disease_to_code_dictionary() # disease to code dictionary

       #query = input("Give disease name (q to quit): ")
        #while query != "q" :
         #   query = query.lower() # lowercase
            # complete here
          #  query = input("Give disease name (q to quit): ")

        print(d)

    query_disease_to_code()

Output: {'cholera due to vibrio cholerae 01, biovar cholerae': 'A000'}
The text I'm reading from has a ton more lines but this the only one showing.

A: First of all, you have a typo in your dict name. Second I would recommend to split these two functionalities (Reading the file and parsing the text):
def disease_to_code_dictionary( file_text ) :

        diseases = {}

        for line in file_text.split("\n")[1:] :

            cells = line.split("\t")

            if len(cells) >= 2 :
                code = cells[0]
                disease = cells[1]
                disease = disease.lower()
                disease = disease.replace("\"","")

                diseases[disease] = code

        return diseases

txt = """Code\tDisease
1\tMalaria
2\tEbola
3\tYellow Fever
"""

Now when I run this code on txt it returns as expected:
{'malaria': '1', 'ebola': '2', 'yellow fever': '3'}


text:
Q: Error: cvc-elt.1: Cannot find the declaration of element 'xsl:stylesheet' currently I am working with soap configuration and to do so, I am using an xsl file. But, when I tried to test the configuration, I got above error.
Here is the full error log:

And here is the content of my xsl file:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope" xmlns:wsa="http://www.w3.org/2005/08/addressing">
  <xsl:output method="xml" encoding="ISO-8859-1" indent="no"/>

  <xsl:template match="/">
        <soapenv:Envelope >
            <soapenv:Header>
              <wsa:To>esbp://mycompany.de/lsmh/zks-eap</wsa:To>
              <wsa:MessageID>
                <xsl:value-of select="1"/>
              </wsa:MessageID>
              <wsa:Action>http://mycompany.de/zks-eap/<xsl:value-of select="//events/dataEvent[@name='request']/@value"/>
              </wsa:Action>
              <wsa:ReplyTo>
                <wsa:Address>esbp://mycompany.de/lsmh/mobako</wsa:Address>
              </wsa:ReplyTo>
              <wsa:From>
                <wsa:Address>esbp://mycompany.de/lsmh/mobako</wsa:Address>
              </wsa:From>
            </soapenv:Header>
            <soapenv:Body>
                <xsl:processing-instruction name="archimoaXsltConnector">callback="true"</xsl:processing-instruction>
                <zkseap:uebermittleAusweisdatenRequest xmlns:zkseap="http://mycompany.de/zks-eap">
                  <ausweis>
                    <nummer>
                      <xsl:value-of select="/ausweisnummer"/>
                    </nummer>
                  </ausweis>
                </zkseap:uebermittleAusweisdatenRequest>
            </soapenv:Body>
        </soapenv:Envelope>
    </xsl:template>
</xsl:stylesheet>

Why am I getting those error? And how can I solve it? Thanks in advance.


text:
Q: Data retrieval from database using perl with a foreach $dbh_source2 = DBI->connect("dbi:Oracle:host=.......;port=......;sid=......",'..........','..........');
foreach $data_line (@raw_data) {
    $SEL = "SELECT arg1,arg2 FROM TABLE_NAME WHERE DATA_NAME = '$data_line'";
    $sth = $dbh_source2->prepare($SEL);
    $sth->execute();

    while (my @row = $sth->fetchrow_array() ) {
        print @row;
        print "\n";
    }
}
END {
    $dbh_source2->disconnect if defined($dbh_source2);
}

I am trying to grab several lines of data from a user.  I want to take that data and use it to query a database and grab ARG1 and ARG2 WHERE USER_DATA = $data_line.
It will not display anything.

A: Here's a quick revision which uses SQL placeholders in order to keep Bobby Tables from destroying your database.  It may also fix the problem you're currently having, but I haven't seen enough details of your problem yet to be sure.
my $dbh_source2 = DBI->connect("dbi:Oracle:host=.......;port=......;sid=......",'..........','..........');

my $SEL = "SELECT arg1,arg2 FROM TABLE_NAME WHERE DATA_NAME = ?";
my $sth = $dbh_source2->prepare($SEL);

foreach my $data_line (@raw_data) {
    $sth->execute($data_line);

    while (my @row = $sth->fetchrow_array() ) {
        print @row;
        print "\n";
    }
}
END {
    $dbh_source2->disconnect if defined($dbh_source2);
}

A: my $dbh_source2 = DBI->connect
("dbi:Oracle:host=.......;port=......;sid=......",'..........','..........');

my $SEL = "SELECT arg1,arg2 FROM TABLE_NAME WHERE DATA_NAME = ?";
my $sth = $dbh_source2->prepare($SEL);

foreach my $data_line (@raw_data) {
    chomp $data_line;
    $sth->execute($data_line);

    while (my @row = $sth->fetchrow_array() ) {
        print "$data_line\t @row\n";
    }
}
END {
    $dbh_source2->disconnect if defined($dbh_source2);
}

The issue I was having was the fact that the development database was not updated with the correct information so some of the items came up blank.  When using the production database with the correct information it worked great!
Thank you all for your help!


text:
Q: select a partir de data no banco postgreSQL Como faço um select no banco postgreSQL pra ele me retorna os dados  a partir de uma data especifica, por exemplo tenho um campo do tipo timestamp com nome data_entrevista, quero que ele me traz os dados cadastrados desde o dia de hoje para frente.
SELECT * FROM tabela Where data_entrevista = data de hoje para frente

A: Utilize >= para trazer apenas datas mais recentes:
SELECT * FROM tabela Where data_entrevista >= '2016-10-19 00:00:00'

A: Como o campo é timestamp (data e horário) pode fazer um cast (::tipo) para date e fazer a comparação apenas com a  data atual CURRENT_DATE
SELECT * FROM tabela Where data_entrevista::date >= CURRENT_DATE

Postgres - documentação - Datetime

A: Assim:
SELECT * FROM tabela Where data_entrevista::date = '2019-10-16'


text:
Q: Maven - Do you need a main to use a project as a library? I'm working on a project where I have a "core" and an "API" that are two separate maven projects.
Currently, I'm exporting the API in a jar using Eclipse and I'm linking it in maven like that :
<dependency>
    <groupId>com.project.my</groupId>
    <artifactId>project-api</artifactId>
    <version>1.0.0</version>
    <scope>system</scope>
    <systemPath>${project.basedir}/src/main/resources/dependencies/project-api.jar</systemPath>
</dependency>

It's working properly and I can use the classes defined in my API.
But now I want to have a better workflow and I'm trying to install the API in my local maven repository and then link it normaly in the core :
<dependency>
    <groupId>com.project.my</groupId>
    <artifactId>project-api</artifactId>
    <version>1.0.0</version>
</dependency>

But when I run maven clean install I'm getting the following error :
Execution default of goal org.springframework.boot:spring-boot-maven-plugin:1.3.3.RELEASE:repackage failed: Unable to find main class

And I indeed don't have a main in my API, since I don't need one.
Note that I use spring-boot for both projects, as I'm using some of their dependencies and it's easier to let them manage the versions (I only use the utility classes in the API).
So I'd like to know if I HAVE to have a main anyway, even if I don't ever use it, or if I'm doing something wrong trying to install my API in the local repository ?
Thanks :)

A: Thanks to Thilo's wise advices, I managed to get it working.
So what I did was removing all unused spring-boot references from my API project and only keeping the spring dependencies I needed, and I was then able to run mvn clean install properly.
Here's what I got rid of :
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>

and
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.3.RELEASE</version>
    <relativePath/>
</parent>

I had to add the versions to some of the dependencies that were previously managed by spring-boot, but it's now working fine.


text:
Q: Como funciona o acesso à strings em um array?
Criar um programa que receba a data em numeral e depois retorne ela por extenso.

Tentei fazer algumas vezes, mas acabei mesclando meu código com um que achei de um fórum e saiu assim:
#include <stdio.h>
#include <stdlib.h>

void Date(int day, int month, int year);

int main(void){
    int day, month, year;

    printf("\nDay(1-31): ");
    scanf("%i", &day);

    //limpa o buffer de entrada.
     getchar();

    printf("\nMonth(1-12): ");
    scanf("%i", &month);

    //limpa o buffer de entrada.
    getchar();

    printf("\nYear(xxxx): ");
    scanf("%i", &year);

    Date(day, month, year);

    return 0;
}

void Date(int day, int month, int year){
    const char* months[] = {"January", "February", "March", "April",
                               "May", "June", "July", "August",
                               "Setember", "October", "November", "Dezember"};
    system ("clear"); //gnu-linux

    printf("The Date is: %s %dth, %d\n", months[month - 1], day , year);

}

Daí me surgiram duas dúvidas sobre o final deste código:
1 - por que é necessário o [month - 1]?
2 - por que o vetor não tem nenhum valor dentro para alocar?
3 - por que é necessário declarar const na variável char?

A:
1 - por que é necessário o [month - 1]?

Porque arrays começam em 0, então se digitou o mês 1 deve pegar o índice 0, se foi 2 deve pegar 1, e assim por diante até o índice 11 que é o mês 12 que conhecemos.

2 - por que o vetor não tem nenhum valor dentro para alocar?

O compilador consegue inferir isso lendo os valores que foram atribuídos para ele, mas há um valor, só não está visível no código.

3 - por que é necessário declarar const na variavel char?

Os valores de texto que tem ali está em uma área estática da memória, portanto uma área que não pode ser modificada. Literais string são sempre assim. Não é um local que pode manipular, então se tentar a aplicação quebra. Se colocar const o compilador sabe que não pode mexer ali então ele dá erro quando for compilar se tentar modificar algo ali, e esse erro é bem melhor que um erro quando está executando. Veja mais em De onde vem o espaço na memória necessário para cada elemento em um array de strings em C?. Também: Troca de conteúdo da variável char.


text:
Q: Ajax success: function(data) is undefined Edit: could've researched better... reading this post now: How do I return the response from an asynchronous call?
I have an ajax request which returns JSON data.  When I watch it in fiddler, it does go out to the service and get the JSON data, but when I try to set a variable to it's response, that variable is "undefined".  If I alert in the success method, it alerts, but the variable is still undefined.
I tried changing the function(data) to function(something) incase that had anything to do with it... same story.
var returndata
$.ajax({
    type: "GET",
    url: "GetSecurables/",
    data: { etaNumber: etaNumber },
    success: function (data) {
        returndata = data; //undefined
        alert('haaalp');
    }
});

The JSON is like below
[
  {
    "DelegateSid":null,
    "DisplayName":"Tom",
    "HasDelegation":true,
    "HasEtaManagement":false
  },
  {
    "DelegateSid":null,
    "DisplayName":"Tim",
    "HasDelegation":true,
    "HasEtaManagement":false
  },
  {
    "DelegateSid":null,
    "DisplayName":"Jake",
    "HasDelegation":true,
    "HasEtaManagement":false
  },
  {
    "DelegateSid":null,
    "DisplayName":"Ryan",
    "HasDelegation":true,
    "HasEtaManagement":false
  }
]

A: Try:
var returndata;

$.ajax({
    type: "GET",
    url: "GetSecurables/",
    data: { etaNumber: etaNumber },
    success: function (data) {
        console.log(data);
        returndata = data;
        console.log(returndata);
    }
});

If the 2 outputs are the same it might be the case that you're trying to access returndata from outside its scope, hence the undefined, or that you're accessing returndata before the Ajax call completes.


text:
Q: How to save the data of JSON file in local path to a SQL table? I want to save the data of JSON file which is in my local path to a SQL table.
My Local Path where the JSON file is present is E:\20180824LocalDump.json
I have used the below code in SQL to get the data from JSON file but I got errors.
DECLARE @Details VARCHAR(MAX)
SELECT @Details = BulkColumn FROM OPENROWSET(BULK 'E:\20180824LocalDump.json', SINGLE_BLOB) JSON;
SELECT * FROM OPENJSON(@Details)
WITH(Departure_airport nvarchar(50)  ,
    DisplayName nvarchar(40),
    Email nvarchar(60),
    Keep_me_deals nvarchar(40),
    Phone_Code nvarchar(50),
    Provider nvarchar(50),
    SignUpDate nvarchar(50),
    Telephone nvarchar(50),
    [Platform] nvarchar(50),
    AppVersion nvarchar(40))

Created a table as shown below:
Create Table Dump
(
Departure_airport nvarchar(50),
DisplayName nvarchar(40),
Email nvarchar(60),
Keep_me_deals nvarchar(40),
Phone_Code nvarchar(50),
Provider nvarchar(50),
SignUpDate nvarchar(50),
Telephone nvarchar(50),
[Platform] nvarchar(50),
AppVersion nvarchar(40)
)

My Json file contents:
[{"Departure_airport":"Test","DisplayName":"Test","Email":"Tst","Keep_me_deals":"Test","Phone_Code":"Test","Provider":"Test","SignUpDate":"Test","Telephone":"Test","Platform":"Test","AppVersion":"Test"},{"Departure_airport":"Test","DisplayName":"Test","Email":"Tst","Keep_me_deals":"Test","Phone_Code":"Test","Provider":"Test","SignUpDate":"Test","Telephone":"Test","Platform":"Test","AppVersion":"Test"},{"Departure_airport":"Test for IE","DisplayName":"Test for IE","Email":"Tst for IE","Keep_me_deals":"Test for IE","Phone_Code":"Test for IE","Provider":"Test for IE","SignUpDate":"Test for IE","Telephone":"Test for IE","Platform":"Test for IE","AppVersion":"Test for IE"},{"Departure_airport":"Test for UK","DisplayName":"Test for UK","Email":"Tst for UK","Keep_me_deals":"Test for UK","Phone_Code":"Test for UK","Provider":"Test for UK","SignUpDate":"Test for UK","Telephone":"Test for UK","Platform":"Test for UK","AppVersion":"Test for UK"},{"Departure_airport":"Test for UK 1","DisplayName":"Test for UK 1","Email":"Tst for UK 1","Keep_me_deals":"Test for UK 1","Phone_Code":"Test for UK 1","Provider":"Test for UK 1","SignUpDate":"Test for UK 1","Telephone":"Test for UK 1","Platform":"Test for UK 1","AppVersion":"Test for UK 1"}]

I am getting an error like:

Invalid object name 'OPENJSON' in SQL.

Please help me on this

A: If you are using SQL 2016 or later, you should also check the compatibility level of the database you are running the query from.
USE <your database>;
GO
SELECT compatibility_level FROM sys.databases WHERE name = '<your database>';
GO

If it is not at least 130 you need to (with the kind permission of your DBA) change it.
ALTER DATABASE <your database> SET COMPATIBILITY_LEVEL = 130;
GO

You probably want to Google for other effects of changing the compatibility level, but it's never caused me a problem.

A: Unfortunately you can't use openjson with SQL Server 2014: native json function have been introduced with SQL Server 2016 (more info on openjson here).
An excerpt from the linked page:

APPLIES TO: Server (starting with 2016)

You can still import the json file with OPENROWSET, but you will have to rely on string manipulation functions or on custom functions to extract data from you json file.


text:
Q: PHP MSSQL - sqlsrv stored procedure no error and no response I created a microsoft sql stored procedure, and I am calling it from the php code below. I do not get any errors, but I do not get any output either. I have looked all over, but I am still fuzzy about how to do the WHILE statement to retrieve the variables I need from sql... I am hoping someone can take a look at the php code below (and the sql code below that) to see what I might be missing. Oh, and when I execute the stored procedure through SQL, it works fine and returns the data I expect. Thanks!
    <?php

$serverName = "PRATHIBA-PC\SQL2008";
$connectionInfo = array( "Database"=>"TMS", "UID"=>"sa", "PWD"=>"asset12345" );
//$connectionInfo = array( "Database"=>"TMS");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false )
{
     echo "Could not connect.\n";
     die( print_r( sqlsrv_errors(), true));
}

/* Define the Transact-SQL query. Use question marks (?) in
 place of  the parameters to be passed to the stored procedure
 */

$tsql_callSP = "{call Getstudentname( 1 )}";

$studentid = '1';

$params = array(
                 array($studentid, SQLSRV_PARAM_IN)
               );

/* Execute the query. */
$stmt3 = sqlsrv_query( $conn, $tsql_callSP, $params);

if( $stmt3 === false ) {
echo "Error in executing statement 3.\n";
die( print_r( sqlsrv_errors(), true)); }

/* Display the value of the output parameters. */
while (sqlsrv_fetch_object($stmt3)) {
// SET PARAMETERS - SET TERMS
//echo $term;
}

/*Free the statement and connection resources. */

while ($obj=sqlsrv_fetch_object($stmt3)) {
// SET PARAMETERS - SET TERMS
echo $obj->term;}

sqlsrv_free_stmt( $stmt3);
?>

This is SQL Server stored procedure code
USE [TMS]
GO

DECLARE @return_value int

EXEC    @return_value = [dbo].[Getstudentname]

SELECT  'Return Value' = @return_value

GO

When I run this code I am getting output:
exec Getstudentname 1;

this is my output in sql server
1   Vivek   Johari  vivek@abc.com
Please help me guys..

A: You could try using a question mark as a place-holder for the parameter like this:
$tsql_callSP = "{call Getstudentname(?)}";

Not sure if this will help?


text:
Q: Windows bash equivalent of start in bash Does it exist? For example, in Windows Bash, I can do this:
start my-file.py # by default, .py gets executed, so it does
start https://github.com # opens github.com

How can I do this in bash

A: These applications are part of the operating system and not the shell.
The shell is simply a program that allows you to enter commands for the operating system. Windows comes with cmd and the new PowerShell. Linux comes with many shells, but the default in almost all distributions is bash, but there are many others that people use, one of the more popular ones is zsh.
macos also comes as default with bash, but just like Linux you can install alternative shells on it.
So the program start is actually part of Windows, you would need to find the equivalent for whatever operating system you are using that is running bash.

*

*In Windows, you can use start

*On macos, you can use open
On Linux, if available, you can try xdg-open, but this requires you to be running a desktop session, from the man page:

xdg-open opens a file or URL in the user's preferred application. If a
  URL is provided the URL will be opened in the user's preferred web
  browser. If a file is provided the file will be opened in the
  preferred application for files of that type. xdg-open supports file,
  ftp, http and https URLs.
xdg-open is for use inside a desktop session only. It is not recommended to use xdg-open as root.

A: You need something that wraps the ShellExecute function.
With Cygwin, this is cygstart.
With PowerShell, this is Start-Process.
You can run PowerShell from the Bash shell, but it is not ideal:
powershell Start-Process Blah.java

This is currently a feature request for Ubuntu on Windows.
In the Ubuntu Bash shell in Windows 10, how do you open a file or directory with the default program?


text:
Q: How does SQL Server ReadCommitted Isolation Level really work? I've found two IMHO inconsistent descriptions on how ReadCommitted works, both in MSDN documentation:

*

*https://msdn.microsoft.com/en-us/library/ms173763.aspx
Specifies that statements cannot read data that has been modified but not committed by other transactions.

*https://technet.microsoft.com/en-us/library/aa259216%28v=sql.80%29.aspx
Specifies that shared locks are held while the data is being read to avoid dirty reads, ...
I'm confused: in case of ReadCommitted, does SQL Server put locks while you READ or while you WRITE uncommitted data? Please clarify who knows for sure

A: Writes always X-lock. Always. This is so that rollbacks are guaranteed to work. Rollbacks needs known and stable data.
About reads: RC guarantees that no uncommitted writes become visible to RC readers. RC can be thought of as taking short-lived S-locks on data being read. There is one exception to this, though: SQL Server has an optimization in that it does not take S-locks on rows that are on unmodified pages. This means that you can read rows under RC that are X-locked in other transactions(!). This fulfills the contract of not reading uncommitted data just fine.
Example: If there is a writing tran that has modified any subset of the database, it is 100% certain that RC readers will not perceive those changes until the writer commits.
The guarantees of RC are so weak that it usually can only be used in cases where you essentially don't care about data consistency deeply.


text:
Q: What status code should we return if the POST succeeds but does not result in creating anything new? We have an endpoint which when you post create a new version of resource and returns a 201 and the location of the newly created resource. It determines the new version number based on a comparison of the current version and the version being posted (using a semver like ruleset).
If the version you post is identical to the existing version then no version number is updated. What should we return in this case?

*

*We could just return a 201 even though we have not technically created anything.

*I don't want to return a 409 as its not really a conflict, like when you post something with the same id. If you posted the same thing when the existing version was slightly different then you would happily get a 201.

*We could just return a 200, but then that would seem weird, and increases the response codes that the users have to deal with

Does the idempotency of the 201 response matter?
Any better suggestions?

A: How about 303 - See Other? Seems to fit. I draw your attention to this sentence
from the spec at https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

This method exists primarily to allow the output of a POST-activated script to redirect the user agent to a selected resource.

That sounds like what you want to do to me. Here's the rest of it.
10.3.4 303 See Other
The response to the request can be found under a different URI and SHOULD be retrieved using a GET method on that resource. This method exists primarily to allow the output of a POST-activated script to redirect the user agent to a selected resource. The new URI is not a substitute reference for the originally requested resource. The 303 response MUST NOT be cached, but the response to the second (redirected) request might be cacheable.
The different URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s).
  Note: Many pre-HTTP/1.1 user agents do not understand the 303
  status. When interoperability with such clients is a concern, the
  302 status code may be used instead, since most user agents react
  to a 302 response as described here for 303

A: I am a bit puzzled by the other answers as some get it almost right. So, let's clear up things a bit. If all requests are indeed performed with the POST method, in the context of ReSTfulness, they are supposed to modify state on the target server. Otherwise, the meaning of POST is a bit relaxed as you can see in RFC 7231, sec. 4.3.3.
Since the intent of the requests is to create a new version of a resource, they have failed if a version with the given presentation already exists. This would disqualify any 2xx-class response codes. From section 6.3:

The 2xx (Successful) class of status code indicates that the client's request was successfully received, understood, and accepted.

If you absolutely wanted to, you could go for 202/Accepted, which "is intentionally noncommittal." This is a bit of a stretch, though, as this status code is intended for queued processing. I would advise against it.
The 204/No Content code suggested by others is a bit of a poor choice. It were absolutely correct if you POSTed to the resource you were updating, though.
As the result is neither informational (1xx) nor a fault by the server (5xx). Let us have a look at the 3xx class first. From section 6.4:

The 3xx (Redirection) class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request.

One of the most prominent one here would be 304/Not Modified. While sounding like a perfect fit, this code is unfortunately not applicable here. It can only be returned in response to conditional GET or HEAD requests.
302/Found may sound like the next best fit. However, this code is intended for temporary redirects, which is in all likelyhood not what you want.
As has been suggested here, 303/See Other is indeed a good choice:

The 303 (See Other) status code indicates that the server is redirecting the user agent to a different resource [...] which is intended to provide an indirect response to the original request.
[...]
This status code is applicable to any HTTP method.  It is primarily used to allow the output of a POST action to redirect the user agent to a selected resource

All other 3xx codes are dealing with various forms of redirects that hardly relate to the situation here.
A final look, 4xx-class of status codes. From RFC 7231, sec. 6.5:

The 4xx (Client Error) class of status code indicates that the client seems to have erred.  Except when responding to a HEAD request, the server SHOULD send a representation containing an explanation of the error situation, and whether it is a temporary or permanent condition. These status codes are applicable to any request method.

Very few of these are actually deeling with the request body. Two of those who do would stand out here: One is 400/Bad Request, which is by design overly broad. It is - if you will - a catch-all solution. However, this would imply that the request body is malformed (as in syntactically incorrect) in some way, which is probably not the case.
More interesting is 409/Conflict. From the RFC (emphasis mine):

The 409 (Conflict) status code indicates that the request could not be completed due to a conflict with the current state of the target resource.

The wording of the definition places this code close to the PUT method, but is not exclusive. To reiterate the definition of the 4xx codes:

These status codes are applicable to any request method.

422/Unprocessable Entity is a contender, but it implies a semantic error, which really isn't the case here.
Ultimately (drumroll) the final piece of the puzzle could be found in section 4.3.3:

If the result of processing a POST would be equivalent to a representation of an existing resource, an origin server MAY redirect the user agent to that resource by sending a 303 (See Other) response with the existing resource's identifier in the Location field.

Note the "MAY." So you can really choose between 303 and 409. I feel 409 were the better fit, as clearly an earlier request introduced a state that is incompatible with the current one. OTOH, 303 may be the politer way to go and is closer to the standard. Either way, as a consumer of your API, I would really like to know if my requests failed. And be it by not having any effect whatsoever.

A: If nothing has been created by the operation, 201 is not suitable for that:

6.3.2. 201 Created
The 201 (Created) status code indicates that the request has been fulfilled and has resulted in one or more new resources being created. [...]

See below some options you could consider if the operation succeeds:

6.3.1. 200 OK
The 200 (OK) status code indicates that the request has succeeded. The payload sent in a 200 response depends on the request method. For the methods defined by this specification, the intended meaning of the payload can be summarized as:
[...]

*

*POST: a representation of the status of, or results obtained from, the action;

[...]
Aside from responses to CONNECT, a 200 response always has a payload, though an origin server MAY generate a payload body of zero length. If no payload is desired, an origin server ought to send 204 (No Content) instead. [...]

6.3.5. 204 No Content
The 204 (No Content) status code indicates that the server has successfully fulfilled the request and that there is no additional content to send in the response payload body. [...]

If the operation fails:

6.5.1. 400 Bad Request
The 400 (Bad Request) status code indicates that the server cannot will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).

11.2. 422 Unprocessable Entity
The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415 (Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request)  status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.

A: A 201 Created should be used whenever you creating a new resource without doubt.
As defined in HTTP Method Definitions RFC, either200 Ok or 204 No Contentis an appropriate response if the operation does not create a new resource depending on the response body content.

The action performed by the POST method might not result in a resource
  that can be identified by a URI. In this case, either 200 (OK) or 204
  (No Content) is the appropriate response status, depending on whether
  or not the response includes an entity that describes the result.
If a resource has been created on the origin server, the response
  SHOULD be 201 (Created) and contain an entity which describes the
  status of the request and refers to the new resource, and a Location
  header (see section 14.30).

Now, coming back to your original question about what to use when the operation is successful and there is nothing to return, you should use 204 No Content. This status code is specifically meant for scenarios where the requested operation is successfully completed but there is no additional relevant information that the server can provide.

The 204 (No Content) status code indicates that the server has successfully fulfilled the request and that there is no additional content to send in the response payload body.

A: I don't think that for this case the idempotency is an issue, because the state of the system is not the same as it was in the inicial request, because the entity now exists, so you can respond with a different code.
200 should be fine, but it is a little weird as you said.
I have never use this, but I read that for some case you should redirect with a 302, to make a get for other resource, in this case I think this apply, return a 302 and make a get pointing for the old semver, assuming that you have a get endpoint for this entity.

A: If the POST'd resource has the same version number, but different data, then a 409 would be fitting.  But if the data is the same as what's already stored, then a 409 might not be required. Through process of elimination I would say 200 OK would be fine.

We could just return a 200, but then that would seem weird, and increases the response codes that the users have to deal with

If this is a costly concern, consider eliminating the 201, not the 200.  The fact of the matter is that for any decently complex service there may be at some point a situation where a 20X (where X is not 0) is applicable.  So does that mean we code with each of the 20X responses in mind and spend time checking if our services has situations where 20X is preferred over 200?  I suspect not.  So unless there is a specific reason to respond with a 20X, for example to deal with a specific use case, then just use 200 and reduce the amount of coding and documenting required.  I suspect for most scenarios, the calling client does not care.

A: Ultimately, the correct answer probably depends on whatever client is consuming your API. If you are building the client too, you could do whatever you prefer... (Just don't get too crazy.)

Assuming you are writing the API and client:
My opinion/suggestion is...

*

*If there IS a new version number: The 201 HTTP status code would fit will.

*If there is NOT a new version number: The 200 or 204 HTTP status code would fit well.

*If there is no benefit to the client knowing the version number has changed or is the same: Send the 200 HTTP status code.

If you don't control the client consuming your API: Obviously defer to what they expect.

You may also wish review all of the HTTP Status Codes in the HTTP RFC spec. The above status codes also link directly to the relevant section.

A: 201 : when new version is created
202 : when existing version is updated
204 : when request is accepted but no processing is done
by def, 204 = No Content

The server has fulfilled the request but does not need to return an
  entity-body, and might want to return updated metainformation. The
  response MAY include new or updated metainformation in the form of
  entity-headers, which if present SHOULD be associated with the
  requested variant.
If the client is a user agent, it SHOULD NOT change its document view
  from that which caused the request to be sent. This response is
  primarily intended to allow input for actions to take place without
  causing a change to the user agent's active document view, although
  any new or updated metainformation SHOULD be applied to the document
  currently in the user agent's active view.
The 204 response MUST NOT include a message-body, and thus is always
  terminated by the first empty line after the header fields.

So its slight tangential to your needs but I think its the best fit.


text:
Q: Shortening a script using the for loop and array I'm using jq.carousel (http://www.eafit.edu.co/banners-eafit/carousel/index.html) to showcase some images of rooms. When you click on a slide of a room, it will direct to a page with unique URL, for example http;//www...../14095/.
My first code below works but when I try to combine the "room" scripts into one using a for loop and array (see second code), it doesn't work. Does anyone know what I'm missing or need to update? Thanks ahead!
Note: the "start:" in the script basically tells what slide should appear after the load pages
Code 1: Working Fine
<script src="/path/to/jq.carousel.js"></script>
<script>
(function() {
     // Room 1
    if (window.location.href.indexOf('14083') > -1) {
        var $carousel = $('#carousel_2').carousel({
            start: 1,
            indicator: true
        });
    }
    // Room 2
    if (window.location.href.indexOf('14094') > -1) {
        var $carousel = $('#carousel_2').carousel({
            start: 2,
            indicator: true
        });
    }
    // Room 3
    if (window.location.href.indexOf('14095') > -1) {
        var $carousel = $('#carousel_2').carousel({
            start: 3,
            indicator: true
        });
    }

  // Script for Prev and Next buttons to navigate through the carousel
  var totalSlides = $(".carousel_box").length - 4;
    $('#carousel_2_prev').on('click', function(ev) {
        ev.preventDefault();
        $carousel.carousel('prev');
    });

    $('#carousel_2_next').on('click', function(ev) {
        ev.preventDefault();
        $carousel.carousel('next');
    });

}());
</script>

Code 2: Combined "Room" Scripts
<script src="/path/to/jq.carousel.js"></script>
<script>
    var nodearray = ['14083', '14094', '14095'];

    (function() {
        // Section that needs to be updated
        for (var i = 0; i < nodearray.length; i++) {
            if (window.location.href.indexOf(nodearray[i]) > -1) {
                var $carousel = $('#carousel_2').carousel({
                    start: i++,
                    indicator: true
                });
            }
        }

        // Script for Prev and Next buttons to navigate through the carousel
        var totalSlides = $(".carousel_box").length - 4;
        $('#carousel_2_prev').on('click', function(ev) {
            ev.preventDefault();
            $carousel.carousel('prev');
        });

        $('#carousel_2_next').on('click', function(ev) {
            ev.preventDefault();
            $carousel.carousel('next');
        });

    }());
</script>

A: You probably don't want the ++ on line 8 in your second code block. That will increment the counting variable i.
<script src="/path/to/jq.carousel.js"></script>
<script>
    var nodearray = ['14083', '14094', '14095'];

    (function() {
        // Section that needs to be updated
        for (var i = 0; i < nodearray.length; i++) {
            if (window.location.href.indexOf(nodearray[i]) > -1) {
                var $carousel = $('#carousel_2').carousel({
                    start: i+1,
                    indicator: true
                });
            }
        }

        // Script for Prev and Next buttons to navigate through the carousel
        var totalSlides = $(".carousel_box").length - 4;
        $('#carousel_2_prev').on('click', function(ev) {
            ev.preventDefault();
            $carousel.carousel('prev');
        });

        $('#carousel_2_next').on('click', function(ev) {
            ev.preventDefault();
            $carousel.carousel('next');
        });

    }());
</script>


text:
Q: recompress useing python and zlib I am trying to decompress a file make some changes and than compress it again. Decompressing seems to work fine. I just need a method to compress it so it is compressed the same way it was before.
Here is my code:
import zlib

path = './input'
pathOut = './output'

def getInt(intArray):
    summe = 0
    for i in range(len(list(intArray))):
        summe += intArray[i]*256**i
        return(summe)

print(path)
inputfile = open(path, 'rb')
header = {}

header.update({"intro":inputfile.read(28)})
print("intro",(header["intro"]))

for key in ["header_size", "c_size", "header_v", "u_size", "blocks"]:
    header.update({key:inputfile.read(4)})
    print(key,getInt(header[key]))

inputfile.seek(getInt(header['header_size']))

blocks_count = getInt(header['blocks'])
data = []
for i in range(blocks_count):
    block_header = {}
    block_header.update({"c_size":inputfile.read(2)})
    print("c_size",getInt(block_header["c_size"]))
    block_header.update({"u_size":inputfile.read(2)})
    print("u_size",getInt(block_header["u_size"]))
    block_header.update({"checksum":inputfile.read(4)})
    print("checksum",getInt(block_header["checksum"]))
    temp = inputfile.read(getInt(block_header['c_size']))[2:-4]
    data.append(zlib.decompressobj().decompress(b'x\x9c' + temp))
output = b''
inputfile.seek(0)
output = inputfile.read(getInt(header["header_size"]))
inputfile.close()

compressor = zlib.compressobj(1)

for block in data:
    compressor.compress(block)
    output += compressor.flush(zlib.Z_SYNC_FLUSH)

print("output length",len(output))
print("c_size",getInt(header["c_size"]))
outputFile = open(pathOut, 'wb')
outputFile.write(output)
outputFile.close()

When I try to decompress my output it says:
Traceback (most recent call last):
    File "C:\Users\LSDesktop\Desktop\bla - Copy.py", line 45, in <module>
        data.append(zlib.decompressobj().decompress(b'x\x9c' + temp))
zlib.error: Error -3 while decompressing data: invalid stored block lengths

here are the first 50 bytes including the header of the first block. Ones how they should be (how they were before I compressed):
b'B\x0c\x00 rWfyx\x01\xacY\tX\x14G\x16\xae\x9e)p\x00\r\x18\x15\xb9Lk\xc7\x03\xaf\x88\x1a\x8c\x0c\xa8\x084(\x82\x17\x87\x17\x88\xa3\x8c\x1c;r\x0b'

and the first 50 bytes including the header of the first block after the I compressed it:
b'\xacY\tX\x14G\x16\xae\x9e)p\x00\r\x18\x15\xb9Lk\xc7\x03\xaf\x88\x1a\x8c\x0c\xa8\x084(\x82\x17\x87\x17\x88\xa3\x8c\x1c;r\x0b\x82&\nk4\x1c\x89fQ\x89'

A: Try Z_FINISH instead of Z_SYNC_FLUSH.  You are decompressing separate zlib streams, but you then try to make a new single zlib stream that is never terminated.  To make separate zlib streams, you need to use Z_FINISH each time.  You must use Z_FINISH at least once at the end, or you will never generate a proper zlib stream.
As for the wrappers around that, if you are attempting to write out the same format you read in, you're not doing that.  You need to recreate the header information, i.e. the lengths and checksums.  Where is this format documented?  Did you copy the code to read the input from somewhere else?
This is not the problem, but you should not be stripping the zlib header and trailer with [2:-4], and then adding a header back with b'x\x9c' +.  In order to decompress. Just decompress the zlib stream directly.


text:
Q: How to ask the user for a precise time including timezone on DialogFlow? I've created an Intent on DialogFlow that expects a user to supply an entity for time, using responses such as:

*

*"I'm looking to arrange for about Eight O'Clock"

*"Quarter past nine tonight."

*"I'm thinking around ten past five."
DialogFlow has been very smart in correctly identifying the relevant entities in each invocation as sys.time.
My application, however, deals with a number of different timezones. So when these values for time actually reach my webhook, I lose the ability to reliably compare the information they're providing against different timezones. i.e. I receive values like 08:50.
As a workaround, I know I could use the Google Maps Time Zone API in conjunction with a user's location, but I'd like my application to work without requiring special location permissions.
So, I'm wondering, is it possible to configure my Intent to recognize these raw time values as sys.datetime? I don't want to burden the user with having to specify the date, if possible, and make assumptions that they just mean "today" if they provide just a time value. Is it possible to do this natively within DialogFlow, or is it more likely that I'll need to write a handler on my webhook?


text:
Q: I don't understand tests in Django, Can you help me please? I am having a hard time with tests in Django and Python, for my final project I am making a  forums website, but I don't really have any idea how or what my tests should be. Here is the views page from mysite file. Could someone please walk me through what I should test for besides if a user is logged in.
from django.core.urlresolvers import reverse
from settings import MEDIA_ROOT, MEDIA_URL
from django.shortcuts import redirect, render_to_response
from django.template import loader, Context, RequestContext
from mysite2.forum.models import *

def list_forums(request):
     """Main listing."""
     forums = Forum.objects.all()
     return render_to_response("forum/list_forums.html", {"forums":forums},      context_instance=RequestContext(request))

def mk_paginator(request, items, num_items):
    """Create and return a paginator."""
    paginator = Paginator(items, num_items)
    try: page = int(request.GET.get("page", '1'))
    except ValueError: page = 1

    try:
        items = paginator.page(page)
    except (InvalidPage, EmptyPage):
        items = paginator.page(paginator.num_pages)
    return items

def list_threads(request, forum_slug):
    """Listing of threads in a forum."""
    threads = Thread.objects.filter(forum__slug=forum_slug).order_by("-created")
    threads = mk_paginator(request, threads, 20)
     template_data = {'threads': threads}
    return render_to_response("forum/list_threads.html", template_data, context_instance=RequestContext(request))

def list_posts(request, forum_slug, thread_slug):
    """Listing of posts in a thread."""
    posts = Post.objects.filter(thread__slug=thread_slug,  thread__forum__slug=forum_slug).order_by("created")
    posts = mk_paginator(request, posts, 15)
    thread = Thread.objects.get(slug=thread_slug)
    template_data = {'posts': posts, 'thread' : thread}
    return render_to_response("forum/list_posts.html", template_data, context_instance=RequestContext(request))

def post(request, ptype, pk):
    """Display a post form."""
    action = reverse("mysite2.forum.views.%s" % ptype, args=[pk])
    if ptype == "new_thread":
        title = "Start New Topic"
        subject = ''
    elif ptype == "reply":
        title = "Reply"
        subject = "Re: " + Thread.objects.get(pk=pk).title
    template_data = {'action': action, 'title' : title, 'subject' : subject}

    return render_to_response("forum/post.html", template_data, context_instance=RequestContext(request))

def new_thread(request, pk):
    """Start a new thread."""
    p = request.POST
    if p["subject"] and p["body"]:
        forum = Forum.objects.get(pk=pk)
        thread = Thread.objects.create(forum=forum, title=p["subject"], creator=request.user)
        Post.objects.create(thread=thread, title=p["subject"], body=p["body"], creator=request.user)
     return HttpResponseRedirect(reverse("dbe.forum.views.forum", args=[pk]))

def reply(request, pk):
    """Reply to a thread."""
     p = request.POST
    if p["body"]:
        thread = Thread.objects.get(pk=pk)
        post = Post.objects.create(thread=thread, title=p["subject"],         body=p["body"],
        creator=request.user)
     return HttpResponseRedirect(reverse("dbe.forum.views.thread", args=[pk]) +      "?page=last")

A: First read the Django testing documentation. You might also want to read this book. It's dated in some areas, but testing is still pretty much the same now as it was in 1.1.
It's a bit much of a topic to cover in an SO answer.

A: Well, you could test:

*

*If you have the right number of pages for the objects you're paginating.

*If the page you're viewing contains the right object range. If trying to access a page that doesn't exist returns the
appropriate error.

*If your views for listing objects and object detail return the correct HTTP status code (200)

For starters. Hope that helps you out.


text:
Q: Convert a dictionary containing arrays to a DataFrame with arrays as strings I have a dictionary that looks like this:
d = {name: 'A', 'numbers': array([2.72, 3.74, 1.75])}

And I need to create a Pandas DataFrame from this dictionary. I am currently using df = pd.DataFrame.from_dict(d)
However, the DataFrame looks like this:
name    numbers
  A      2.72
  A      3.74
  A      1.75

I tried using df = pd.DataFrame(d), but got the same result.
As I have arrays of numbers that contain more than a thousand values, there's a lot of duplicated info in the DataFrame, not really useful for my intended purpose.
I would like to have a DataFrame like this one:
name    numbers
  A      "[2.72, 3.74, 1.75]"

A: This would do:
pd.DataFrame({k:[v] for k,v in d.items()}).astype(str)

Output:
  name             numbers
0    A  [2.72, 3.74, 1.75]


text:
Q: Which are the different ways to deploy clojure web apps? There is a lot of infomation scattered throughout the internet regarding this issue.
Can anyone give me an overview about clojure web app deployment? The differences between deployment in a standalone server vs a containerless aproach? The advantages and disadvantages among the different players such as Amazon's Elastic Beanstalk (EB), Heroku, Google App Engine, etc? Support for maven and lein?
Thanks!


text:
Q: node js set style css page and fill data? here is a list of folders and files i have
public__
         |_generate-todo.js
         |_index.js
         |_style.css
views__
         |_404
         |main
users-data.json
server.js

Problem 1: I have done with view now i want to assign public folder style sheet and js files to my main handlebar page to generate better layout
problem 2: I have to fill my main handle drop down select list with json data in  user-data.json file
what i done:
   var path = require('path');
   var express = require('express');
   var exphbs = require('express-handlebars');

   var app = express();
   var usersData = require('./users-data');
   var port = process.env.PORT || 3000;

   // Use Handlebars as the view engine for the app.
   app.engine('handlebars', exphbs({ defaultLayout: 'main' }))
   app.set('view engine', 'handlebars');

   // Define the port to run on
    app.set('port', 3000);

   app.get('/', function (req, res) {
   res.render('index-page');
   });

    app.use(function(req, res) {
      res.redirect('404-page');
     });

    var server = app.listen(app.get('port'), function() {
    var port = server.address().port;
        console.log('Magic happens on port ' + port);
    });

anybody help me with these problems

A: The following answer relates to a previous version of the question.
Here you can see the original question
Solution Problem 1:
You have to serve your /public folder with express.
You can do it with the following code:
app.use(express.static(path.join(__dirname, '/public')));
Then you can add your css an js files from your public directory as usual. (Don't use /public in your href or src statement.)
So you can add this to your html file(s):
<link rel="stylesheet" href="/style.css" type="text/css">
<script src="/index.js" type="text/javascript"></script>
<script src="/generate-todo.js" type="text/javascript"></script>

Lookup express.static() docs for reference: express.static() documentation
Solution Problem 2:
You have already a require statement for your json file in your server.js:
var usersData = require(./users-data.json);

You can pass it to your template in the res.render() method:
// pass a local variable to the view
res.render('your-template', { usersData: usersData });

Now you can use it as usersData in your template on your dropdown-select. (e.g. {{ usersData.something }})
See express.js res.render() documentation for reference.


text:
Q: ReactJS syntax error: unexpected token '<' I was following a course on udemy on react components and I was met with this
Syntax error.
I have the following dependencies installed using yarn:
   "dependencies": {
    "babel-preset-env": "1.5.2",
    "babel-preset-react": "6.24.1"
    }
Here's myJSX file:

class Header extends React.Component {
    render() {
        return
This is from header
;
    }
}

const jsx = (

Title

);

ReactDOM.render(jsx, document.getElementById('app'));

I am using this command to convert this to the main JS file:
babel src/app.js --out-file=public/scripts/app.js --preset=env,react --watch

Please let me Know what I am doing wrong here

A: Not 100% that this helps, but as stated in babel docs you should use presets instead of preset
babel script.js --presets react

So your full babel command:
babel src/app.js --out-file public/scripts/app.js --presets env,react --watch


text:
Q: node.js + express.js + dust.js issues The quick question: why won't express.js run with dust.js?
I know it's not officially supported, but dust.js even has issues with my node.js version.
Node won't even start due to require.path issues.
server:testapp treejanitor$ node --version
v0.6.12

I get issues when setting the app engine to dust. (app.js in express)
var dust = require('dust');
...
app.set('view engine', 'dust');

I'm showing the console here to give you my simple list of modules.
Also someone searching for the same problem might cut/paste the error.
server:hummr treejanitor$ npm list
application-name@0.0.1 /Users/treejanitor/git/testapp/testapp
├── consolidate@0.3.0  extraneous
├── dust@0.3.0
├─┬ express@2.5.8
│ ├─┬ connect@1.8.7
│ │ └── formidable@1.0.9
│ ├── mime@1.2.4
│ ├── mkdirp@0.3.0
│ └── qs@0.4.2
└─┬ jade@0.25.0
  ├── commander@0.5.2
  └── mkdirp@0.3.0

server:testapp treejanitor$ supervisor app.js

DEBUG: Error: require.paths is removed. Use node_modules folders, or the NODE_PATH environment variable instead.
    at Function.<anonymous> (module.js:378:11)
    at Object.<anonymous> (/Users/treejanitor/git/testapp/testapp/node_modules/dust/lib/server.js:6:8)

I tried the following attempt with no luck:
Dust.js load template from filesystem in Node.js
NOTE: I tried the alpha version of express (3.0) which didn't help.
Same goes for consolidate.js and all the modules in that example.

Some reasons why I am interested in node + express + dust:
LinkedIn picks dustjs
Twitter's Bootstrap framework

A: I once discussed about setting up Dust.js with Express@3.0 on Node.js 0.6.x through the consolidate.js module. You can read it here
However, you may want to use LinkedIn's fork of Dust.js, which supports Node.js 0.6.x out of the box with other improvements.
Consolidate.js already supports that fork, but you still need Express@3.0 to work.

A: So here's the trick - I thought I'd share what I found.
It required finding this nugget - search for dust-x in the page if you're interested.
http://nodejs.debuggable.com/2012-03-23.txt
To resolve things, in your express app
cd node_modules
git clone git://github.com/laurie71/dust-x.git
git clone https://github.com/caolan/dustjs.git

The fork of dust.js resolving the require.paths issue with node.js
https://github.com/caolan/dustjs
The 'wrapper' of dust making it available as a template engine
(You'll still need dust.js installed as a module)
https://github.com/laurie71/dust-x
The example usage
https://gist.github.com/2174537
Most important bit:
var dustx = require('dust-x');

...

// Configuration

app.configure(function(){
    app.set('views', __dirname + '/views');
    app.register('.dust', dustx/*({})*/);
    app.set('view engine', 'dust');
    // app.set('view engine', 'jade');
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(app.router);
    app.use(express['static'](__dirname + '/public'));
});

Btw, I think I could have manually fixed the dust.js issue inside its server.js but I wanted to give kudos to the person who actually forked dust.js and made the solution publicly available.

PS: I'm still fairly new to posting on stackoverflow, so if I've breached some etiquette just let me know. I read in the FAQ that answering your own questions is encouraged, so I thought I'd give it a try.
In particular, I know my formatting is probably weak.  In the answer, I actually preferred showing the full link rather than the guide-suggested URL embedding because it reveals structure of the containing sites.  With the site URL soaked up in your brain, it gives you more opportunity to the site as reference the next go-around. Also the URLs were reasonably short. ;^) Suggestions are greatly appreciated.
What is the way a 'console' is typically formatted?  As code?

A: It could be an issue with node.js  and express.js versions..I am using node v0.10.9 and express v3.0.x  and they work well for me.
For integrating dust.js with express.js and node.js, I found this github repo to be a useful resource to help you get started with:
https://github.com/chovy/express-template-demo
(It uses the linkedin fork of dust.js)


text:
Q: Is it possible to use linear-gradient on top of a landing image in react? I am wishing to add a gradient to a landing page image.
I see examples in CSS using background (Example) but I am curious if it is possible to add it inline.
I appreciate any critiques, thank you!
import React from 'react';
import city from '../images/city-buildings.jpg'

function Home() {
  return (

      <img
        src={city}
        alt="city buildings looking up"
        width="100%"
        height="100%"
        backgroundImage="linear-gradient(to right, #4880EC, #019CAD)".  <------------- this line
      />

  );
}

export default Home;

A: To apply a linear gradient over an image this code worked for me:
Component
import React, { Component } from 'react';
import city from '../images/city-buildings.jpg'

const style = {
  width: '100%',
  height: '100%',
  opacity: '0.8'
}

export default class MyComponent extends Component {
  render() {
    return (

    )
  }
}

Component.css
.home {
  background: linear-gradient(#e66465, #9198e5);
}


text:
Q: JavaScript String object is being split into an array on jQuery.post I'm using jQuery to do ajax calls - many of which are working fine, but I've just run into an odd problem trying to send a string to the server. I've narrowed the code down to just this:
var x = new String('updateGroup');
var y = 'updateGroup';
$.post('page.aspx', {
    f: x,
    f2: y
}, function(data) {
});

When it hits the server however, the request variables are as follows:
Request["f"]          null          string
Request["f2"]         "updateGroup" string
Request.Form.AllKeys  {string[12]}  string[]
  [0]                 "f[0]"        string
  [1]                 "f[1]"        string
  [2]                 "f[2]"        string
  [3]                 "f[3]"        string
  [4]                 "f[4]"        string
  [5]                 "f[5]"        string
  [6]                 "f[6]"        string
  [7]                 "f[7]"        string
  [8]                 "f[8]"        string
  [9]                 "f[9]"        string
  [10]                "f[10]"       string
  [11]                "f2"          string

where Request["f[0]"] contains "u" etc.
Can someone explain why this happens?

A: If you throw away all details, what's being executed in your case is:

*

*jQuery.post

*which calls jQuery.ajax internally to do the ajax

*which calls jQuery.param internally to build the query string

The point is that new String is not a primitive string but a string object, and will pass the following check in jQuery.ajax (typeof new String("foo") === "object", not "string"):
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
    s.data = jQuery.param( s.data, s.traditional );
}

jQuery.param is executing as follows:
for ( var prefix in a ) {
    buildParams( prefix, a[ prefix ], traditional, add );
}

This means it does a for in loop over the string, which indeed puts each character separately in the query string.
You can check this behaviour with this testcase:
var x = new String("abc");

for(var i in x) {
    console.log(i, x[i]);
}

// 0  "a"
// 1  "b"
// 2  "c"

A: When you use new String you create a string object rather than a string itself, if you run this in your browser you will see they're an object and a string respectfully:
console.log(typeof new String("hello"));
console.log(typeof "hello");

More information here (including why you can an array of characters posted to the server):
http://www.devguru.com/technologies/ecmascript/quickref/string.html

A: JavaScript distinguishes between a literal string and an object of type String.
I suspect that when the jQuery post method is inspecting the data object you have sent it, it checks if the typeof each value is string. If it is, its job is done. If it finds an Object (which a String is) it iterates over it - which is why you're getting an array of characters.
if you have a String object you can use String.valueOf() to get the primitive value

A: You should never create a string like this in javascript, it's considered a bad practice:
 var x = new String('updateGroup');

but always like this
 var x = 'updateGroup';

because in the first case you create an object and only in the second case you create a string. The same goes for arrays, always use
 var array = [];


text:
Q: Select some line in Powershell GET-ADUser I need a help
i'm trying to make a script that capture the result of a "GET-ADUser" cmdlet, to put in a variable, but something goes wrong..
The code i'm using:
$Name = (Get-ADUser -Identity UserName | FT GivenName)

But has result, i recieve:
PS C:\> $Name

GivenName
---------
Bruno

Anyone knows how i catch only the name on this?
Thanks.

A: You would use the following format to select one particular property to be returned from the object and saved to your $name variable.
$name = (Get-ADUser -Identity UserName).GivenName


text:
Q: Class generator definition Why does inspect.isgenerator() return false for this class generator definition (working in python 3.7)?
I know that isgenerator is checking weather the object is of type
"generator"

and my class is of type
"__main__.generator"

which I don't know why. How do I make it of type "generator"? (I need this because of some other 3rd library which is checking this).
class generator(object):
  def __init__(self):
    pass
  def __getitem__(self, index):
    return [0,0]

  def __iter__(self):
    return self

  def __next__(self):
    return [0,0]

  def next(self):
      return self.__next__()

a = generator()

import inspect
print(inspect.isgenerator(a))
print(type(a))

thanks for help!

A: "Generator" is a specific built-in type, and your type will never be that type, no matter what methods you implement or what name you give it. You cannot make instances of your class be actual generators. (Not even through subclassing - the real generator type cannot be subclassed.) Also, generators have send and throw methods used for coroutine functionality, but it doesn't make sense for your class to have those, and implementing them still won't make your objects pass inspect.isgenerator.
inspect.isgenerator is intended to check for an actual generator, not arbitrary iterators or objects mimicking generators.
If the third-party library you're using needs a real generator, you will have to give it an actual generator, by writing and calling a generator function, or by writing a generator expression.
If the third-party library doesn't actually need anything generator-specific, you could file an issue asking that they switch to a less restrictive check than inspect.isgenerator.

A: Generator cant be subclassed. If you just want to pass the test inspect.isgenerator add to your class:
import types
class generator(object):
    ...
    @property
    def __class__(self):
        # maybe condition with caller
        return types.GeneratorType

...
print(inspect.isgenerator(a)) # True


text:
Q: SetOptions not persistent between sessions Let's say I decide I want all my axes to be colored red, so I do
SetOptions[Plot,AxesStyle->Red]

For the remainder of my session, I correctly get
Options[Plot,AxesStyle]
(* {AxesStyle->Red} *)

But when I quit and subsequently reload MMA, I get
Options[Plot,AxesStyle]
(* {AxesStyle -> {}} *)

For how long are changes made by SetOptions supposed to persist? I (apparently incorrectly) understood that these changes were supposed to persist across sessions (i.e., permanent). I thought if you wanted such changes to persist only for the current session, you needed to use something like $FrontEndSession.

A:
For how long are changes made by SetOptions supposed to persist?

Normally, SetOptions is used with functions (see here). In this case changes do not persist across kernel restarts.

I (apparently incorrectly) understood that these changes were supposed to persist across sessions (i.e., permanent).

No, that is not the case, except in special situations.

I thought if you wanted such changes to persist only for the current session, you needed to use something like $FrontEndSession.

SetOptions[$FrontEnd, ...] does indeed persist between restarts. This is a special case though. The same applies to using SetOptions with cell or notebook references: the cells/notebooks are modified, and if you then save them, the changes become permanent.
This use of SetOptions in my mind is completely distinct from setting options for functions, it just happens to have the same syntax.


text:
Q: asp.net mvc viewmodel entity has no key Error when trying to create view from controller I have ViewModel class in ASP.NET-MVC application and when I am trying to create view --> to detail the records. I am getting error that entity don't have primary key. I have test invidual model classes and they are working fine, I am not what I am missing here...
ViewModel class
public class RentingApplicationsViewModel
{
    public RentingApplicationsViewModel() {

        _PropertyRentingApplicationModel = new PropertyRentingApplication();
        _PropertyTypeModel = new PropertyType();
    }

    public PropertyRentingApplication _PropertyRentingApplicationModel { get; set; }
    public PropertyType _PropertyTypeModel { get; set; }

}

Model class
[Table("PropertyRentingApplication")]
public class PropertyRentingApplication
{
     public PropertyRentingApplication() { }

     [Key]
    // [Column(Order = 0)]
     [Display(Name = "Application ID")]
     public int ApplicationID { get; set; }

     //[Key]
     //[Column(Order = 1)]
     [Display(Name = "Property Type ID")]
     [Required(ErrorMessage = "Require Property Type ID")]
     public int PropertyTypeID { get; set; }

     //[Key]
     //[Column(Order = 2)]
     [Display(Name = "Student ID")]
     [Required(ErrorMessage = "Require Student ID")]
     public int StudentID { get; set; }

     [Display(Name = "Application Reference")]
     [MaxLength(150)]
     public string ApplicationReference { get; set; }

     [Display(Name = "Date Of Application")]
     [Required(ErrorMessage = "Require Date of Application Been Submitted")]
     public System.DateTime DateOfApplication { get; set; }

     [Display(Name = "Secure Entire Property")]
     [Required(ErrorMessage = "Require Information on If You Want to Secure Entire Property")]
     public bool SecureEntireProperty { get; set; }

     [Display(Name = "Application Status")]
     [MaxLength(50)]
     [Required(ErrorMessage = "Require Application Status")]
     public string ApplicationStatus { get; set; }

     public PropertyType PropertyType { get; set; }
     public Student Student { get; set; }

     public ICollection<AdditionalTenant> AdditionalTenants { get; set; }

}

....
[Table("PropertyType")]
public class PropertyType
{
     public PropertyType() { }

     [Key]
     [Display(Name = "Property Type ID")]
     public int PropertyTypeID { get; set; }

     [Display(Name = "Property Type")]
     [MaxLength(250)]
     [Required(ErrorMessage = "Require Property Type i.e. Flat, House, Studio")]
     public string Type { get; set; }

     [Display(Name = "Title")]
     [MaxLength(250)]
     [Required(ErrorMessage = "Require Property Type Title")]
     public string Title { get; set; }

     public ICollection<Property> Properties { get; set; }
     public ICollection<PropertyRentingPrice> PropertyRentingPrices { get; set; }

}

A: Are you connecting to the Default context that includes Identity classes, If so the scaffolding is looking at every class in the identity context, You should try and create a new context for your class or you can place [key] above the user guid.


text:
Q: unable to import nvd3 guage chart JS file I need to implement guage chart and I am using NVD3 for that.
https://github.com/enplore/nvd3-charts
I tried to import js files mentioned in above link
but getting the following error,
GET http://[ip]/nodejs/bower_components/nvd3/build/gaugeChart.js


text:
Q: Heavy tail central limit theorem I am looking for a proof based on characteristic functions for the generalized central limit theorem when the second moment does not exist, in which case one ends up with a power law rather than a Gaussian state.
This Theorem is described on the wikipedia page of the CLT click me
but unfortunately there is no modern reference to this result given.

A: Welcome to MO! This theorem is e.g. Theorem 14 on page 91 of Petrov's book, with further references to [24], [50].


text:
Q: How to make full screen html background video for half page? How to make html background video for half page?
.video {
    position: fixed; no-repeat;
    top: 50%; left: 50%;
    z-index:-1000;
    min-width: 100%;
    min-height: 100%;
    width: auto;
    height: auto;
    transform: translate(-50%, -50%);
}

I use this code for full background video but I want only for the header section.

A: try to change the height value to 50% and delete the top:50% :
{
position: fixed; no-repeat;
left: 50%;
z-index:-1000;
min-width: 100%;
min-height: 100%;
width: auto;
height: 50%;
transform: translate(-50%, -50%);
}


text:
Q: TeXnicCenter not working with Acrobat Reader Even after updating to R20 in the PDF section, TeXnicCenter is not opening Acrobat Reader. I'm using Adobe Acrobat Reader DC version 2020.013.20074. The old trick does not seem to work.

A: I have the Acrobat Pro DC version 21 (not acrobat reader). In order to find the version of the server I looked at the following registry entry:
HKEY_LOCAL_MACHINE \Software\Classes\acrobat\shell\open\ddeexec\application
In my case I found that the server was AcroViewA21. Also in my case the executable that I was calling was the "Acrobat.exe", and not the "AcroRd32.exe".
It worked perfectly.

A: To confirm the previous answer, after my Adobe Acrobat automatically updated to 64 bit my TeXnicCenter failed to view - it hung. I changed the viewer comand line to that which appears in the Adobe icon properties target, which uses Acrobat.exe rather than AcroRd32.exe. This still failed to view, but did when I changed the viewer from AcroViewR21 to AcroViewA21 as suggested in Answer 1. Thank you very much Answer 1.

A: New version of Adobe Reader was released and new server version is required.
Adobe Acrobat Reader DC
Continuous Release Version 2022.001.20085 64Bit
Executable: Acrobat.exe
Server version: AcroViewA22


text:
Q: How to solve the integral $\int\frac{x^2-1}{(x^2+1)\sqrt{x^4+1}}\,dx$ .
$$\large \int \frac{x^2-1}{(x^2+1)\sqrt{x^4+1}}~dx$$

In this I tried to substitute $x^2 +1$ by $t$.
after that got stuck.

A: HINT:
$$x^2-1=x^2\left(1-\dfrac1{x^2}\right)$$
As $\displaystyle\int\left(1-\dfrac1{x^2}\right)dx=x+\dfrac1x$
write
$$x^2+1=x\left(x+\dfrac1x\right)$$
$$x^4+1=x^2\left(x^2+\dfrac1{x^2}\right)\implies\sqrt{x^4+1}=|x|\sqrt{x^2+\dfrac1{x^2}}$$
Finally $ x^2+\dfrac1{x^2}=\left(x+\dfrac1x\right)^2-2$