text:
Q: Still showing merge conflicts even after I pushed the fixes I merged my master branch into my uat branch using the git merge --squash master command and I resolved all the conflicts and pushed my changes into the repo. Now, no one has touched the uat branch since I merged but when I run a git merge --squash master in my uat branch, I still see the same conflicts even though I fixed those conflicts and pushed them.

A: This is normal.
The problem is that git merge --squash is what one might call a terminal action on a branch: after doing git merge --squash branch, you should1 delete the branch, git branch -D branch, or at least rename it to a "don't work on this any more" name: git branch -m branch dead-branches/branch for instance.

1"Should" here is a value judgement.  There's no technical requirement, and you might have offsetting reasons for keeping the branch: you just need to know what Git is doing and what it means to keep the branch.

Real merges
It's worth looking at what a normal (non-squash) merge does, before considering a squash "merge", to see why I put the word merge in quotes for the --squash case.  Git's git merge is about combining work, and the mechanism it uses is to find a common starting point.  This is a commit—ideally one single commit, the commit—that is on both branches, closest to the tip of each branch.  If we draw them the way I like to, the branch names and commits look like this:
     C--D--E   <-- mainline (HEAD)
    /
A--B   [common starting point]
    \
     F--G--H   <-- branch

where the main line branch that you have checked out—denoted by the word HEAD attached to the branch name mainline—means, in effect, "commit E".  Commits A through E are all on that branch, because Git starts at E and works backwards: E's parent is D; D's parent is C; C's parent is B; B's is A.  (A is the very first commit ever made so it has no parent: it's a root commit.  This is not important here, but worth mentioning since the first commit you ever make in a new repository is one of these root commits, and usually the only one.)
Meanwhile, the other branch branch really means "commit H".  Commits A, B, and F through H are all on branch branch.
Note that commit B is on both branches!  It's the commit that's "nearest" to the two tip commits, E and H, so it is the merge base.
A true merge starts by finding the merge base, given the tip commits.  Git then, in effect, compares the contents saved as the merge-base snapshot—what you'd get if you git checkout <hash-of-B>—to the contents of the current commit E:
git diff --find-renames <hash-of-B> <hash-of-E>   # what we did

It repeats this with the base and your other branch tip:
git diff --find-renames <hash-of-B> <hash-of-H>   # what they did

This is the work that Git should combine.  If you changed three files that they didn't change at all, Git should apply your changes to the base.  If they changed some files that you didn't change at all, Git should apply their changes to the base.  Where you and they both touched the same files, Git should combine those changes, if it can, making sure that if you both made exactly the same change, Git takes only one copy of that change.
Applying the combined changes to the base gives a new snapshot (or has merge conflicts; then Git normally stops and makes you clean up the mess).  Assuming all has gone well, Git commits the new snapshot, setting its first parent to your current commit, and its second parent to the other commit:
     C--D--E
    /       \
A--B         I   <-- mainline (HEAD)
    \       /
     F--G--H   <-- branch

Let's redraw this in a less bendy fashion:
A--B--C--D--E--I   <-- mainline (HEAD)
    \         /
     F---G---H   <-- branch

The merge commit I is on only one branch, in this case the main-line branch.  Let's check out the side branch branch and do more work on it now:
A--B--C--D--E--I   <-- mainline
    \         /
     F---G---H--J--K   <-- branch (HEAD)

If we git checkout mainline (to attach our HEAD there) and run git merge branch, Git now must find, once again, the best commit that's on both branches.  We start at K for the side branch, then look at J, then at H.  Meanwhile we start at I for the main-line, then look at both E and H simultaneously.  Commit H is in our list of side-branch commits, so it's the one closest to both branches: it's the new merge base.
Git will now combine our changes with their changes.  These changes are:
git diff --find-renames H I   # what we did
git diff --find-renames H K   # what they did

Note that Git isn't starting from B this time: the merge base is now H, because of merge commit I.
Assuming all goes well, Git makes a new commit with the combined changes applied to whatever is in H:
A--B--C--D--E--I-----L   <-- mainline (HEAD)
    \         /     /
     F---G---H--J--K   <-- branch

and we are all done.
Squash "merges"
Now let's see what a git merge --squash does, starting with the same thing we had originally:
A--B--C--D--E   <-- mainline (HEAD)
    \
     F---G---H   <-- branch

Git does the same merge-base finding, and the same combining.  I like to refer to this as merge as a verb: it's the action of finding a merge base, getting two git diffs, and combining the results.
But the next step, when all has gone well, is different.  Instead of making a merge commit—merge as an adjective, modifying commit, meaning a commit with two (or more) parents—Git makes a commit with just one parent.  Well, in fact, it stops entirely, as if you ran git merge --no-commit, but when you finish the process by running git commit, that makes an ordinary, non-merge commit I:
A--B--C--D--E--I   <-- mainline (HEAD)
    \
     F---G---H   <-- branch

New commit I has the same effect as combining the three commits F-G-H and applying them to the contents of E: content-wise, it's what you would get if you did a git rebase -i master while on branch and changed the last two pick commands to squash.  But it's not a merge commit!  It's not a merge-as-an-adjective, even though it did the merge-as-a-verb action.
So, if you now git checkout branch and make more commits and then switch back to the main line, what you have now looks like this:
A--B--C--D--E--I   <-- mainline (HEAD)
    \
     F---G---H--J--K   <-- branch

and if you now ask Git to merge the two branches, Git starts by finding the merge base.  The merge base is the first commit that's on both branches, and since I is not a merge commit, that's commit B again.
Note that I has all the changes from F-G-H in its contents (because we made it by merge-as-a-verb-ing), but Git has no idea, so this next merge has to look at B vs H, which means putting in everything from F-G-H again.
If Git was able to resolve all the conflicts on its own last time, it might be able to resolve all the conflicts on its own this time, too.  This new merge-as-a-verb, whether or not we use --squash, may be able to do everything automatically.  If Git had to stop and get help last time, though, chances are it will have to stop and get help this time too: many of the same conflicts will occur.  They may even be worse, depending on what we did when we resolved them to make commit I.
The normal solution is that when we do the git merge --squash and make commit I, we throw away the side branch entirely:
A--B--C--D--E--I   <-- mainline (HEAD)

If we want to make more changes, we make a new side branch:
A--B--C--D--E--I   <-- mainline, branch2 (HEAD)

and then make new commits on it:
A--B--C--D--E--I   <-- mainline
                \
                 J--K   <-- branch2 (HEAD)

Commits F through H are abandoned (and soon-ish, gone for real, especially if we delete the name branch, as this also deletes the reflog for branch; this reduces any remaining commit-protection to just the 30 days for "unreachable" commits in the HEAD reflog).  We don't need or want them any more, though: those three old dull snapshots are now represented as commit I's single snapshot instead.


text:
Q: Twig, error on compare date If I try to compare date as this:
{% if (expireDate==NULL) %}
    {% if (date(expireDate) < date()) %}
        DANGER!
    {% elseif (date(expireDate) == date()) %}
        WARNING
    {% else %}
        DON'T WORRY
    {% endif %}
{% endif %}>

I assume that date() without params return the current date, and expireDate has a Date value.
My problem is that "WARNING" never been shown, and this mean that even if expireDate is today the (date(expireDate) < date()) is always false.
Am I doing something wrong?
UPDATE#1
This should works, but I don't know if it's correct.
{% if (expireDate==NULL) %}
    {% if (date(expireDate)|date('d-m-Y') < date()|date('d-m-Y')) %}
        DANGER!
    {% elseif (date(expireDate)|date('d-m-Y') == date()|date('d-m-Y')) %}
        WARNING
    {% else %}
        DON'T WORRY
    {% endif %}
{% endif %}>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Template ASP.NET Core Web Application does not exist in New Project I install visual studio 2015 with update 3 and after that I install  NET Core for Visual Studio Official MSI Installer , now when I want create new Project I dont have ASP.NET Core Web Application in .NetCore tab.

what's problem ?

A: You have to install the Microsoft ASP.NET and Web Tools from https://visualstudiogallery.msdn.microsoft.com/c94a02e9-f2e9-4bad-a952-a63a967e3935
Then you find your template in Template/Visual C#/Web.


text:
Q: Weird behavior in bashrc: concatenate, same code run/fail I have a VM with CentOS 6 and I am loading some scripts from bashrc.
Everything worked fine, but I wanted to copy-paste the same code and scripts in an older backup of same VM, but I got an error: "unexpected end of file". Also the same error had to deal another person when I wanted to share those scripts with him (he had the same VM).
So I started to debug a little and found that one row he didn't liked it was (it was parsing an array:
COUNTER=1
while [[ ! -z ${SCRIPT[$COUNTER]} ]]; do

Also he didn't liked this either (it's not exactly the same with "while" logic, but it does the job):
for i in ${Script[@]}; do

So, I replaced it with:
for ((i = 0; i < ${#SCRIPT[@]}; i++)); do

Now I tryed to get the error name with same piece of code and no more errors occurred.
Also I have this behavior which is the weirdest from all:
Code:
BASH_SCRIPTS_LOCATION='/mnt/hgfs/Shared-workspace/scripts/'
SCRIPT[0]='aliases.sh'
SCRIPT[1]='scripts_config.sh'
SCRIPT[2]='credentials.sh'
SCRIPT[3]='other_functions.sh'
SCRIPT[4]='ssh_functions.sh'
SCRIPT[5]='release_functions.sh'
SCRIPT[6]='test_functions.sh'
for ((i = 0; i < ${#SCRIPT[@]}; i++)); do
    loadedScript=${BASH_SCRIPTS_LOCATION}${SCRIPT[$i]}
    echo -e "$loadedScript"
done

Terminal output (seems the "concatenate" it is replacing the characters starting from the begging of first String/variable :
aliases.shShared-workspace/scripts/
scripts_config.shworkspace/scripts/
credentials.shed-workspace/scripts/
other_functions.shorkspace/scripts/
ssh_functions.sh-workspace/scripts/
release_functions.shkspace/scripts/
test_functions.shworkspace/scripts/

I think I am using something very inappropriate. But I am not sure what or what I should be looking for.
Any recommandation or advice is welcome.
Thanks!

A: It doesn't show here but your script has carriage return chars in the shell definition lines. Edit them out (using Notepad++ for instance or tr -d "\015" < yourscript.sh > newscript.sh)
You can redirect your script to a file you'll see all the text in the file.
Carriage return char (asc 13, \r) just resets the cursor without skipping to newline. Every text written after that overwrites the text in the current line. Windows uses that to complement the linefeed character. Windows text mode is like that


text:
Q: CSS - Easy way for Containing Floats I read many articles about problems of Containing Floats on websites.
There is also many guides (like this) that explain how to fix some issues about this.
What I would like to know is : what about this easy code?
.maindiv{width:980px; margin:0 auto;}

I tried on many browsers, and looks that it ALWAYS works. So whats the problem with this? I also try with (for example) :
.maindiv{width:980px; margin:0 auto; background-color:#000099;}

and seems that, although main container got a background-color, the within div (floated) doesnt get any problems.
Im just curios :)

A: There is no problem with this isolated piece of code, but it will give you problems if you try to give it a background and then insert some floating children.

A: .maindiv{width:980px; margin:0 auto;} accomplishes something rather different. An element with an explicit width declaration and a auto left and right margin causes that div to be centered.
It most definitely does NOT solve the containing floats issue.
See http://jsfiddle.net/aPmu5/


text:
Q: Finding intersection of two arrays I'm having trouble finding what's wrong with my code - at first I thought I was finished, but then I found some issues. I am creating a function called bagIntersection that takes two bag objects and finds common items in both, and then places them into a new bag:
For example, if bag has items {"b", "b", "c"} and bag2 has items {"b", b", "d", "e"}, the function call:
ArrayBag<std::string> resultBag = bag.bagIntersection(bag2);

should only return string "b" in the resultBag. My function bagIntersection is returning {"b","b"} into the resultBag. So somehow I'm getting multiples of "b".
(code removed) The code was correct.

A: If you want to remove duplicate you can do like this with a vector container for example :
std::sort(v.begin(), v.end());
v.erase(std::unique(v.begin(), v.end()), v.end());

and you will have only one "b".


text:
Q: Ibus anthy - removing given input modes For the Anthy engine in Ibus, you can press Ctrl + , to switch between entering text with hiragana, full width katakana, half width katakana, normal width latin and wide latin.
I want to remove some of these (e.g. the half width katakana option and the wide latin option) as I never use them and it makes cycling between the ones I need slower. I have looked into the Ibus anthy settings but could not find anything. Searching AskUbuntu also found nothing similar.
Note: I am using Ubuntu 14.04
How can this be done?

A: Select Anthy, then Preferences-Anthy. In the Setup window go to the Key Binding tab.

Normally the shortcut listed for "hiragana-mode", katakana-mode, etc. is [ ] for no shortcut.
Doubleclick on an item and you can add a shortcut key description. I used Ctrl+H and Ctrl+K (of course use whichever you want). Then you can use those keys directly to select the kana mode, rather than cycling through the options.


text:
Q: Linq to Entities Binding, Filtering and Editing in WinForms 1) Binding to The following populates a READ ONLY WinFrms grid:
    Dim query = (From profile _
              In db.profile _
              Where profile.employee.employeeId = employeeID _
              Select profile.description)

    Me.DataGridView.DataSource = profileQueryList

2) Binding to the entity itself makes the WinForms grid EDITABLE, but unfiltered:
    Me.DataGridView.DataSource = db.profile

I need something that combines the filtering feature of #1 with the editable feature of #2.

A: Try to use an explicit ToList() call.
Me.DataGridView.DataSource = query.ToList()

I guess that else only the expression tree of the query is bound and the entities are only fetched on demand.

A: Found the solution!  It's documented in:
Linq to Entities Filtering an Entity Dynamic/Strongly Typed

A: Don't bind directly to the queryable. Instead, you need to go through the EntityDataSource class. Note, especially, this article on how to filter data with this control.


text:
Q: No newline after (sub)section? I want my text to appear right after the call to \subsection{Name} but  I can't find how to do it. I'm using the article class.
An example of command:
\subsection{a)} Blah blah bla...

produces:

a)
Blah blah bla...

instead of what I want:

a) Blah blah bla...

Anything I could do?

A: I don't know of any way to do that with (sub)section headings, but have you considered the enumerate environment? If you're trying to make an ordered list, you can do:
\renewcommand{\labelenumi}{\alph{enumi})}
\begin{enumerate}
  \item Blah blah bla...
  \item Next one
  \item etc.
\end{enumerate}

and you would get something like

a) Blah blah bla...
b) Next one
c) etc.

A: Your specific example can be solved by using the enumerate environment (as mentioned by elcelista), but your general question can be answered by using the titlesec package.  The titlesec package defines the \titleformat command which allows any sectioning command to be easily redefined.  The syntax of the \titleformat command is
\titleformat{command}[shape]{format}{label}{sep}{before}[after]

To eliminate the newline after a subsection heading, put the following in the preamble for your document:
\titleformat{\subsection}[runin]{}{}{}{}[]

Here is an example document and its output:
\documentclass{article}
\usepackage{titlesec}
\titleformat{\subsection}[runin]{}{}{}{}[]

\begin{document}
\subsection*{a)}
Blah blah bla...
\end{document}

A: Just to add on the other answers, or maybe for other readers coming here:
If you just want some initial bold text, and suppress the newline, that is what \paragraph{My title} Here some text. would do. Also see here.
Maybe you also want to define your custom section type (\mysection{My title} ... or so). This would be via package titlesec and \titleclass command. See here for more.

A: I'm not entirely sure that I understand you problem. I am assuming that your a) is meant to be the subsection numbering, and that "Blah blah blah" is mean to be the title, and that you have not exhibited the text of the subsection at all.
Subsection are numbered (lettered?) automatically, the argument is the title:
 \subsection{Blah blah blah}
 Then the text of the subsection...

will generate something like:

3.1 Blah blah blah
Then the text of the subsection...

where the c)
To change the formatting of the subsection header, you either hack the class definition or choose a more flexible class (like memoir).


text:
Q: python: tkinter to display video from webcam and do a QR scan I have been trying to create a tkinter top level window that streams video form webcam and do a QR scan. I got this QR scan code from SO and another code that just updates images from webcam instead of streaming the video on a tkinter label.
and i tried to combine these both so that a toplevel window with a label updating image from webcam and a close button to close the toplevel window. And while it streams the images, it can scan for QR code and if a scan is successful, the webcam and the toplevel window gets closed.
here is what i tried.
import cv2
import cv2.cv as cv
import numpy
import zbar
import time
import threading
import Tkinter
from PIL import Image, ImageTk

class BarCodeScanner(threading.Thread, Tkinter.Toplevel):
    def __init__(self):
        # i made this as a global variable so i can access this image
        # outside ie,. beyond the thread to update the image on to the  tkinter window
        global imgtk
        imgtk = None
        threading.Thread.__init__(self)
        self.WINDOW_NAME = 'Camera'
        self.CV_SYSTEM_CACHE_CNT = 5 # Cv has 5-frame cache
        self.LOOP_INTERVAL_TIME = 0.2
        cv.NamedWindow(self.WINDOW_NAME, cv.CV_WINDOW_NORMAL)
        self.cam = cv2.VideoCapture(-1)
        self.confirm = 0

    def scan(self, aframe):
        imgray = cv2.cvtColor(aframe, cv2.COLOR_BGR2GRAY)
        # to show coloured image, as from the other code mentioned in the other code
        imgcol = cv2.cvtColor(aframe, cv2.COLOR_BGR2RGBA)
        imgcol_array = Image.fromarray(imgcol)
        imgtk = ImageTk.PhotoImage(image=imgcol_array)

        raw = str(imgray.data)
        scanner = zbar.ImageScanner()
        scanner.parse_config('enable')
        width = int(self.cam.get(cv.CV_CAP_PROP_FRAME_WIDTH))
        height = int(self.cam.get(cv.CV_CAP_PROP_FRAME_HEIGHT))
        imageZbar = zbar.Image(width, height,'Y800', raw)
        scanner.scan(imageZbar)

        for symbol in imageZbar:
            print 'decoded', symbol.type, 'symbol', '"%s"' % symbol.data
            return symbol.data

    def run(self):
        self.datalst = []
        print 'BarCodeScanner run', time.time()
        while True:
            for i in range(0,self.CV_SYSTEM_CACHE_CNT):
                self.cam.read()
            img = self.cam.read()
            self.data = self.scan(img[1])

            cv2.imshow(self.WINDOW_NAME, img[1])
            cv.WaitKey(1)
            time.sleep(self.LOOP_INTERVAL_TIME)
            if self.data:
                self.datalst.append(self.data)
            # i have added this section so that it waits for scan
            # if a scan is made it and if gets same value after 2 scans
            # it has to stop webcam
            if len(self.datalst) == 2 and len(set(self.datalst)) <= 1:
                # I want to close the webcam before closing the toplevel window
                #self.cam.release()
                #cv2.destroyAllWindows()
                break
        self.cam.release()

def Video_Window():
    video_window = Tkinter.Toplevel()
    video_window.title('QR Scan !!')
    img_label = Tkinter.Label(video_window)
    img_label.pack(side=Tkinter.TOP)
    close_button = Tkinter.Button(video_window, text='close', command = video_window.destroy)
    close_button.pack(side=Tkinter.TOP)

    def update_frame():
        global imgtk
        img_label.configure(image=imgtk)
        img_label.after(10,update_frame)
    update_frame()

def main():
    root = Tkinter.Tk()
    button_scanQr = Tkinter.Button(root, text='QR Scan', command=start_scan)
    button_scanQr.pack()
    root.mainloop()

def start_scan():
    scanner = BarCodeScanner()
    scanner.start()

    Video_Window()
    #scanner.join()

main()

Problem is,

*

*I actually wanted to display the video on the Toplevel window, not the OpenCV window

*at the same time do a QR Scan,if a read is sucessfull, the Toplevel window should close without abruptly closing webcam(because, when i try to use self.cam.release() or cv2.destroyAllWindows() my webcams lights or on even if i forcefully terminate the programs compilation).

Now what i get is a separate window created by OpenCV that streams video inside. But i don't want that window, instead i want the video to be displayed on the tkinter's toplevel window. also when there is a sucessfull read, the webcam stucks at the final image it reads.
i tried to remove the line that was responsible for OpenCV window, inside the run method of BarcodeScanner class
cv2.imshow(self.WINDOW_NAME, img[1])

it still showed up with a different window with no output, and if i try to close that window, it created another one similar and recursively.
UPDATE:
As i noticed i made some silly mistakes without understanding of some lines in cv2, i made some change on the code by adding the toplevel window code into the run method of the class(im not sure if this is a right way).
import cv2
import cv2.cv as cv
import numpy
import zbar
import time
import threading
import Tkinter
from multiprocessing import Process, Queue
from Queue import Empty
from PIL import Image, ImageTk

class BarCodeScanner(threading.Thread, Tkinter.Toplevel):
    def __init__(self):
        threading.Thread.__init__(self)
        #self.WINDOW_NAME = 'Camera'
        self.CV_SYSTEM_CACHE_CNT = 5 # Cv has 5-frame cache
        self.LOOP_INTERVAL_TIME = 0.2
        #cv.NamedWindow(self.WINDOW_NAME, cv.CV_WINDOW_NORMAL)
        self.cam = cv2.VideoCapture(-1)
        # check if webcam device is free
        self.proceede = self.cam.isOpened()
        if not self.proceede:
            return
        self.confirm = 0

    def scan(self, aframe):
        imgray = cv2.cvtColor(aframe, cv2.COLOR_BGR2GRAY)
        raw = str(imgray.data)
        scanner = zbar.ImageScanner()
        scanner.parse_config('enable')
        width = int(self.cam.get(cv.CV_CAP_PROP_FRAME_WIDTH))
        height = int(self.cam.get(cv.CV_CAP_PROP_FRAME_HEIGHT))
        imageZbar = zbar.Image(width, height,'Y800', raw)
        scanner.scan(imageZbar)
        for symbol in imageZbar:
            print 'decoded', symbol.type, 'symbol', '"%s"' % symbol.data
            return symbol.data

    def run(self):
        if not self.proceede:
            return
        def show_frame():
            _, img = self.cam.read()
            img = cv2.flip(img,1)
            cv2image = cv2.cvtColor(img, cv2.COLOR_BGR2RGBA)
            img = Image.fromarray(cv2image)
            imgtk = ImageTk.PhotoImage(image=img)
            img_label.imgtk = imgtk
            img_label.configure(image=imgtk)
            video_window.after(250, show_frame)

        def destroy_video_window():
            self.cam.release()
            video_window.destroy()

        # Toplevel GUI
        video_window = Tkinter.Toplevel()
        video_window.title('QR Scan !!')
        img_label = Tkinter.Label(video_window)
        img_label.pack(side=Tkinter.TOP)
        close_button = Tkinter.Button(video_window, text='close', command = destroy_video_window)
        close_button.pack(side=Tkinter.RIGHT)
        show_frame()

        self.datalst = []
        print 'BarCodeScanner run', time.time()
        while True:
            for i in range(0,self.CV_SYSTEM_CACHE_CNT):
                self.cam.read()
            img = self.cam.read()
            self.data = self.scan(img[1])
            time.sleep(self.LOOP_INTERVAL_TIME)
            if self.data:
                self.datalst.append(self.data)
            if len(self.datalst) == 2 and len(set(self.datalst)) <= 1:
                video_window.destroy()
                break
        self.cam.release()

def main():
    root = Tkinter.Tk()
    button_scanQr = Tkinter.Button(root, text='QR Scan', command=scaner)
    button_scanQr.pack()
    root.mainloop()

def scaner():
    scanner = BarCodeScanner()
    scanner.start()

main()

now, I can get the image on the Toplevel window, But i dont know how to close the webcam.
condition 1: when i show a QR code to scan, it reads it successfully and webcam quits without any error.
condition 2: when i click the close button on the toplevel window(say if user doesn't want to do any scan and just want to close the webcam) i get error saying
libv4l2: error dequeuing buf: Invalid argument
VIDIOC_DQBUF: Invalid argument
select: Bad file descriptor
VIDIOC_DQBUF: Bad file descriptor
select: Bad file descriptor
VIDIOC_DQBUF: Bad file descriptor
Segmentation fault (core dumped)

I am writing this application for Linux, Mac and Windows machine. How can i close or terminate the webcam safely.

A: Your program has two threads, the main thread and the worker thread that reads frames from the camera. When the close button is clicked, it happens in the main thread. After self.cam.release() the object self.cam is probably in an unusable state, and when a method of self.cam is called by the worker thread, there may be some trouble. Maybe the implementation of cv2.VideoCapture is faulty and it should throw some exception when that happens.
Accessing tkinter widgets from other thread than the main thread may also cause problems.
For clean program termination, creating an instance of threading.Event and then checking for event.is_set() at some point in the work thread could work. For example
def destroy_video_window():
    self.stop_event.set()
    video_window.destroy()

and then in the worker thread
while True:
    if self.stop_event.is_set():
        break
    for i in range(0, self.CV_SYSTEM_CACHE_CNT):
        self.cam.read()

There are several things that could be done in other way, the following is a modified version of the code. It avoids calling tkinter methods from other thread than the main thread, event_generate() being the only tkinter method called by the worker thread. Explicit polling is avoided by emitting virtual events, for example <<ScannerQuit>>, that are placed in the tkinter event queue.
import cv2
import cv2.cv as cv
import zbar
import time
import threading
import Tkinter as tk

from PIL import Image, ImageTk

class Scanner(object):
    def __init__(self, handler, *args, **kw):
        self.thread = threading.Thread(target=self.run)
        self.handler = handler

        self.CV_SYSTEM_CACHE_CNT = 5 # Cv has 5-frame cache
        self.LOOP_INTERVAL_TIME = 0.2
        self.cam = cv2.VideoCapture(-1)

        self.scanner = zbar.ImageScanner()
        self.scanner.parse_config('enable')
        self.cam_width = int(self.cam.get(cv.CV_CAP_PROP_FRAME_WIDTH))
        self.cam_height = int(self.cam.get(cv.CV_CAP_PROP_FRAME_HEIGHT))

        self.last_symbol = None

    def start(self):
        self.thread.start()

    def scan(self, aframe):
        imgray = cv2.cvtColor(aframe, cv2.COLOR_BGR2GRAY)
        raw = str(imgray.data)
        image_zbar = zbar.Image(self.cam_width, self.cam_height, 'Y800', raw)
        self.scanner.scan(image_zbar)

        for symbol in image_zbar:
            return symbol.data

    def run(self):
        print 'starting scanner'

        while True:
            if self.handler.need_stop():
                break

            # explanation for this in
            # http://stackoverflow.com/a/35283646/5781248
            for i in range(0, self.CV_SYSTEM_CACHE_CNT):
                self.cam.read()

            img = self.cam.read()

            self.handler.send_frame(img)

            self.data = self.scan(img[1])

            if self.handler.need_stop():
                break

            if self.data is not None and (self.last_symbol is None
                                          or self.last_symbol <> self.data):
                # print 'decoded', symbol.type, 'symbol', '"%s"' % symbol.data
                self.handler.send_symbol(self.data)
                self.last_symbol = self.data

            time.sleep(self.LOOP_INTERVAL_TIME)

        self.cam.release()

class ScanWindow(tk.Toplevel):
    def __init__(self, parent, gui, *args, **kw):
        tk.Toplevel.__init__(self, master=parent, *args, **kw)

        self.parent = parent
        self.gui = gui
        self.scanner = None

        self.lock = threading.Lock()
        self.stop_event = threading.Event()

        self.img_label = tk.Label(self)
        self.img_label.pack(side=tk.TOP)

        self.close_button = tk.Button(self, text='close', command=self._stop)
        self.close_button.pack()

        self.bind('<Escape>', self._stop)

        parent.bind('<<ScannerFrame>>', self.on_frame)
        parent.bind('<<ScannerEnd>>', self.quit)
        parent.bind('<<ScannerSymbol>>', self.on_symbol)

    def start(self):
        self.frames = []
        self.symbols = []

        class Handler(object):
            def need_stop(self_):
                return self.stop_event.is_set()

            def send_frame(self_, frame):
                self.lock.acquire(True)
                self.frames.append(frame)
                self.lock.release()

                self.parent.event_generate('<<ScannerFrame>>', when='tail')

            def send_symbol(self_, data):
                self.lock.acquire(True)
                self.symbols.append(data)
                self.lock.release()

                self.parent.event_generate('<<ScannerSymbol>>', when='tail')

        self.stop_event.clear()
        self.scanner = Scanner(Handler())
        self.scanner.start()
        self.deiconify()

    def _stop(self, *args):
        self.gui.stop()

    def stop(self):
        if self.scanner is None:
            return

        self.stop_event.set()

        self.frames = []
        self.symbols = []
        self.scanner = None
        self.iconify()

    def quit(self, *args):
        self.parent.event_generate('<<ScannerQuit>>', when='tail')

    def on_symbol(self, *args):
        self.lock.acquire(True)
        symbol_data = self.symbols.pop(0)
        self.lock.release()

        print 'symbol', '"%s"' % symbol_data
        self.after(500, self.quit)

    def on_frame(self, *args):
        self.lock.acquire(True)
        frame = self.frames.pop(0)
        self.lock.release()

        _, img = frame
        img = cv2.flip(img, 1)
        cv2image = cv2.cvtColor(img, cv2.COLOR_BGR2RGBA)
        img = Image.fromarray(cv2image)
        imgtk = ImageTk.PhotoImage(image=img)
        self.img_label.imgtk = imgtk
        self.img_label.configure(image=imgtk)

class GUI(object):
    def __init__(self, root):
        self.root = root

        self.scan_window = ScanWindow(self.root, self)
        self.scan_window.iconify()

        self.root.title('QR Scan !!')

        self.lframe = tk.Frame(self.root)
        self.lframe.pack(side=tk.TOP)

        self.start_button = tk.Button(self.lframe, text='start', command=self.start)
        self.start_button.pack(side=tk.LEFT)

        self.stop_button = tk.Button(self.lframe, text='stop', command=self.stop)
        self.stop_button.configure(state='disabled')
        self.stop_button.pack(side=tk.LEFT)

        self.close_button = tk.Button(self.root, text='close', command=self.quit)
        self.close_button.pack(side=tk.TOP)

        self.root.bind('<<ScannerQuit>>', self.stop)
        self.root.bind('<Control-s>', self.start)
        self.root.bind('<Control-q>', self.quit)
        self.root.protocol('WM_DELETE_WINDOW', self.quit)

    def start(self, *args):
        self.start_button.configure(state='disabled')
        self.scan_window.start()
        self.stop_button.configure(state='active')

    def stop(self, *args):
        self.scan_window.stop()
        self.start_button.configure(state='active')
        self.stop_button.configure(state='disabled')

    def quit(self, *args):
        self.scan_window.stop()
        self.root.destroy()

def main():
    root = tk.Tk()
    gui = GUI(root)
    root.mainloop()

main()


text:
Q: JSR-352 Java Batch: why does JobListener.afterJob() always get batch status STARTED? I'm a Java Batch newbie. I deployed a simple batch job that includes a JobListener on WebSphere Liberty 17.0.0.4 (note that I'm using IBM's JSR-352 implementation, not Spring Batch). The batch job itself runs as expected: it reads an input file, does a simple data transformation, and writes to a DB. But in the JobListener's afterJob() method for a successful execution, I see a batch status of STARTED and an exit status of null. (These are the same values I see logged in the beforeJob() method). I expected afterJob() to see a status of COMPLETED unless there were exceptions.
The execution id logged by afterJob() is the same value returned by JobOperator.start() when I kick off the job, so I know I'm getting the status of the correct job execution.
I couldn't find any examples of a JobListener that fetches a batch status, so there's probably a simple error in my JSL, or I'm fetching the batch status incorrectly. Or do I need to explicitly set a status somewhere in the implementation of the step? I'd appreciate any pointers to the correct technique for setting and getting a job execution's final batch status and exit status.
Here's the JSL:
<job ...>
    <properties>...</properties>

    <listeners>
        <listener ref="jobCompletionNotificationListener"/>
    </listeners>

    <flow id="flow1">
        <step id="step1">...</step>
    </flow>
</job>

Here's the listener's definition in batch.xml:
<ref id="jobCompletionNotificationListener"
     class="com.llbean.batch.translatepersonnames.jobs.JobCompletedListener"/>

Here's the JobListener implementation:
@Dependent
@Named("jobCompletedListener")
public class JobCompletedListener implements JobListener {
    ...
    @Inject
    private JobContext jobContext;

    @Override
    public void afterJob() {
        long executionId = jobContext.getExecutionId();
        JobExecution jobExecution = BatchRuntime.getJobOperator().getJobExecution(executionId);
        BatchStatus batchStatus = jobExecution.getBatchStatus();
        String exitStatus = jobExecution.getExitStatus();
        logger.info("afterJob(): Job id " + executionId + " batch status = " + batchStatus +
                ", exit status = " + exitStatus);
        ...
    }
}

I tried adding <end on="*" exit-status="COMPLETED"/> to the <job> and <flow> in the JSL, but that had no effect or resulted in a status of FAILED.

A: Good question.  Let me tack on a couple points to @cheng's answer.
First, to understand why we implemented it this way, consider the case where the JobListener throws an exception.    Should that fail the job?   In Liberty we decided it should.   But if the job already had a COMPLETED status, well, that would imply that it was... completed, and shouldn't be able to fail at that point.
So afterJob() is really more like "end of job" (or you could think of it as "after job steps").
Second, one reason to even ask this question is because you want to know, in the afterJob() method, whether the job executed successfully or not.
Well, in the Liberty implementation at least (which I work on, for IBM), you can indeed see this.   A previous failure will have set the BatchStatus to FAILED while a successful (this far) execution will have its status still at STARTED.
(For what it's worth, this was an area we realized could use more attention and standardization a bit late in the 1.0 spec effort, and I hope we can address more in the future.)
If it helps and you're interested, you can see the basic logic in the flow leading up to and including the WorkUnitThreadControllerImpl.endOfWorkUnit call here.

A: It's because job listener's afterJob method is part of the job execution.  So when you call getBatchStatus() inside afterJob() method, the job execution is still going on, and not yet completed, hence the batch status STARTED.


text:
Q: Using jQuery on external loaded DataTable after AJAX refresh So I have on my page a div with id="machine-content", which I use to display various info about my machines. Mainly, I display information in tables. I am trying to use DataTables (https://datatables.net/), but I have problem initializing the table. After click on action (i.e. "show me repairs", "show me workhours"), I load a table element from external html and fill it with data through AJAX according to chosen action.
So here's how my files look.
In index.php (jquery and datatables are loaded in head):

...

...

External html is super simple:

I then have data.js that controls index.php. There, I handle clicks to actions and loading of table through AJAX. All the data is loaded correctly but when I want to initialize a DataTable (to get search field, paging, etc.) it doesnt work. As far as I know, I have to initialise it after the data is loaded, anyway I also tried initialising it before. Here is data.js:
//EXAMPLE of handling chosen action with button click
//I TRIED putting //I TRIED putting $.('#example').DataTable(); HERE
//wrapped in $(document).ready

$('#arentals').click(function(){
            $( '#machine-content' ).load("/gui/machines/machines/templates/table.html", function() {
                load_service_table("RENTALS");
     });
});

function load_service_table(action){
    var action_url;

    switch(action) {
        case 'REPAIRS':
            action_url='/gui/machines/machines/show_services.php';
            break;
        case 'RENTALS':
            action_url='/gui/machines/machines/show_rentals.php';
            break;
        case 'REVENUES':
            action_url='/gui/machines/machines/show_revenues.php';
            break;
        default:
            action_url='/gui/machines/machines/show_hours.php';
    }

    $.ajax({
            url: action_url,
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            dataType: "html",
            type: "POST",
            success: function(data) {
                //I TRIED putting $.('#example').DataTable(); HERE
                $( '#machine-content-h1' ).text(action);
                $( '#example' ).html(data);
                //I ALSO TRIED putting $.('#example').DataTable(); HERE
            }
    });
    //AND HERE
}

PHP functions are simple and in AJAX return only head and body elements of table, so I guess there is no problem.
So my question is: How can I initialize this thing? I mean, if I am able to set html to #example in AJAX success function, why can't I initialise the same element there? Any help would be deeply appreciated.
EDIT
I always get this error:
jquery.dataTables.min.js:65 Uncaught TypeError: Cannot read property 'aDataSort' of undefined
SOLUTION
I only added $('#machine-content').find('#example').DataTable(); to AJAX success function which now looks like this:
$.ajax({
            url: action_url,
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            dataType: "html",
            type: "POST",
            success: function(data) {

                $( '#machine-content-h1' ).text(action);
                $( '#example' ).html(data);
                $('#machine-content').find('#example').DataTable();
            }
    });

A: datatable has a build-in ajax method
$('#myTable').DataTable( {
    ajax: '/api/myData'
} );

https://datatables.net/manual/ajax#Loading-data
or use:
$('#machine-content').find('.table').DataTable();

A: I know this post is older so probably of no help to you now but for anyone else who comes across this.
Something like the following should work:
var adminUsers = {

list: () => {

var action = 'list_users';
var url = base_url+'index.php/admin/users/io';
var data = { }

var response = ajaxRequest.post(action, url, data);

response.then(
    function(obj){
        var data = JSON.parse(obj);
        console.log(data);
        //console.log(data.data.result);
        $.each(data.data, function(i,e){
            var html = '';
            html = html + '
';
            html = html + ''+e.id+'	';
            html = html + ''+e.username+'	';
            html = html + ''+e.first_name+' '+e.last_name+'	';
            html = html + ''+e.status+'	';
            html = html + ''+e.locked+'	';
            html = html + ''+e.uuid+'	';
            html = html + '
';
            $('#users-list tbody').append(html);
        });

        $('#users-list').DataTable(adminUsers.dataTable());
    },
    function(jqXHR, textStatus, errorThrown){
        ajaxRequest.error(jqXHR, textStatus, errorThrown);
    });
},
dataTable: () => {
var config = {
        initComplete : function() {

            $("#users-list_filter").detach().appendTo('#search');
            $("#users-list_length").detach().appendTo('#display_length');
            $("#users-list_length").attr('style', 'margin-right:10px;');
            $("#users-list_filter input").addClass('form-control');

        },
        language: {
            search: "",
            searchPlaceholder: 'Search...'
        }
    }

    return config;
}

};


text:
Q: Python raw_input doesn't work after using subprocess module I'm using the subprocess module to invoke plink and run some commands on a remote server.  This works as expected, but after a successful call to subprocess.check_call or subprocess.check_output the raw_input method seems to block forever and doesn't accept input at the command line.
I've reduced it to this simple example:
import subprocess

def execute(command):
    return subprocess.check_call('plink.exe -ssh ' + USER + '@' + HOST + ' -pw ' + PASSWD + ' ' + command)

input = raw_input('Enter some text: ')
print('You entered: ' + input)

execute('echo "Hello, World"')

# I see the following prompt, but it's not accepting input
input = raw_input('Enter some more text: ')
print('You entered: ' + input)

I see the same results with subprocess.check_call and subprocess.check_output.  If I replace the final raw_input call with a direct read from stdin (sys.stdin.read(10)) the program does accept input.
This is Python 2.7 on Windows 7 x64.  Any ideas what I'm doing wrong?'
Edit:  If I change execute to call something other than plink it seems to work okay.
def execute(command):
    return subprocess.check_call('cmd.exe /C ' + command)

This suggests that plink might be the problem.  However, I can run multiple plink commands directly in a console window without issue.

A: I was able to resolve this by attaching stdin to devnull:
def execute(command):
    return subprocess.check_call('plink.exe -ssh ' + USER + '@' + HOST + ' -pw ' + PASSWD + ' ' + command, stdin=open(os.devnull))


text:
Q: Maven doesn't download dependencies: "The repository system is offline" I'm not comfortable with Maven, but I managed to make it work for a while with Netbeans. But suddenly, Maven refuses to download new dependencies :
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal on project matheos: Could not resolve dependencies for project lecoleopensource:matheos:jar:1.4.4-SNAPSHOT: The repository system is offline but the artifact org.docx4j:docx4j-ImportXHTML:jar:3.2.2 is not available in the local repository.
    at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.getDependencies(LifecycleDependencyResolver.java:210)
    at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.resolveProjectDependencies(LifecycleDependencyResolver.java:117)
    at org.apache.maven.lifecycle.internal.MojoExecutor.ensureDependenciesAreResolved(MojoExecutor.java:258)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:201)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
Caused by: org.apache.maven.project.DependencyResolutionException: Could not resolve dependencies for project lecoleopensource:matheos:jar:1.4.4-SNAPSHOT: The repository system is offline but the artifact org.docx4j:docx4j-ImportXHTML:jar:3.2.2 is not available in the local repository.
    at org.apache.maven.project.DefaultProjectDependenciesResolver.resolve(DefaultProjectDependenciesResolver.java:189)
    at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.getDependencies(LifecycleDependencyResolver.java:185)
    ... 22 more
Caused by: org.sonatype.aether.resolution.DependencyResolutionException: The repository system is offline but the artifact org.docx4j:docx4j-ImportXHTML:jar:3.2.2 is not available in the local repository.
    at org.sonatype.aether.impl.internal.DefaultRepositorySystem.resolveDependencies(DefaultRepositorySystem.java:375)
    at org.apache.maven.project.DefaultProjectDependenciesResolver.resolve(DefaultProjectDependenciesResolver.java:183)
    ... 23 more
Caused by: org.sonatype.aether.resolution.ArtifactResolutionException: The repository system is offline but the artifact org.docx4j:docx4j-ImportXHTML:jar:3.2.2 is not available in the local repository.
    at org.sonatype.aether.impl.internal.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:538)
    at org.sonatype.aether.impl.internal.DefaultArtifactResolver.resolveArtifacts(DefaultArtifactResolver.java:216)
    at org.sonatype.aether.impl.internal.DefaultRepositorySystem.resolveDependencies(DefaultRepositorySystem.java:358)
    ... 24 more
Caused by: org.sonatype.aether.transfer.ArtifactNotFoundException: The repository system is offline but the artifact org.docx4j:docx4j-ImportXHTML:jar:3.2.2 is not available in the local repository.
    at org.sonatype.aether.impl.internal.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:348)
    ... 26 more

Something is apparently offline, but I don't understand why and how to fix this.
Here is a part of my pom file :
    <dependencies>
        <!-- docx4j : converts html to docx -->
        <dependency>
                <groupId>org.docx4j</groupId>
                <artifactId>docx4j</artifactId>
                <version>3.2.2</version>
        </dependency>

        <!-- pdf2dom : converts pdf to html -->
        <!--dependency>
                <groupId>net.sf.cssbox</groupId>
                <artifactId>pdf2dom</artifactId>
                <version>1.3</version>
        </dependency-->

    </dependencies>

What I don't understand is that it used to work fine until now...
I don't understand Maven very well, so tell me if I should have given other details. Thank you !
EDIT : I removed the repository section, still the same. I edited the artefactID to docx4j, still the same.

A: Simply remove the repositories section you have defined. Neither you need to define a local repository, because it is still defined in the settings.xml Maven configuration, nor you would place project dependencies under src/main/resources.
Update
Could it be you are running Maven in "offline mode"? Have a look at your Netbeans preferences -> Java -> Maven and your run configuration, if there is an "-o" parameter.


text:
Q: How to determine the AVERAGE number of associated records I have two tables:

*

*reviews (id, created_at, completed_at, type)

*reviews_skills (id, review_id, note)

I have the following query that tells me What % of reviews have 1 or more notes.
SELECT  TRUNC(DATE_PART('day', CURRENT_DATE - r.created_at )/7)  AS weeks_ago,
        date(min(r.created_at)) AS "Date Start",
        date(max(r.created_at)) AS "Date End",
        count(*) as  "reviews in Cohort",
                AVG(has_note::int) as "Reviews w 1 or more Notes Ratio"
FROM (SELECT r.id, r.created_at,
             ( MAX(rs.note) IS NOT NULL ) as has_note
      FROM reviews r JOIN
           reviews_skills rs
           ON r.id = rs.review_id

            WHERE r.completed_at IS NOT NULL
                    AND r.created_at > '2019-01-01'
                    AND r.type = 'long_form'

            GROUP BY r.id
     ) f
GROUP BY weeks_ago
ORDER BY weeks_ago DESC;

What I'm trying to add to this query is: what is the AVG # of notes per review?

A: If I understand correctly, you just need the count in the subquery and then an average:
SELECT  TRUNC(DATE_PART('day', CURRENT_DATE - r.created_at )/7)  AS weeks_ago,
        date(min(r.created_at)) AS "Date Start",
        date(max(r.created_at)) AS "Date End",
        count(*) as  "reviews in Cohort",
        AVG(has_note::int) as "Reviews w 1 or more Notes Ratio",
          AVG(num_notes) as avg_notes
FROM (SELECT r.id, r.created_at,
             COUNT(rs.note) as num_notes,
             ( MAX(rs.note) IS NOT NULL ) as has_note
      FROM reviews r JOIN
           reviews_skills rs
           ON r.id = rs.review_id
      WHERE r.completed_at IS NOT NULL AND
            r.created_at > '2019-01-01' AND
            r.type = 'long_form'
      GROUP BY r.id
     ) f
GROUP BY weeks_ago
ORDER BY weeks_ago DESC;


text:
Q: Performance with ROW_NUMBER I have a query which uses ROW_NUMBER().  I have something like this:
ROW_NUMBER() OVER (ORDER BY publish_date DESC) rnum

The query runs pretty fast.  However, if I add any reference to the "rnum" column, the query slows to a crawl.   So, it appears that just having ROW_NUMBER() is not the issue, but when I use the "rnum" in the actual query, it crawls for like 30 seconds.
Any thoughts?
For Reference, here is the query:
  WITH aquire AS (
    SELECT rtnum, trans_id, source, provider, publish_date, story_link, industry_name, sector_name, subject, teaser, tickers
    FROM (SELECT d.trans_id, d.source, 'AquireMedia' AS provider,
                 d.trans_time AS publish_date, '/research/get_news.php?id=' || d.trans_id AS story_link,
                 i.name AS industry_name, s.sector_name, d.headline AS subject, NULL AS teaser,
                 NEWS.NEWS_FUNCTIONS.CONCATENATE_TICKERS(d.trans_id,'AQUIREMEDIA') AS tickers,
                 ROW_NUMBER() OVER (PARTITION BY d.trans_id ORDER BY d.trans_time DESC) as rtnum
          FROM   story_descriptions_3m d, story_tickers_3m t, uber_master_mv m, industry i, ind_sector ix, sectors s, comp_ind c
          WHERE  d.trans_id = t.trans_id
            AND  t.m_ticker = m.m_ticker
            AND  t.m_ticker = c.m_ticker(+)
            AND  c.ind_code = i.ind_code(+)
            AND  i.ind_code = ix.ind_code(+)
            AND  ix.sector_id = s.sector_id(+)  AND s.sector_id = 10 )
    WHERE rtnum = 1),
partner AS (
  SELECT rtnum, trans_id, source, provider, publish_date, story_link, industry_name, sector_name, subject, teaser, tickers
  FROM (SELECT CAST(n.story_id AS VARCHAR2(20)) trans_id, n.provider AS source, 'Partner News' AS provider,
               n.story_date AS publish_date, n.link AS story_link, i.name AS industry_name, s.sector_name, n.title AS subject,
               CAST(substr(n.teaser,1,4000) AS VARCHAR2(4000)) AS teaser, NEWS.NEWS_FUNCTIONS.CONCATENATE_TICKERS(n.story_id,'OTHER') AS tickers,
               ROW_NUMBER() OVER (PARTITION BY n.story_id ORDER BY n.story_date DESC) as rtnum
        FROM   news_stories_3m n, news_stories_lookup_3m t, comp_ind c, uber_master_mv m, industry i, ind_sector ix, sectors s
        WHERE  t.story_id = n.story_id
          AND  t.ticker   = m.ticker
          AND  m.m_ticker = c.m_ticker(+)
          AND  c.ind_code = i.ind_code(+)
          AND  i.ind_code = ix.ind_code(+)
          AND  ix.sector_id = s.sector_id(+)  AND s.sector_id = 10 )
   WHERE rtnum = 1)
  SELECT  trans_id, source, provider,
         TO_CHAR(publish_date,'MM/DD/YYYY HH24:MI:SS') AS publish_date,
         UNIX_TIMESTAMP(publish_date) AS timestamp,
         story_link, industry_name, sector_name, subject, teaser, tickers
  FROM (SELECT trans_id, source, provider, publish_date, story_link, industry_name, sector_name, subject, teaser, tickers,
                         ROW_NUMBER() OVER (ORDER BY publish_date DESC) rnum
             FROM (SELECT trans_id, source, provider, publish_date, story_link, industry_name, sector_name, subject, teaser, tickers
                        FROM   aquire WHERE rtnum <= 5
                        UNION ALL
                        SELECT trans_id, source, provider, publish_date, story_link, industry_name, sector_name, subject, teaser, tickers
                        FROM   partner WHERE rtnum <= 5))
WHERE rnum BETWEEN 1 AND 1 * 5;

A: Let simulate your query on a simple example to demonstrate and explain that you encounter expactable results.
Sample Data
create table tab1 as
select rownum id, lpad('x',3000,'y') pad from dual connect by level <= 1000000;

Now if you run a query below  in your IDE, you will instantly see the first page of the result set.
Note, you define the row_numberbut do not use it.
select id, pad from (
 select id, pad,
  row_number() over (order by id) as rnum
 from tab1
)

The answert is in the execution plan below
--------------------------------------------------------------------------
| Id  | Operation         | Name | Rows  | Bytes | Cost (%CPU)| Time     |
--------------------------------------------------------------------------
|   0 | SELECT STATEMENT  |      |  1000K|  2866M|   135K  (1)| 00:00:06 |
|   1 |  TABLE ACCESS FULL| TAB1 |  1000K|  2866M|   135K  (1)| 00:00:06 |
--------------------------------------------------------------------------

you see that no sorting and filtering is performed, the row_number is simple ignored.
This (fetching only few initial rows and no sorting) explains why the query performs.
Contrary if you constraint on the row_number as  follows
SQL> select id, pad from (
  2   select id, pad,
  3    row_number() over (order by id) as rnum
  4   from tab1
  5  ) where rnum between 1 and 5
  6  ;

Elapsed: 00:00:07.80

You observe respectable elapsed time. Again the execution plan provides the answer.
See here how to get the execution plan for your query.
-----------------------------------------------------------------------------------------
| Id  | Operation                | Name | Rows  | Bytes |TempSpc| Cost (%CPU)| Time     |
-----------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT         |      |     5 |  7640 |       |   762K  (1)| 00:00:30 |
|*  1 |  VIEW                    |      |     5 |  7640 |       |   762K  (1)| 00:00:30 |
|*  2 |   WINDOW SORT PUSHED RANK|      |  1000K|  2866M|  3906M|   762K  (1)| 00:00:30 |
|   3 |    TABLE ACCESS FULL     | TAB1 |  1000K|  2866M|       |   135K  (1)| 00:00:06 |
-----------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - filter("RNUM">=1 AND "RNUM"<=5)
   2 - filter(ROW_NUMBER() OVER ( ORDER BY "ID")<=5)

The consequence is that now you must now go throu all records (in your case perform all the joins), which breaks the performance.
To prove it, run simple your performat query with a fetch all option or with added order by clause. It is quite possible that you will get the same non-performant result as in your second query.
Final Remark
Instead of the ROW_NUMBER() you may use the row_limiting_clause
Pass the ordering column from the row_number in the order by clause and use offset and fetch first to limit the result.
select id, pad from (
 select id, pad
 from tab1
) order by id
fetch first 5 rows only;

Under the cover you'll see the identical execution plan using the WINDOW SORT PUSHED RANK as above.


text:
Q: Selenium WebDriver (2.25) Timeout Not Working I think I've read all the Selenium timeout questions on Stack Overflow, yet neither implicit nor explicit timeout works in my Selenium webdriver 2.25 (Python 2.7 binding) and both "no_timeout_here =" lines would hang forever --
browser = webdriver.Firefox()
browser.implicitly_wait(6)
browser.set_page_load_timeout(30)
browser.get("http://www.google.com")
try:
    #no_timeout_here = browser.find_element_by_id("id_not_found")
    no_timeout_here = WebDriverWait(browser, 5).until(lambda browser:
            browser.find_element_by_id("id_not_found"))
except:
    raise

All pointers will be greatly appreciated!
Update Oct. 16th
Thanks to seleniumnewbie for your comprehensive answer, however, your unittest code still hangs on my Ubuntu 11.04 (64-bit) under Python 2.7 --
(2012/10/17 11:51:58)$ time ./timeout.py
^CTraceback (most recent call last):
...
KeyboardInterrupt

real    2m26.572s
user    0m0.368s
sys 0m0.232s

(2012/10/17 11:54:26)$ python -V
Python 2.7.2+

(2012/10/17 11:57:04)$ uname -a
Linux 3.0.0-26-generic #43-Ubuntu SMP Tue Sep 25 17:19:22 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux

(2012/10/17 11:57:10)$ ls selenium-server-standalone-2.25.0.jar

May I know your OS/Python version?

A: If you are using Firefox 17 and Selenium 2.26.0 then you are hitting defect #4814: http://code.google.com/p/selenium/issues/detail?id=4814

A: Based on answers found here
1
I would  recommend using WebDriverWait with ExpectedConditons.
//scroll down with Javascript first
WebDriverWait wait = new WebDriverWait(driver, 30);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("selector")));
//interact with your element
element.click()

Take a look at the guidance provided by Selenium Official page:
http://seleniumhq.org/docs/04_webdriver_advanced.html
2
try using fluent wait in particular. The main feature is:
An implementation of the Wait interface that may have its timeout and polling interval configured on the fly.
Each FluentWait instance defines the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition. Furthermore, the user may configure the wait to ignore specific types of exceptions whilst waiting, such as NoSuchElementExceptions when searching for an element on the page.
public WebElement fluentWait(final By locator){
        Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
                .withTimeout(30, TimeUnit.SECONDS)
                .pollingEvery(5, TimeUnit.SECONDS)
                .ignoring(NoSuchElementException.class);

        WebElement foo = wait.until(
new Function<WebDriver, WebElement>() {
            public WebElement apply(WebDriver driver) {
                        return driver.findElement(locator);
                }
                }
);
                           return  foo;              }     ;

The method described returns you web element you can operate with.
So the approach be the following:
1) you need to find the selectors  of elements you expect to be rendered after scrolling
e.g.
String cssSelector = "blablabla"

2) scroll down with js
3)
WebElement neededElement  = fluentWait(cssSelector);
neededElement.click();
//neededElement.getText().trim();

you can get more info about fluent wait here
UPDATE

from selenium import webdriver
import unittest, time, re

class Sdsdsd(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.implicitly_wait(30)
        self.base_url = "https://www.google.com/"
        self.verificationErrors = []

    def test_sdsdsd(self):
        driver = self.driver
        driver.get ("http://www.google.com")
        try:
             driver.find_element_by_id("id_not_found")# I am only searching for the element not assigning it to anything.
        except:
            raise

    def is_element_present(self, how, what):
        try: self.driver.find_element(by=how, value=what)
        except NoSuchElementException, e: return False
        return True

    def tearDown(self):
        self.driver.quit()
        self.assertEqual([], self.verificationErrors)

if __name__ == "__main__":
    unittest.main()

and I get this exception, which is desired
E
======================================================================
ERROR: test_sdsdsd (__main__.Sdsdsd)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "sdsdsd.py", line 19, in test_sdsdsd
    driver.find_element_by_id("id_not_found")
  File "/Library/Python/2.6/site-packages/selenium-2.2.0-py2.6.egg/selenium/webdriver/remote/webdriver.py", line 172, in find_element_by_id
    return self.find_element(by=By.ID, value=id_)
  File "/Library/Python/2.6/site-packages/selenium-2.2.0-py2.6.egg/selenium/webdriver/remote/webdriver.py", line 525, in find_element
    {'using': by, 'value': value})['value']
  File "/Library/Python/2.6/site-packages/selenium-2.2.0-py2.6.egg/selenium/webdriver/remote/webdriver.py", line 144, in execute
    self.error_handler.check_response(response)
  File "/Library/Python/2.6/site-packages/selenium-2.2.0-py2.6.egg/selenium/webdriver/remote/errorhandler.py", line 110, in check_response
    raise exception_class(message, screen, stacktrace)
NoSuchElementException: Message: u'Unable to locate element: {"method":"id","selector":"id_not_found"}' ; Stacktrace: Method WebDriverError threw an error in file:///private/var/folders/TA/TAS7MYfcEuG3lBNHwhrjRU+++TI/-Tmp-/tmpEf_lrD/extensions/fxdriver@googlecode.com/resource/modules/utils.js

----------------------------------------------------------------------
Ran 1 test in 33.818s

FAILED (errors=1)

Also note that it failed after 33 seconds, which means it waited for 30 seconds before erroring out.
When i change the implicit wait to self.driver.implicitly_wait(15)
I get this error
E
======================================================================
ERROR: test_sdsdsd (__main__.Sdsdsd)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "sdsdsd.py", line 19, in test_sdsdsd
    driver.find_element_by_id("id_not_found")
  File "/Library/Python/2.6/site-packages/selenium-2.2.0-py2.6.egg/selenium/webdriver/remote/webdriver.py", line 172, in find_element_by_id
    return self.find_element(by=By.ID, value=id_)
  File "/Library/Python/2.6/site-packages/selenium-2.2.0-py2.6.egg/selenium/webdriver/remote/webdriver.py", line 525, in find_element
    {'using': by, 'value': value})['value']
  File "/Library/Python/2.6/site-packages/selenium-2.2.0-py2.6.egg/selenium/webdriver/remote/webdriver.py", line 144, in execute
    self.error_handler.check_response(response)
  File "/Library/Python/2.6/site-packages/selenium-2.2.0-py2.6.egg/selenium/webdriver/remote/errorhandler.py", line 110, in check_response
    raise exception_class(message, screen, stacktrace)
NoSuchElementException: Message: u'Unable to locate element: {"method":"id","selector":"id_not_found"}' ; Stacktrace: Method WebDriverError threw an error in file:///private/var/folders/TA/TAS7MYfcEuG3lBNHwhrjRU+++TI/-Tmp-/tmpXSbCY0/extensions/fxdriver@googlecode.com/resource/modules/utils.js

----------------------------------------------------------------------
Ran 1 test in 18.843s

FAILED (errors=1)


text:
Q: PreCompile header in Vistual studio 2005 problem I have 2 projects. Both have the setting for Create/Use Precompiled Header set to "Use Precompiled Header (/Yu)"
I deleted a file in both projects. One compiles successfully but the other generates an error
Error   2   fatal error C1083: Cannot open precompiled header file: 'file.pch': No such file or directory

A: Have you tried "Rebuild"? An ordinary Build sometimes gets messed up. Also, is it really file.pch?


text:
Q: How to display UtfGrid info First off sorry if this question have been asked, I have been looking for an answer for some time now but can't find any solution.
I have created a .mbtiles file with Tilemill, extracted the .png and the .grid.json files using mbutil. I used IIS to display the PNG tiles using Leaflet. All that works great, except for the utfgrid(.grid.json)info isn't showing.
Do I need Wax?
I have tried Wax but with no success. Any suggestions will be immensely helpful.
Most of the info I have comes from:
http://build-failed.blogspot.com/2012/03/custom-map-tiles-part-2-tilemill.html.
My map code is shown below, the info for each grid comes from the key "Un"
HTML

.....

Java
    var map = L.map('map').setView([-28.7640911,24.302625], 6)//Load my tile layer
        var tilesUrl = 'http:/localhost/GP_Un_Lable/{z}/{x}/{y}.png',
        tilesLayer = new L.TileLayer(tilesUrl);
        tilesLayer.setOpacity(0.7);
        map.addLayer(tilesLayer);
        var utfGrid = new L.UtfGrid('http:/localhost/GP_Un_Lable/{z}/{x}/{y}.grid.json?callback={cb}');
        map.addLayer(utfGrid);
            utfGrid.on('mouseover', function (e) {
                if (e.data) {
                    document.getElementById("UtfGridTextHere").innerHTML = e.data.Un;
                } else {
                    document.getElementById("UtfGridTextHere").innerHTML = "nothing";
                }
                //console.log('mouseover: ' + e.data);
            });
            utfGrid.on('mouseout', function (e) {
                document.getElementById("UtfGridTextHere").innerHTML = "nothing";
            });

A: You may need to look at the second step.  The tutorial started you out with just creating the tiles.  Then tutorial added support for the "hit grid" created by the "Teaser" tab in TileMill.  The teaser step created another part of the .mbtile spec.
The mbutil utility is used to extract either the grid or tiles.  In the second run, it extracts both.  In the change to the second code, he shows where he added both references to the .png files and the .grid.json files.  The other thing that his path shows me is the 1.0.0 reference.  This means that you are using the TMS directory path to display the data.
The other part of the code that you are missing is the formatter section that formats how the .json file will be displayed.
The glue that you are missing from his explanation is that TMS is used to display information without a web server.  At least that's how I have used the TMS format before.  You say that you have an IIS web server.  The .mbtiles format is just a sqlite3 database if you did not know this.  Look up some of the existing tile servers.  Hook up a version of a mbtiles server that works for you in your web server environment.  Then just use the .mbtiles database.  That way you do not have to haul around a bizzlion files.
var tilejson = {
    tilejson: '1.0.0',
    tiles: ['http://localhost/tiles/freguesias/1.0.0/Freguesias/{z}/{x}/{y}.png'],
    grids: ['http://localhost/tiles/freguesias/1.0.0/Freguesias/{z}/{x}/{y}.grid.json'],
    formatter: function (options, data) { return "CODE: " + data.DICOFRE }
};

map = new L.Map('map');
map.addLayer(new wax.leaf.connector(tilejson));
map.setView(new L.LatLng(39.5,-5.0), 6);

wax.leaf.interaction(map, tilejson);


text:
Q: The formula used to calculate electrical potential energy
Sorry for the ugly picture but it makes my question more understandable.
The $\Delta V$ from $A$ to $B$ is calculated by$$\int_A^B E \, \mathrm{d}r$$ where $r$ is the distance between $A$ and $B$. The curve line is the real path the charge take going from $A$ to $B$. Suppose that the green arrow is the $\vec E$ and the red arrow is $dl$ at some arbitrary point on the path the charge move.
From what I learned from class
$$\int_A^B E \, \mathrm{d}r = \int_A^B E \, \mathrm{d}l$$
This is the point I don't understand and make me reconsider what I learn about work in physics. Can someone explain why $\int_A^B E \, \mathrm{d}r = \int_A^B E \, \mathrm{d}l$
Does the calculation of the work involve vector and $E\, \mathrm{d}l$ here is the dot product of $\vec E$ and $\vec {\mathrm{d}l}$ or it is calculated by projecting all the force exert to the object to the axis created by start point and end point?

A: The dot product is missing. The integral must also be multiplied by a Cosine of the angle between the vectors. $dl$ and $dr$ are the same thing. It's just an infinitesimally small distance on the direction of the field.


text:
Q: Nuget : how to NOT remove old packages after package update? A couple months ago we've started using Nuget in our ASP.NET MVC projects. We're building a lot of applications that consist of several reusable compontents. For example:
Application A
- Authentication Module (nuget package with JavaScript/Templates/Controllers/POCO)
- Payment Module (nuget package with JavaScript/Templates/Controllers/POCO)
Application B
- Authentication Module (nuget package with JavaScript/Templates/Controllers/POCO)
But our team has grown a lot the last weeks and we're experiencing some problems when merging packages. Everytime we update a package, the old version package is removed from the package folder. This is great, but it causes a lot of problems when merging/checkin into git (we use tortoiseGit). For Example:
Developer 1 updates the Authentication module in Application A to version 2.0 and checks this in. Developer 2 is also working on Application A and updates the Authentication module to version 2.1. Developer 1 checks in before Developer 2. When Developer 2 pulls the latest changes from git and tries to checkin his changes he will experience a lot of conflicts in the nuget packages folder because he doesnt have the files from version 2.0  in his package folder (TortoiseGit Error: FileNotFound). Now Developer 1 has to create the package folder in his local file system and mark it as deleted to be able to checkin in his changes.
This problem would be resolved if Nuget doesn't delete old package folders on an update. Is this possible? In this scenario we would of course clean up old packages in the nuget package folder manually...

A: It sounds like a better solution for your team would be to not include the packages folder in version control, and instead enable package restore.
If you use Nuget 2.7+ , visit this site


text:
Q: How to animate the needle of the gauge in R? I'm trying to animate the needle of my gauge made with the package "ggplot2". I've already try with the package "gganimate", but I don't understand how to use it exactly.The gauge.
What I'm trying to do is to start the needle in the red section of the gauge and make it go to the number I sent to it. It goes to 0% to 100%, each section have 1/4 of the gauge.
Here's the code:
    library(ggplot2)
    library(gganimate)

gg.gauge <- function(pos) {
  breaks <- c(0, 25, 50, 75, 100)  #Distance between color section in %

  #Calculate the ray of each circle
  get.poly <- function(a,b,r1=0.7,r2=1.0) {
    th.start <- pi*(1-a/100)
    th.end   <- pi*(1-b/100)
    th       <- seq(th.start,th.end,length=100)
    x        <- c(r1*cos(th),rev(r2*cos(th)))
    y        <- c(r1*sin(th),rev(r2*sin(th)))
    return(data.frame(x,y))
  }

  # Create gauge
  ggplot()+
    geom_polygon(data=get.poly(0, 25),aes(x,y),fill="red")+                         #Red section
    geom_polygon(data=get.poly(25, 50),aes(x,y),fill="orange")+                     #Orange section
    geom_polygon(data=get.poly(50, 75),aes(x,y),fill="gold")+                       #Yellow section
    geom_polygon(data=get.poly(75, 100),aes(x,y),fill="forestgreen")+               #Green section
    geom_polygon(data=get.poly(0, 100, 0.993, 1.01),aes(x,y),fill="black")+         #Black periphery superior
    geom_polygon(data=get.poly(0, 100, 0.70, 0.72),aes(x,y),fill="black")+          #Black periphery inferior
    geom_polygon(data=get.poly(0.7, 0),aes(x,y),fill="black")+                      #Black based under red
    geom_polygon(data=get.poly(100, 99.3),aes(x,y),fill="black")+                   #Black based under green
    geom_polygon(data=get.poly(0, 100, 0.3, 0),aes(x,y),fill="black")+              #Half black cercle
    geom_polygon(data=get.poly(pos-0.60, pos+0.60, 0.1, 1.1),aes(x,y))+             #Needle
    annotate("text",x=0.88,y=-0.1,label="Growth",vjust=0,size=8,fontface="bold")+
    annotate("text",x=-0.84,y=-0.1,label="Defensive",vjust=0,size=8,fontface="bold")+
    coord_fixed()+
    theme_bw()+
    theme(axis.text=element_blank(),
          axis.title=element_blank(),
          axis.ticks=element_blank(),
          panel.grid=element_blank(),
          panel.border=element_blank())
}

Thanks in advance for the help.

A: Here is one implementation of something similar to what it sounds like you are trying to do. Let me know if you have any questions!
library(ggplot2)
library(gganimate)
library(dplyr)

get.poly <- function(a,b,r1=0.7,r2=1.0) {
  th.start <- pi*(1-a/100)
  th.end   <- pi*(1-b/100)
  th       <- seq(th.start,th.end,length=100)
  x        <- c(r1*cos(th),rev(r2*cos(th)))
  y        <- c(r1*sin(th),rev(r2*sin(th)))
  return(data.frame(x,y))
}

one <- get.poly(0, 25)
one$color <- "red"
two <- get.poly(25, 50)
two$color <- "orange"
three <- get.poly(50, 75)
three$color <- "gold"
four <- get.poly(75, 100)
four$color <- "forestgreen"
five <- get.poly(0, 100, 0.993, 1.01)
five$color <- "black"
six <- get.poly(0, 100, 0.70, 0.72)
six$color <- "black"
seven <- get.poly(0.7, 0)
seven$color <- "black"
eight <- get.poly(100, 99.3)
eight$color <- "black"
nine <- get.poly(0, 100, 0.3, 0)
nine$color <- "black"

all_ten <- data.frame()
for (i in 1:100){
  ten <- get.poly(i-0.60, i+0.60, 0.1, 1.1)
  ten$state <- i
  all_ten <- all_ten %>%
    bind_rows(ten)
}

all_ten$color <- "black"

all <- one %>%
  bind_rows(two,
            three,
            four,
            six,
            nine)

ggplot(all_ten, mapping = aes(x,y))  +  transition_time(state) + geom_polygon(all, mapping = aes(x,y, fill = color)) +
  annotate("text",x=0.88,y=-0.1,label="100",vjust=0,size=8,fontface="bold")+
  annotate("text",x=-0.84,y=-0.1,label="0",vjust=0,size=8,fontface="bold")+
  coord_fixed()+
  theme_bw()+ geom_polygon() +
  theme(axis.text=element_blank(),
        axis.title=element_blank(),
        axis.ticks=element_blank(),
        panel.grid=element_blank(),
        panel.border=element_blank()) + scale_fill_manual(values = c("black", "forestgreen", "gold","orange","red")) + guides(fill = F) +
  labs(title = 'Gauge Value: {frame_time}')


text:
Q: Why is text line breaking—when cutting and pasting in the console—so much slower than in any other application? I often work with Vim, but sometimes I feel that I can do certain things better in Kate. So I copy the file from vim via ctrl+c and paste it into Kate.
This way, everything is pretty fast. But if I repaste it to Vim, the pasting-process becomes terribly slow even when using :set paste.
I somehow understand that, since Vim does a lot of stuff, but it's not only Vim. But in other applications, I've seen the same. Pasting stuff into the MYSQL server is very slow, too. The same with bash and Zsh.
I don't understand why pasting text that needs automatic line-breaks with long texts in graphical applications is (almost always) faster than in the command line. Isn't there way more calculation involved in doing that in the GUI? I mean, technically, the command line is a block of very big pixels (which can display single letters each). The command-line-resolution is way less than the one of the GUI, so it should be faster.

A: There is a GUI version of vim (gvim), including one for Windows (as well as one for 'Cygwin' that runs on the X-GUI (that also runs on windows).
I'd try the native gvim and see if that gives you the speed you are looking for.
Note: I don't think the newest vims run in the console at all (too many problems). (Clarification: the cygwin version doesn't run in the Windows cmd.exe -- no terminal support.  It does run in a regular TTY emulator as well as the cygwin tty emulators and under cygwin-X -- best would likely be cygwin-X -- I run my linux-gvim sessions, exclusively through cygwin's X.  My connection to my server is "internal" (not exposed to internet), so I don't need to use encryption, so it runs plenty fast.
To better answer the original poster's Question though, there are some unknowns -- like what console he is talking about and when he mentions zsh & bash, is he talking about cygwin versions, or ones running under the win10-linux subsystem, or what?
Originally thought problem might be the console you were using, so recommended trying the native versions, but as for why consoles are slower -- I touch on that below.  Remember: even if you run a text console -- it is still, likely
running on the windows desktop.  So it is a GUI-emulation of a text console window -- not an actual-hardware based console like the old-pre-windows DOS consoles used to be (which used graphics hardware to do scrolling, for example).  As for native vim versions:
Try https://tuxproject.de/projects/vim/
I'd recommend this version:
http://tuxproject.de/projects/vim/complete-x64.exe
If you don't care about how to get your pasting faster into vim, but only want the answer of why the console is slower --- the gui, can accept pasted text directly without going through a single-character-by-single-character read/write interface (the console).  Going through the console involves reading & writing single-characters, 1 at a time.  I.e. the paste goes into windows (the OS), which turns it into a stream of single-characters sent to the input driver in the console.  Those go into a system buffer (not vim).  Then vim has to read those characters from the system.  While you can read / write multiple characters, they are still processed and displayed 1 at a time by the underlying SW.  Very inefficient.  When vim updates the console -- it is writing the characters and outputting tty-movement codes (not so much on input) to move text around.  Everything is handled by turning graphical actions into character codes that are sent to the console, that interprets the character codes in order to simulate a TTY.
On top of that, it still will do the normal processing that vim does -- but to see which has a larger impact, running the GUI version of vim will cut out all the console stuff.
On top of the normal slowness of a simulated console, the console in Windows has is running in Windows -- and Windows has been adding more layers of indirection since XP.  At least 1 was added in XP,  a reasonable small/fast layer, but going to vista/win7, very noticeable per-key delay was added.  Those delays happen for each key!  From what I understand, more layers were added for Win10 to allow for cloud & remote device indirection.
As far as the paste in the GUI version of vim -- it has indirections added, but they are for the entire paste-message (not per character).  So vim gets the entire pasted text that it can process without updating the screen with each character -- so only 1 screen update is needed after the pasted text has been processed.  More may be done, depending on speed of processing and video speed -- i.e. vim sometimes shows partial progress when things take longer, but I believe that is a toggle-able option in vim.


text:
Q: CentOS 6.x for CUDA development on a MBP Here is a short description of my situation - I need a portable machine for CUDA and iOS development, so any of the newer MacBook Pros with NVIDIA GPUs seemed like a no-brainer at first. However, the CUDA-requiring project already has a huge code base from a large number of contributors that is developed on CentOS 5.x/6.x. CentOS is also the only platform that is officially supported.
I obviously need a Mac because of the iOS project, but is MBP the right machine for the CentOS+CUDA based one? Did anyone get this to work properly, or is buying two separate machines (MacBook Pro + a PC laptop) the only solution?
P.S. I am mostly worried about the GPU-switching support between MacBook Pro's cards on Linux, so any first-hand experience from existing MBP owners is very welcome.

A: I don't think you'll be able to do this. I tried RHEL and it locked up on load. Same results on Fedora 16. I did successfully install Fedora 17 but was unable to get dynamic video card switching to work. Nor was I able to get the Nvidia card to work. I believe you have to run dual X servers and map the second card to your DFP out based on other posts. Additionally, heat and power consumption are increased since it never powers off the NVidia card. I did a lot of playing with Bumblebee and switching configurations for the Nouveau driver since the Nvidia driver yields a black screen. However, it wasn't switching properly. I believe the best I ever had it working was to run on the Intel card with hardware acceleration using the Nouveau driver. I would not recommend it as a CUDA platform at this time. There is a reasonable amount of contrib energy focused in this direction though and I don't think it will be too long before it is working. The Linux kernel has had support related to this being implemented as well.

A: I know this post is long time ago, but I want to share some information for someone visit this post later.
I did install Ubuntu & Centos & Debian on a MBP(9.2). It seems the important point is the kernel version, not the distro itself. The newer the kernel, the better the performance/ compatibility to Apple's hardware. In my case, intel_pstate kernel module support better than older module(don't remember) for Ivy Bridge. Being on Debian jessie 3.13, work like a charm, just a little bit tweak.( a little). On Centos 2.6 and Ubuntu 3.2, it seems not right. Temperature, fan, keyboard, trackpad... Have to tweak them all. And kernel panic, hanging happen a lot. Not even mentioning on a MBP with dedicated graphics card.


text:
Q: What problems can I solve using recursion? Today I made one method with usage of recursion in php and get interested in it. what problems actually can recursion solve? For what things we can use recursion?
I started to search it on web and search and search, but I can't find anything.
So I am asking, what we can I do with usage of recursion?
Are there some limitations? Things that we can't do with recursion but with standard loops we can? I wonder if I could use now recursion normally in my code very often.

A: What we can I do with usage of recursion?
Solving recursive problems. The parent-child problem, where every child can be a parent itself again, is most the commonly one.
function doSomethingWithNode($node)
{
    // Do something with $node

    // Loop over all childs, and run this code for those childs too, and for those childs, and for those childs, and ...
    foreach($node->getChilds() as $child) {
        doSomethingWithNode($child);
    }
}

doSomethingWithNode($rootNode);

Are there some limitations?
Yes. PHP (and other programming languages) keeps track of which code calls which function, so it knows where to continue after the function returns. This is called the call stack. Adding new entries to the call stack will take both some memory and some time. Mainly the first CAN lead to problems when you have a lot (millions) of iterations.
Depending on your installation the call stack may even be limited. By default it isn't. By installing the xdebug-extension it gives you a maximum of 100 nested calls (by default, can be changed in the config). In those setups it will lead to a Fatal error (example).
Things that we can't do with recursion but with standard loops we can? I  wonder if I could use now recursion normally in my code very often
Due to above limitations, recursion should be used with care. When you can solve it with a normal while or for-loop: use the normal loop. Most of the time it will lead to easier to read code.
When you care about portability (for example when writing an open source project), you probably want to have xdebug-users in mind.

A: Every type of iterating through any data structure can be done with recursion. In fact you can replace every loop construct like for, while, do while, foreach, etc as simple recursion:
function factorial($n) {
  $result = $n < 0 ? -1 : 1;
  for($i = abs($n), $i > 1; $i--) {
    $result *= $i;
  }
  return $result;
}

Can be written:
function factorial($n) {
  $forHelper = function($result, $i) {
    return $i === 1 ? $result : $forHelper($result * $i, $i - 1);
  }
  return $forHelper($n < 0 ? -1 : 1, abs($n));
}

This is called tail recursion. In some languages the two above produces very similar runtime code, but not PHP. It uses some memory for each call it does. For me both are equally readable, but I bet most programmers would find it easier with the loop, especially when it gets nested.
Some algorithms where you iterate a graph or tree will have a simpler version using recursion rather than iteration:
function treeDepth($node) {
  if( $node === null ) {
    return 0;
  } else {
    return 1 + max(treeDepth($node->left), treeDepth($node->right));
  }
}

An iterative solution here would need some way of keeping track of the places it needs to visit and thus you are doing some housekeeping that is handled automatically by the recursive version.
function treeDepth($node) {
  $max = 0;
  $backtrack = [[0, $node]];
  while( count($backtrack) ) {
    list($depth, $node) = array_pop($backtrack);
    while($node !== null) {
      array_push($backtrack, [++$depth, $node->right]);
      $node = $node->left;
    }
    $max = max($max, $depth);
  }
  return $max;
}

The limitation depends on the language. In PHP it allocates some memory for each call frame that is not allocated for a simple loop. The node traversal always uses memory since the process is inherently recursive.
Ultimately you should code in the way that makes your code as clear as possible without thinking about optimization. Use looping constructs where it is clearest and recursion where it is clearest. Only when you actually stumble on performance issues you should profile and rewrite the parts that use most time. I use to keep the original code as comment if it's short and documents what actually goes on in the more complex iterative version. In PHP function calls themselves are expensive.


text:
Q: Bad positioning with md-input in Chrome - Angular Material & HTML I have an ng-repeat with a layut="row" containing an md-input, an icon and a button, there is also a spinner but that is not going to be shown when the button is shown and vice versa.
I have been experiencing some bad positioning with these rows in Chrome. I have no idea why it does this and how to fix it? Have someone else experienced this bug? Here are some screenshots and below is my html.
Also, I cannot scroll the md-content in firefox, while it works in chrome.. that is also a bug I have not solved yet. So if someone knows the solution for that that would be a bonus :) Thanks!
Chrome:

Firefox:

My html:
<md-content class="darkgrey-bkgr white-text" flex layout="column" layout-margin>

    <md-input-container flex>
      Parameter {{id}}
      <input ng-model="doc.value">
    </md-input-container>

      code
      <md-tooltip md-direction="right">
        {{doc.formattedValue}}
      </md-tooltip>

    <md-progress-circular class="small-config-spinner" md-mode="indeterminate"></md-progress-circular>
    <md-button class="md-icon-button md-fab md-mini md-primary" ng-click="ctrl.updateConfigParameter(id,doc.value)">
      check
    </md-button>

</md-content>

A: You just need to use a parent div element to get the desired result.

     //Your Code

Its wokring fine in Chrome and Firefox
Here is the working example. http://codepen.io/next1/pen/MeJWpd


text:
Q: Custom keyboard for mathematical input How can you display a keyboard that has only digits and typical mathematical signs: parenthesis, operators (+,*,/,-,^), etc..  I'm looking for something with the same look and feel as the standard keyboard on iOS, that can be moved, undocked,  and split. I could probably use buttons in a UIView but it wouldn't feel the same as the usual keyboard.

A: UIKeyboardType
The type of keyboard to display for a given text-based view.

typedef enum {
   UIKeyboardTypeDefault,
   UIKeyboardTypeASCIICapable,
   UIKeyboardTypeNumbersAndPunctuation,
   UIKeyboardTypeURL,
   UIKeyboardTypeNumberPad,
   UIKeyboardTypePhonePad,
   UIKeyboardTypeNamePhonePad,
   UIKeyboardTypeEmailAddress,
   UIKeyboardTypeDecimalPad,
   UIKeyboardTypeTwitter,
   UIKeyboardTypeAlphabet = UIKeyboardTypeASCIICapable
} UIKeyboardType;

Set it as per your requirement.