text:
Q: Sockets in python client not closing after event read write events in multi-connection server I am using this article from real python that allows for multiconnections. However, after I use it with a small change -

*

*after sending and receiving messages from the client and server, the client does not close; or

*all data.messages have been exausted, the client does not close.

The goal is to close the client after all communication is done from the server and client.
I have tried sock.settimeout(5.0) like methods but they do not work.
Looks like this break does not work which could be the real problem other than settimeout:
if not sel.get_map(): break
Second, looks like it does not get into this code while I was checking:
if not recv_data:
    print("closing connection", data.connid)
    sel.unregister(sock)
    sock.close()

https://github.com/realpython/materials/blob/master/python-sockets-tutorial/multiconn-client.py
The changes to the above code are as follows:
server.py
import sys
import socket
import selectors
import types

sel = selectors.DefaultSelector()
messages = [b"Message 1 from server.", b"Message 2 from server."]

def accept_wrapper(sock):
    conn, addr = sock.accept()  # Should be ready to read
    print("accepted connection from", addr)
    conn.setblocking(False)
    data = types.SimpleNamespace(
            addr=addr,
            inb=b"",
            messages=list(messages),
            outb=b"",
        )
    events = selectors.EVENT_READ | selectors.EVENT_WRITE
    sel.register(conn, events, data=data)

def service_connection(key, mask):
    sock = key.fileobj
    data = key.data
    if mask & selectors.EVENT_READ:
        recv_data = sock.recv(1024)
        if recv_data:
            data.inb += recv_data
            print("received", recv_data, "from", data.addr)
        else:
            print("closing connection to", data.addr)
            sel.unregister(sock)
            sock.close()
    if mask & selectors.EVENT_WRITE:
        if not data.outb and data.messages:
            data.outb = data.messages.pop(0)
        if data.outb:
                print("echoing", repr(data.outb), "to", data.addr)
                sent = sock.send(data.outb)
                data.outb = data.outb[sent:]

if len(sys.argv) != 3:
    print("usage:", sys.argv[0], "<host> <port>")
    sys.exit(1)

host, port = sys.argv[1], int(sys.argv[2])
lsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
lsock.bind((host, port))
lsock.listen()
print("listening on", (host, port))
lsock.setblocking(False)
sel.register(lsock, selectors.EVENT_READ, data=None)

try:
    while True:
        events = sel.select(timeout=None)
        for key, mask in events:
            if key.data is None:
                accept_wrapper(key.fileobj)
            else:
                service_connection(key, mask)
except KeyboardInterrupt:
    print("caught keyboard interrupt, exiting")
except:
    print("uncaught error, exiting")
finally:
    sel.close()

client.py
import sys
import socket
import selectors
import types

sel = selectors.DefaultSelector()
messages = [b"Message 1 from client.", b"Message 2 from client."]

def start_connections(host, port, num_conns):
    server_addr = (host, port)
    for i in range(0, num_conns):
        connid = i + 1
        print("starting connection", connid, "to", server_addr)
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setblocking(False)
        sock.connect_ex(server_addr)
        events = selectors.EVENT_READ | selectors.EVENT_WRITE
        data = types.SimpleNamespace(
            connid=connid,
            recv_total=0,
            messages=list(messages),
            outb=b"",
            inb=b"",
        )
        sel.register(sock, events, data=data)

def service_connection(key, mask):
    sock = key.fileobj
    data = key.data
    if mask & selectors.EVENT_READ:
        recv_data = sock.recv(1024)
        print("received", repr(recv_data), "from connection", data.connid)
        if recv_data:
            data.recv_total += len(recv_data)
            data.inb += recv_data
        if not recv_data:
            print("closing connection", data.connid)
            sel.unregister(sock)
            sock.close()
    if mask & selectors.EVENT_WRITE:
        if not data.outb and data.messages:
            data.outb = data.messages.pop(0)
        if data.outb and data.inb:
            print("sending", repr(data.outb), "to connection", data.connid)
            sent = sock.send(data.outb)
            data.outb = data.outb[sent:]

if len(sys.argv) != 4:
    print("usage:", sys.argv[0], "<host> <port> <num_connections>")
    sys.exit(1)

host, port, num_conns = sys.argv[1:4]
start_connections(host, int(port), int(num_conns))

try:
    while True:
        events = sel.select(timeout=1)
        if events:
            for key, mask in events:
                service_connection(key, mask)
        else:
            break
        # Check for a socket being monitored to continue.
        if not sel.get_map():
            break
except KeyboardInterrupt:
    print("caught keyboard interrupt, exiting")
except:
    print("uncaught error, exiting")
finally:
    sel.close()
    sys.exit(1)

THIS IS THE ORIGINAL CODE (Echo server and client) OF THE MASTER REPO TUTS:
gitserver.py
#!/usr/bin/env python3

import sys
import socket
import selectors
import types

sel = selectors.DefaultSelector()

def accept_wrapper(sock):
    conn, addr = sock.accept()  # Should be ready to read
    print("accepted connection from", addr)
    conn.setblocking(False)
    data = types.SimpleNamespace(addr=addr, inb=b"", outb=b"")
    events = selectors.EVENT_READ | selectors.EVENT_WRITE
    sel.register(conn, events, data=data)

def service_connection(key, mask):
    sock = key.fileobj
    data = key.data
    if mask & selectors.EVENT_READ:
        recv_data = sock.recv(1024)  # Should be ready to read
        if recv_data:
            data.outb += recv_data
        else:
            print("closing connection to", data.addr)
            sel.unregister(sock)
            sock.close()
    if mask & selectors.EVENT_WRITE:
        if data.outb:
            print("echoing", repr(data.outb), "to", data.addr)
            sent = sock.send(data.outb)  # Should be ready to write
            data.outb = data.outb[sent:]

if len(sys.argv) != 3:
    print("usage:", sys.argv[0], "<host> <port>")
    sys.exit(1)

host, port = sys.argv[1], int(sys.argv[2])
lsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
lsock.bind((host, port))
lsock.listen()
print("listening on", (host, port))
lsock.setblocking(False)
sel.register(lsock, selectors.EVENT_READ, data=None)

try:
    while True:
        events = sel.select(timeout=None)
        for key, mask in events:
            if key.data is None:
                accept_wrapper(key.fileobj)
            else:
                service_connection(key, mask)
except KeyboardInterrupt:
    print("caught keyboard interrupt, exiting")
finally:
    sel.close()

gitclient.py
#!/usr/bin/env python3

import sys
import socket
import selectors
import types

sel = selectors.DefaultSelector()
messages = [b"Message 1 from client.", b"Message 2 from client."]

def start_connections(host, port, num_conns):
    server_addr = (host, port)
    for i in range(0, num_conns):
        connid = i + 1
        print("starting connection", connid, "to", server_addr)
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setblocking(False)
        sock.connect_ex(server_addr)
        events = selectors.EVENT_READ | selectors.EVENT_WRITE
        data = types.SimpleNamespace(
            connid=connid,
            msg_total=sum(len(m) for m in messages),
            recv_total=0,
            messages=list(messages),
            outb=b"",
        )
        sel.register(sock, events, data=data)

def service_connection(key, mask):
    sock = key.fileobj
    data = key.data
    if mask & selectors.EVENT_READ:
        recv_data = sock.recv(1024)  # Should be ready to read
        if recv_data:
            print("received", repr(recv_data), "from connection", data.connid)
            data.recv_total += len(recv_data)
        if not recv_data or data.recv_total == data.msg_total:
            print("closing connection", data.connid)
            sel.unregister(sock)
            sock.close()
    if mask & selectors.EVENT_WRITE:
        if not data.outb and data.messages:
            data.outb = data.messages.pop(0)
        if data.outb:
            print("sending", repr(data.outb), "to connection", data.connid)
            sent = sock.send(data.outb)  # Should be ready to write
            data.outb = data.outb[sent:]

if len(sys.argv) != 4:
    print("usage:", sys.argv[0], "<host> <port> <num_connections>")
    sys.exit(1)

host, port, num_conns = sys.argv[1:4]
start_connections(host, int(port), int(num_conns))

try:
    while True:
        events = sel.select(timeout=1)
        if events:
            for key, mask in events:
                service_connection(key, mask)
        # Check for a socket being monitored to continue.
        if not sel.get_map():
            break
except KeyboardInterrupt:
    print("caught keyboard interrupt, exiting")
finally:
    sel.close()

A: I was able to get it working using a custom created signal and adding handle code for it. Please find it below:
SERVER.PY
import sys
import socket
import selectors
import types

sel = selectors.DefaultSelector()
messages = [b"Server", b"process"]

def accept_wrapper(sock, host, port):
    conn, addr = sock.accept()  # Should be ready to read
    print("accepted connection from", addr)
    conn.setblocking(False)
    data = types.SimpleNamespace(
            host=host,
            port=port,
            addr=addr,
            recv_total=0,
            sent_total=0,
            messages=list(messages),
            inb=b"",
            outb=b"",
        )
    events = selectors.EVENT_READ | selectors.EVENT_WRITE
    sel.register(conn, events, data=data)

def service_connection(key, mask):
    sock = key.fileobj
    data = key.data
    ex = False
    if mask & selectors.EVENT_READ:
        recv_data = sock.recv(1024)
        print("received", repr(recv_data), "from connection", data.addr)
        if recv_data:
            data.inb += recv_data

        if not recv_data and not data.messages:
            print("closing connection", data.addr)
            sel.unregister(sock)
            sock.close()
        if (recv_data.decode() == "exit" or "exit" in recv_data.decode()):
            ex = True
    if mask & selectors.EVENT_WRITE:
        if not data.messages and ex:
            print("closing connection", data.addr)
            sel.unregister(sock)
            sock.close()
        if not data.outb and data.messages:
            data.outb = data.messages.pop(0)
        if data.outb:
            print("echoing", data.outb, "to", data.addr)
            sent = sock.send(data.outb)
            data.outb = data.outb[sent:]

if len(sys.argv) != 3:
    print("usage:", sys.argv[0], "<host> <port>")
    sys.exit(1)

host, port = sys.argv[1], int(sys.argv[2])
lsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
lsock.bind((host, port))
lsock.listen()
print("listening on", (host, port))
lsock.setblocking(False)
sel.register(lsock, selectors.EVENT_READ, data=None)

try:
    while True:
        events = sel.select(timeout=None)
        for key, mask in events:
            if key.data is None:
                accept_wrapper(key.fileobj, host, port)
            else:
                service_connection(key, mask)
except KeyboardInterrupt:
    print("caught keyboard interrupt, exiting")
except Exception as e:
    print("uncaught error, exiting", e)
finally:
    sel.close()

CLIENT.PY
import sys
import socket
import selectors
import types

sel = selectors.DefaultSelector()
messages = [b"Client", b"exit"]

def start_connections(host, port, num_conns):
    server_addr = (host, port)
    for i in range(0, num_conns):
        connid = i + 1
        print("starting connection", connid, "to", server_addr)
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setblocking(False)
        sock.connect_ex(server_addr)
        events = selectors.EVENT_READ | selectors.EVENT_WRITE
        data = types.SimpleNamespace(
            connid=connid,
            host=host,
            port=port,
            addr=port,
            recv_total=0,
            sent_total=0,
            messages=list(messages),
            inb=b"",
            outb=b"",
        )
        sel.register(sock, events, data=data)

def service_connection(key, mask):
    sock = key.fileobj
    data = key.data
    ex = False
    if mask & selectors.EVENT_READ:
        recv_data = sock.recv(1024)
        print("received", repr(recv_data), "from connection", data.connid)
        if recv_data:
            data.recv_total += len(recv_data)
            data.inb += recv_data

        if not recv_data and not data.messages:
            print("closing connection", data.connid)
            sel.unregister(sock)
            sock.close()
        if (recv_data.decode() == "exit" or "exit" in recv_data.decode()):
            ex = True
    if mask & selectors.EVENT_WRITE:
        if not data.messages and ex:
            print("closing connection", data.connid)
            sel.unregister(sock)
            sock.close()
        if not data.outb and data.messages:
            data.outb = data.messages.pop(0)
        if data.outb and data.inb:
            print("sending", data.outb, "to connection", data.connid)
            sent = sock.send(data.outb)
            data.outb = data.outb[sent:]

if len(sys.argv) != 4:
    print("usage:", sys.argv[0], "<host> <port> <num_connections>")
    sys.exit(1)

host, port, num_conns = sys.argv[1:4]
start_connections(host, int(port), int(num_conns))

try:
    while True:
        events = sel.select(timeout=1)
        if events:
            for key, mask in events:
                service_connection(key, mask)
        else:
            break
        if not sel.get_map():
            break
except KeyboardInterrupt:
    print("caught keyboard interrupt, exiting")
except Exception as e:
    print("uncaught error, exiting", e)
finally:
    sel.close()
    sys.exit(1)


text:
Q: How to trace class field accesses of certain classes only in Scala? I would like to use variable tracer for Scala programs which traces reads and writes of certain class fields.
For example, if I have a custom actor class like:
class Server extends Actor {
  var counter = 0

  def receive = {
    case A                   => counter += 1
    case B if (counter == 0) => ...
    case B =>                   ...
  }
}

The class uses Akka's actor type.
I want to trace all fields of classes which inherit from Actor such as counter and distinguish between reads and writes. Note that I do not want to trace other class fields!
Is there any tracer framework for Scala which allows tracing reads/writes of class fields for certain classes only?
If there is no other way, I am also willing to instrument the Scala code, changing all fields to a custom type with operators. In this case I would need some instrumentation framework for Scala code.

A: I have asked here: https://users.scala-lang.org/t/how-to-instrument-source-code-of-existing-scala-libraries/4717
They recommended something like https://scalameta.org/

redpajama_set_name: RedPajamaStackExchange


text: Q: how to use a USB Webcamera without NDK? I am trying to connect USB web camera to my Android phone and capture images using the web camera. I want to do this without using any Library. As far as I see, I could not find any Android API to support USB web camera. I see a lot of applications on the PlayStore doing the job.


text:
Q: Side effect function is not getting called in Cmd.run using redux-loop I am working on a react redux application where in, on a button click I need to change my window location.
As of now, I am dispatching the button click action and trying to achieve the navigation in reducer using redux-loop.
Component js
class Component {
 constructor() {
  super()
 }

 render() {
  return (
   <button onClick={() => this.props.onButtonClick()}>Navigate</button>
  )
 }

}

 const mapDispatchToProps = (dispatch) => {
    return {
        "onButtonClick": () => dispatch(handleClick())
    };
}

Action js
export const handleClick = () => ({
    type: NAVIGATE
});

Reducer js
export default (state = {}, action) => {
    if (action.type === NAVIGATE) {
        return loop(state, Cmd.run(navigateTo));
    }
};

Effect js
export const navigateTo = () => {
 window.location = "https://www.stackoverflow.com";
}

Apart from this action, I have lot many actions that involve side effect as well as state manipulation, hence redux-loop.
I have two questions:

*

*Control is not going into navigateTo() on button click. What am I doing wrong?

*I feel reducer is not a right place for it as we are not manipulating state here.
What would be the best place to put this piece of code when button click action is dispatched?

A: the code you have looks correct. Did you use the store enhancer when creating your redux store? Did you try setting a breakpoint in your reducer and verifying it gets called as you expect? https://redux-loop.js.org/docs/tutorial/Tutorial.html


text:
Q: Align beam endings at angled grating in pst-optexp I am trying to replicate an optical setup used for CPA using pst-optexp. My current code is the following:
\begin{pspicture}(18,20)
    \Large
    \definecolor{passiveFiberColor}{HTML}{FF8000}
    \definecolor{activeFiberColor}{HTML}{0080FF}
    \definecolor{fiberLoopColor}{HTML}{8000FF}
    \definecolor{dispersionFiberColor}{HTML}{80FF00}
    \definecolor[ps]{bl}{rgb}{tx@addDict begin Red Green Blue end}%
    \psset[optexp]{fiber=none, usefiberstyle}

    \newpsstyle{Fiber}{linewidth=2\pslinewidth}
    \pnodes(1.5, 4){LaserIn}(2, 4){LaserOut}
    \pnodes (5, 4) {BSIn} (4, 3.5) {BSOut} (4, 4){BSCenter}
    \pnodes (7, 4) {MCenter} (6, 3) {Mout}
    \pnodes (5.5, 2.5) {GICenter} (6.5, 2.5) {GIOut}
    \pnodes (7.5, 2.5) {LIOut} (7, 2.5) {LICenter} (8, 2.5) {LIICenter} (8.5, 2.5) {LIIOut}
    \pnodes (10, 2.5) {GIICenter} (8.5, 3.5) {GIIOut}

    \drawbeam[beam, ArrowInside=->](LaserIn)(BSIn)

    %Stretcher stage
    \mirror[beam, mirrortype=extended, fillstyle=solid](BSIn)(MCenter)(Mout)
    \drawbeam[beam](Mout)(GICenter)
    %Fancy beams in stretcher
    \multido{\i=0+1}{40}{%
        \pstVerb{\i\space 650 400 sub 39 div mul 400 add tx@addDict begin wavelengthToRGB end}%
        \drawbeam[linecolor=bl, beamangle=\i\space 16 sub 0.2 mul](GICenter)(LICenter)%
        \drawbeam[linecolor=bl, loadbeampoints](LICenter)(LIICenter)%
        \drawbeam[linecolor=bl, loadbeampoints, beamangle=\i\space 16 sub 0.125 mul -1 mul](LIICenter)(GIICenter)%
        \drawbeam[linecolor=bl, loadbeampoints](GIICenter)(GIIOut)%
    }%
    \optgrating[reverse, angle=0, gratingalign=c, fillstyle=solid](Mout)(GICenter)(GIOut)
    \lens[fillstyle=solid](GIOut)(LIOut)
    \lens[fillstyle=solid](LIOut)(LIIOut)
    \optgrating[angle = 0, gratingalign = c, fillstyle=solid](LIIOut)(GIICenter)(GIIOut)
    \mirror[mirrortype=extended](GIICenter)(GIIOut)(GIICenter)

    %Amp stage
    \pnodes (4, 2.5) {AmpIn} (4, 0.5) {AmpOut}

    %Compressor stage
    \pnodes (4, -1) {BSIICenter} (5, -1) {BSIIOut}
    \pnodes (7, -1) {MIICenter} (6, 0) {MIIOut}
    \pnodes (5.5, 0.5) {GIIICenter} (6.5, 0.5) {GIIIOut}
    \pnodes (8.5, 0.5) {GIVCenter} (8, 1) {GIVOut}
    \pnode (7.5, -0.5) {MREFCenter}
    %Output
    \pnode(1.5, -1) {CPAOut}

    \drawbeam[beam, ArrowInside=->] (BSCenter) (AmpIn)
    \drawbeam[beam, ArrowInside=->] (AmpOut)(BSIICenter)
    \drawbeam[beam, ArrowInside=<->] (BSIICenter) (BSIIOut)
    \drawbeam[beam, ArrowInside = ->] (BSIICenter) (CPAOut)
    \pnodes (3.5, 2.5) {RectLowerX} (4.5, 0.5) {RectUpperX}
%
    \beamsplitter(BSIn)(BSCenter)(BSOut){}
    \psframe[fillstyle=solid, fillcolor=red!40!black](RectLowerX)(RectUpperX)

    \beamsplitter(AmpOut)(BSIICenter)(BSIIOut)
    \mirror[mirrortype=extended](BSIIOut)(MIICenter)(MIIOut)
    \mirror[beam, mirrortype=extended](GIVCenter)(MREFCenter)(GIVCenter)
    %Fancy beams in compressor
    \multido{\i=0+1}{40}{%
    \pstVerb{\i\space 650 400 sub 39 div mul 400 add tx@addDict begin wavelengthToRGB end}%
        \drawbeam[linecolor=bl, beamangle=\i\space 16 sub 0.2 mul](GIIICenter)(GIVCenter)%
        \drawbeam[linecolor=bl, loadbeampoints](GIVCenter)(MREFCenter)
    }%
    \drawbeam[beam](MIICenter)(GIIICenter)
    \optgrating[reverse, angle = 0, gratingalign = c, fillstyle=solid] (MIIOut)(GIIICenter)(GIIIOut)
    \optgrating[angle = -45, fillstyle=solid](GIIIOut)(GIVCenter)(MREFCenter)

    \drawbeam[beam] (MIICenter) (BSIIOut)

\end{pspicture}

My result looks like this:

It looks quite close to what I want, but in the lower compressor part I have issues with non-overlapping expanded beams. How can I fix that?
Sidenote: Yes, the code is messy, I'll have to clean up later, but if there are any improvements visible, I'm open for them, too.

A: The main advantage of \drawbeam is connecting components, without knowing about the actual shape, reflection and transmission behavior. You haven't used that at all, so that \drawbeam starts at a plane through the given node, but not at the grating component. That's what your observing as error in the compressor.
All your \drawbeam uses could have been replaced by \psline.
To connect components you can e.g. give them names with compname. You can find a very extensive description with many examples in section "9 Connecting components" of the pst-optexp manual.
Also, there is an optexp component, which draws components on top of the beams, although they are defined before the beams.
\documentclass{standalone}
\usepackage{pst-optexp}
\begin{document}
\begin{pspicture}(0,-2)(11,5)
  \begin{optexp}
    \definecolor[ps]{bl}{rgb}{tx@addDict begin Red Green Blue end}%
    \psset[optexp]{mirrortype=extended, gratingalign=c}

    \pnodes(1.5, 4){LaserIn}(2, 4){LaserOut}
    \pnodes (5, 4) {BSIn} (4, 3.5) {BSOut} (4, 4){BSCenter}
    \pnodes (7, 4) {MCenter} (6, 3) {Mout}
    \pnodes (5.5, 2.5) {GICenter} (6.5, 2.5) {GIOut}
    \pnodes (7.5, 2.5) {LIOut} (7, 2.5) {LICenter} (8, 2.5) {LIICenter} (8.5, 2.5) {LIIOut}
    \pnodes (10, 2.5) {GIICenter} (8.5, 3.5) {GIIOut}

    %Stretcher stage
    \mirror[compname=StretcherM1](BSIn)(MCenter)(Mout)
    \optgrating[reverse, fillstyle=solid, compname=StretcherG1](Mout)(GICenter)(GIOut)
    \lens[compname=StretcherL1](GIOut)(LIOut)
    \lens[compname=StretcherL2](LIOut)(LIIOut)
    \optgrating[compname=StretcherG2, fillstyle=solid](LIIOut)(GIICenter)(GIIOut)
    \mirror[compname=StretcherM2](GIICenter)(GIIOut)(GIICenter)

    %Fancy beams in stretcher
    \multido{\i=0+1}{40}{%
        \pstVerb{\i\space 650 400 sub 39 div mul 400 add tx@addDict begin wavelengthToRGB end}%
        \drawbeam[linecolor=bl, beamangle=\i\space 16 sub 0.2 mul, n=1.3]{StretcherG1}{StretcherL1}{StretcherL2}{StretcherG2}%
        \drawbeam[linecolor=bl, loadbeampoints]{StretcherG2}{StretcherM2}%
    }%

%     %Amp stage
     \pnodes (4, 2.5) {AmpIn} (4, 0.5) {AmpOut}

%     %Compressor stage
     \pnodes (4, -1) {BSIICenter} (5, -1) {BSIIOut}
     \pnodes (7, -1) {MIICenter} (6, 0) {MIIOut}
     \pnodes (5.5, 0.5) {GIIICenter} (6.5, 0.5) {GIIIOut}
     \pnodes (8.5, 0.5) {GIVCenter} (8, 1) {GIVOut}
     \pnode (7.5, -0.5) {MREFCenter}
%     %Output
     \pnode(1.5, -1) {CPAOut}

% %
     \beamsplitter[compname=BS1](BSIn)(BSCenter)(BSOut)
     \optbox[optboxsize=2 1, fillstyle=solid, fillcolor=red!40!black, compname=Amp](BSCenter)(BSIICenter)

     \beamsplitter[compname=BS2](AmpOut)(BSIICenter)(BSIIOut)
     \mirror[compname=CompressorM1](BSIIOut)(MIICenter)(MIIOut)
     \mirror[compname=CompressorM2](GIVCenter)(MREFCenter)(GIVCenter)
     \optgrating[reverse, fillstyle=solid, compname=CompressorG1] (MIIOut)(GIIICenter)(GIIIOut)
     \optgrating[angle = -45, fillstyle=solid, compname=CompressorG2](GIIIOut)(GIVCenter)(MREFCenter)

     %Fancy beams in compressor
     \multido{\i=0+1}{40}{%
     \pstVerb{\i\space 650 400 sub 39 div mul 400 add tx@addDict begin wavelengthToRGB end}%
         \drawbeam[linecolor=bl, beamangle=\i\space 16 sub 0.2 mul]{CompressorG1}{CompressorG2}%
         \drawbeam[linecolor=bl, loadbeampoints]{CompressorG2}{CompressorM2}
       }%

     % finally draw all beam between the respective components
       \drawbeam[ArrowInside=->, ArrowInsideMinLength=1](LaserIn){BS1}{StretcherM1}{StretcherG1}
       \drawbeam[ArrowInside=->, ArrowInsideMinLength=1, beaminsidefirst]{BS1}{Amp}{BS2}{CompressorM1}{CompressorG1}
       \drawbeam[ArrowInside=->, ArrowInsideMinLength=1, beaminsidefirst]{BS2}(CPAOut)
    \end{optexp}

\end{pspicture}
\end{document}


text:
Q: how to make jquery show and hide image i am trying to add some functionality to a question i recently posted.
once you scroll down the page 200px the image changes size.
I also want to add the following functions but cant get it to work.
1) when you scroll down the screen i want the background image to disappear but once you scroll back up the page i want it to reappear.
is this easily achieved???
thanks for your help.
please update my fiddle.
http://jsfiddle.net/LLbAu/6/
$( window ).scroll(function() {
 if($(window).scrollTop() > 200){

    $("#profile-pic-bg img").css({
        "position": "absolute",
        "top": "20px",
        "left":"5px" ,
        "width":'50px'
    });

 }else{
     $('#profile-pic-bg img').css({'width': '145px',});
 }

});

A: You should deal with the css code by using a class inside css and with jquery, just add and remove that class. Than it's easyer to change stuff.
$( window ).scroll(function() {
 if($(this).scrollTop() > 200)

    $("#profile-pic-bg img").addClass('scrolled');

 else
     $("#profile-pic-bg img").removeClass('scrolled');

});

and the css
    #profile-pic-bg img {
            position: absolute;
            top: 20px;
            left: 5px;
            width:50px;
    }
#profile-pic-bg img.scrolled {
    width: 145px;
}

}

A: Try $(document).scrollTop()
also don't forget $(document).ready(function(){ });
else open your console and find the errors :)


text:
Q: Can linux-lowlatency be used with UEFI secure boot? I am using the linux-lowlatency package as my main kernel (as the generic kernel produces horrible lags while playing audio to my bluetooth speakers).
I regularly find that my /boot partition is full, due partly to having the generic kernel installed alongside the low latency one. So I wanted to remove the linux-generic package, but I found that it will also remove the linux-signed-generic package.
linux-signed-generic is described as: "Signed with Ubuntu EFI key".
There is no linux-signed-lowlatency.
So here is my questions:

*

*can I use the low latency kernel package with EFI secure boot ?

*(is linux-lowlatency also signed with Ubuntu EFI key ?)

A: Secure boot will let the Microsoft signed shim.efi boot, which then runs the Canonical signed grubx64.efi.  Now this Canonical signed grub can run either signed or unsigned (by Canonical) Linux kernels -- some features will not be available on the unsigned kernels at boot, but you probably won't notice.  Last time I tried this was with the 12.10 kernels, so things may have changed.


text:
Q: Can't load rule as lexer or parser - Antlr4 I am getting an error Can't load Chat as lexer or parser
when running the command grun Chat chat
I am following the instructions at https://tomassetti.me/antlr-mega-tutorial/#setup-antlr
Using python on a Mac OS and here's my bash_profile details :-
export CLASSPATH=".:/usr/local/lib/antlr-4.7.1-complete.jar:$CLASSPATH"
alias antlr4='java -Xmx500M -cp "/usr/local/lib/antlr-4.7.1-complete.jar:$CLASSPATH" org.antlr.v4.Tool'
alias grun='java -Xmx500M -cp "/usr/local/lib/antlr-4.7.1-complete.jar:$CLASSPATH" org.antlr.v4.gui.TestRig'

Commands run :-
To create the python files: antlr4 -Dlanguage=Python3 Chat.g4
The following files are created when the above command is run :-
chat.interp, chat.tokens, chatLexer.interp, ChatLexer.py, ChatLexer.tokens, ChatListener,py, ChatParse.py

To run the grun tool: grun Chat chat
I tried different parser rules but get the same error.

A: grun is a Java tool that expects the lexer and parser to exist as Java classes that it can load and instantiate. So you'll need to generate Java code from the grammar and then compile it using javac before you can use grun.
If you can't generate Java from your grammar (because your grammar contains Python actions for example), you can't use grun.


text:
Q: Mac Apache Ant version 1.8.2 instead of 1.9.6 I've downloaded the last apache ant version on my Mac but the version seems the old one.
Any idea?
myMac:~ mauri$ brew install ant
==> Downloading https://homebrew.bintray.com/bottles/ant-1.9.7.el_capitan.bottle.tar.gz
######################################################################## 100,0%
==> Pouring ant-1.9.7.el_capitan.bottle.tar.gz
  /usr/local/Cellar/ant/1.9.7: 1,611 files, 34.9M
myMac:~ mauri$
myMac:~ mauri$ ant -version
Apache Ant(TM) version 1.8.2 compiled on December 20 2010
myMac:~ mauri$
myMac:~ mauri$ ./Downloads/apache-ant-1.9.6/bin/ant -version
Apache Ant(TM) version 1.8.2 compiled on December 20 2010
myMac:~ mauri$ uname -a
Darwin myMac 15.6.0 Darwin Kernel Version 15.6.0: Mon Aug 29 20:21:34 PDT 2016; root:xnu-3248.60.11~1/RELEASE_X86_64 x86_64

here the relative export variables.
myMac:~ mauri$ export ANT_HOME=/Users/mauri/Downloads/apache-ant-1.9.6
myMac:~ mauri$ export CLASSPATH=$ANT_HOME/lib:$CLASSPATH
myMac:~ mauri$ export PATH=$ANT_HOME/bin:$PATH
myMac:~ mauri$ ant -version
Apache Ant(TM) version 1.8.2 compiled on December 20 2010
myMac:~ mauri$ /Users/mauri/Downloads/apache-ant-1.9.6/bin/ant -version
Apache Ant(TM) version 1.8.2 compiled on December 20 2010
myMac:~ mauri$ which ant
/Users/mauri/Downloads/apache-ant-1.9.6/bin/ant
myMac:~ mauri$

here one more command what the core tasks mean?
myMac:~ mauri$ ant -diagnostics
------- Ant diagnostics report -------
Apache Ant(TM) version 1.8.2 compiled on December 20 2010

-------------------------------------------
 Implementation Version
-------------------------------------------
core tasks     : 1.8.2 in file:/Library/Java/Extensions/selenium-html-runner-3.0.1.jar

-------------------------------------------
 ANT PROPERTIES
-------------------------------------------
ant.version: Apache Ant(TM) version 1.8.2 compiled on December 20 2010
ant.java.version: 1.7
Is this the Apache Harmony VM? no
Is this the Kaffe VM? no
Is this gij/gcj? no
ant.core.lib: /Library/Java/Extensions/selenium-html-runner-3.0.1.jar
ant.home: /usr/local/Cellar/ant/1.9.7

-------------------------------------------
 ANT_HOME/lib jar listing
-------------------------------------------
ant.home: /usr/local/Cellar/ant/1.9.7
No such directory.

-------------------------------------------
 USER_HOME/.ant/lib jar listing
-------------------------------------------
user.home: /Users/mauri
No such directory.

I've tried to uninstall and install ANT again from brew, but the problem is still the same
myMac:OrgSight mauri$ brew uninstall ant
Uninstalling /usr/local/Cellar/ant/1.9.7... (1,611 files, 34.9M)
myMac:OrgSight mauri$ brew install ant
==> Downloading https://homebrew.bintray.com/bottles/ant-1.9.7.el_capitan.bottle.tar.gz
Already downloaded: /Users/mauri/Library/Caches/Homebrew/ant-1.9.7.el_capitan.bottle.tar.gz
==> Pouring ant-1.9.7.el_capitan.bottle.tar.gz
  /usr/local/Cellar/ant/1.9.7: 1,611 files, 34.9M
myMac:OrgSight mauri$ which ant
/usr/local/bin/ant
myMac:OrgSight mauri$ ant -version
Apache Ant(TM) version 1.8.2 compiled on December 20 2010
myMac:OrgSight mauri$ /usr/local/Cellar/ant/1.9.7/bin/ant -version
Apache Ant(TM) version 1.8.2 compiled on December 20 2010

A: I realized after relooking at the post, that you tried to install ant, it has downloaded ant 1.9.7 version and extraction seemed to be /usr/local/Cellar/ant/1.9.7.
Or you may use the downloaded directory which is /Users/mauri/Downloads/apache-ant-1.9.6
So, all you need to do is to set the environment variables to the right installation path.
Run the following commands on the terminal.
export ANT_HOME=/Users/mauri/Downloads/apache-ant-1.9.6
export CLASSPATH=$ANT_HOME/lib:$CLASSPATH
export PATH=$ANT_HOME/bin:$PATH

Now ant -v should give right result.
Note that the above changes are only for the command session. If you want to apply it permanently, then update the same in your ~/.bash_profile file.
UPDATE:
If the is continue to persist(i.e., referring to older version of ant), it is possible to have softlink to older version. Try to remove that.

A: I'm still trying to the reason behind that, but The Ant wrapper script sources some files from /etc if present, so the global installation may leak into your setup regardless. I guess the key is
core tasks  : 1.8.2 in

file:/Library/Java/Extensions/selenium-html-runner-3.0.1.jar" - whatever has
put Selenium there, it takes precedence.
I want to thank Stefan Bodewig from Apache ANT for this great insight
myMac:~ mauri$ cd /Library/Java/Extensions
myMac:Extensions mauri$ l
total 30536
-rw-r--r--@ 1 root  wheel    15M  4 Dez 12:12 selenium-html-runner-3.0.1.jar
myMac:Extensions mauri$ mv selenium-html-runner-3.0.1.jar ~/
myMac:Extensions mauri$ which ant
/Users/mauri/Downloads/apache-ant-1.9.6/bin/ant
myMac:Extensions mauri$ ant -version
Apache Ant(TM) version 1.9.6 compiled on June 29 2015


text:
Q: Sinatra/ActiveRecord can't handle simultaneous requests? This is my first Sinatra project and I'm pretty late in and I'm realizing that when make multiple requests at once that use ActiveRecord that I run into problems.  If I only make one request, each one works on its own.  But when I call both at once, I get failure.
So far I've narrowed it down to the problem being two ActiveRecord requests simultaneously. Maybe I'm not setting up ActiveRecord correctly?  I use PostgreSQL because Heroku uses it, and am no inclined to change. (The issue happens on Heroku, too.)
Here's the log:
192.168.1.113 - - [30/Sep/2012:10:33:00 MDT] "GET /version/current?platform=android HTTP/1.1" 200 33
 - -> /version/current?platform=android ActiveRecord::StatementInvalid - NoMethodError: undefined method `fields' for nil:NilClass: SELECT  "rankings".* FROM "rankings"  WHERE "rankings"."user_id" = 1 LIMIT 1:
/Users/zablanc/.rvm/gems/ruby-1.9.3-head@emm/gems/activerecord-3.2.7/lib/active_record/connection_adapters/postgresql_adapter.rb:667:in `block in exec_query'

...

Warning! Rack::Session::Cookie data size exceeds 4K.
Warning! Rack::Session::Cookie failed to save session. Content dropped.

192.168.1.113 - - [30/Sep/2012:10:33:01 MDT] "GET /badges/all HTTP/1.1" 200 311
 - -> /badges/all
192.168.1.113 - - [30/Sep/2012:10:33:01 MDT] "GET /moves/ranking/all HTTP/1.1" 500 166185
 - -> /moves/ranking/all

I have no idea how to shut up those cookie warnings, tho they seem to have no effect on the app. Here's how I configure my app (in a config file I require from the main script):
enable :logging

use ActiveRecord::ConnectionAdapters::ConnectionManagement

use Rack::Session::Cookie, :key => 'rack.session',
                           :path => '/',
                           :expire_after => 31_536_000, # In seconds
                           :secret => 'jeowkfj...secret...kjn5'

ActiveRecord::Base.include_root_in_json = false

def establish_connection(url)
    db = URI.parse(url)

    ActiveRecord::Base.establish_connection(
        :adapter  => db.scheme == 'postgres' ? 'postgresql' : db.scheme,
        :host     => db.host,
        :port     => db.port,
        :username => db.user,
        :password => db.password,
        :database => db.path[1..-1],
        :encoding => 'utf8'
    )
end

configure :development do
    establish_connection('postgres://postgres:postgres@localhost:5432/emm')
end

configure :test do
    establish_connection('postgres://postgres:postgres@localhost:5432/emm-test')
end

configure :production do
    establish_connection(ENV['DATABASE_URL'])
end

I'm guessing I'm not setting up ActiveRecord right, but I think it's just like the tutorials I've seen.  What gives?

A: Sounds like you are using threads but have some non-thread-safe code in your application.
Which webserver are you using, which middleware are you using, which postgresql gem are you using, did you check to see that all your gems are thread-safe?


text:
Q: addObjectsFromArray to the beginning of an existing array I'm having trouble adding an existing array to the beginning of another array.
For example:
 MutableID array contains 1,2,3,4,5 & idArray array contains 6,7,8
self.MutableID.addObjectsFromArray(idArray as [AnyObject])
//currently puts values to the end of the array not the beginning

this code outputs 1,2,3,4,5,6,7,8 but I want it to output 6,7,8,1,2,3,4,5
I need the values added to the beginning of self.MutableID Any suggestions on how I can accomplish this?

A: self.MutableID.insertContentsOf(idArray as [AnyObject], at: 0)

A: This question is the Swift version of this question which solves the problem in Objective-C.
If we must, for whatever reason, be using Objective-C's NSArray or NSMutableArray, then we can simply use a Swift translation of the code in my answer over there:
let range = NSMakeRange(0, newArray.count)
let indexes = NSIndexSet(indexesInRange: range)
oldArray.insertObjects(newArray as [AnyObject], atIndexes: indexes)

Where oldArray is an NSMutableArray and newArray is NSArray or NSMutableArray.
Or the other approach, append and reassign:
oldArray = newArray.arrayByAddingObjectsFromArray(oldArray as [AnyObject])

But the most correct thing to do would be to use the Swift Array type, and then use the insertContentsOf(_: Array, at: Int) method, as fluidsonic's answer describes.

A: NSMutableArray has insertObjects method.
self.MutableID.insertObjects(otherArray as [AnyObject], atIndexes: NSIndexSet(indexesInRange: NSMakeRange(0, otherArray.count)))

Or you can assign the mutable array to a swift array and use insertContentsOf method ;)
self.MutableID = NSMutableArray(array: [1,2,3,4])
var otherArray = NSMutableArray(array: [6,7,8,9])

var swiftArr : [AnyObject] = self.MutableID as [AnyObject]
swiftArr.insertContentsOf(otherArray as [AnyObject], at: 0)


text:
Q: When will the 4.3 branch become EOL I have a wordpress setup which is v4.3.18. When will this branch (4.3) become End Of Life and stop receiving updates? I can't find anything offical

A: It is EOL. WordPress will backport security fixes when it can, but makes no promises for updates for anything except the latest version. You should have updated 3 years ago.

WordPress will be backported security updates when possible, but there are no guarantee and no timeframe for older releases. There are no fixed period of support nor Long Term Support (LTS) version such as Ubuntu's. None of these are safe to use, except the latest series, which is actively maintained.

https://codex.wordpress.org/Supported_Versions


text:
Q: Remove grey header-box in AmCharts While plotting some historical data on a chart I stumbled on this annoying grey box that I can't get rid of.
Basically I started with this example: http://www.amcharts.com/demos/date-based-data/ and did some slight modifications (removed chartScrollbar).
The chart is using type: serial with theme: light.
Still haven't found anything in the documentation http://docs.amcharts.com/3/javascriptcharts/ that resembles this.
I've tried 'guides', 'graphs', 'chartScrollBar' but nothing seems to work.
Appreciate any help in this.
Chart with grey header-box:

AmCharts conf:
        chart = AmCharts.makeChart("chartdiv", {
            "type": "serial",
            "theme": "light",
            "marginLeft": 0,
            "marginRight": 0,
            "autoMarginOffset": 0,
            "path": "http://www.amcharts.com/lib/3/",
            "dataDateFormat": "YYYY-MM-DD",
            "valueAxes": [{
                "id": "v1",
                "axisAlpha": 0,
                "position": "left"
            }],
            "balloon": {
                "borderThickness": 1,
                "shadowAlpha": 0
            },
            "graphs": [{
                "id": "g1",
                "bullet": "round",
                "bulletBorderAlpha": 1,
                "bulletColor": "#FFFFFF",
                "bulletSize": 5,
                "hideBulletsCount": 50,
                "lineThickness": 2,
                "title": "red line",
                "useLineColorForBulletBorder": true,
                "valueField": "value",
                "balloonText": "
[[category]]
[[value]]
"
            }],
            "chartScrollbar": {
                "enabled": false
            },
            "chartCursor": {
                "pan": true,
                "valueLineEnabled": true,
                "valueLineBalloonEnabled": true,
                "cursorAlpha": 0,
                "valueLineAlpha": 0.2
            },
            "categoryField": "date",
            "categoryAxis": {
                "parseDates": true,
                "dashLength": 1,
                "minorGridEnabled": true,
                "position": "bottom"
            },
            "export": {
                "enabled": false
            },
            "dataProvider": chartData
        });

A: The "grey box" is chart scrollbar. By default chart does not display the scrollbar. So to remove it simply remove it from your chart config altogether:
chart = AmCharts.makeChart("chartdiv", {
    "type": "serial",
    "theme": "light",
    "marginLeft": 0,
    "marginRight": 0,
    "autoMarginOffset": 0,
    "path": "http://www.amcharts.com/lib/3/",
    "dataDateFormat": "YYYY-MM-DD",
    "valueAxes": [{
        "id": "v1",
        "axisAlpha": 0,
        "position": "left"
    }],
    "balloon": {
        "borderThickness": 1,
        "shadowAlpha": 0
    },
    "graphs": [{
        "id": "g1",
        "bullet": "round",
        "bulletBorderAlpha": 1,
        "bulletColor": "#FFFFFF",
        "bulletSize": 5,
        "hideBulletsCount": 50,
        "lineThickness": 2,
        "title": "red line",
        "useLineColorForBulletBorder": true,
        "valueField": "value",
        "balloonText": "
[[category]]
[[value]]
"
    }],
    "chartCursor": {
        "pan": true,
        "valueLineEnabled": true,
        "valueLineBalloonEnabled": true,
        "cursorAlpha": 0,
        "valueLineAlpha": 0.2
    },
    "categoryField": "date",
    "categoryAxis": {
        "parseDates": true,
        "dashLength": 1,
        "minorGridEnabled": true,
        "position": "bottom"
    },
    "export": {
        "enabled": false
    },
    "dataProvider": chartData
});


text:
Q: Adding custom mime type to contacts in android I am trying to write an app that store data for the user for
each contacts he chooses.
I want to add to each user a custom provider (like facebook does)
that on press will open my app and allow the user to review the stored data.
I have created a custom provider following this guide:
http://www.c99.org/2010/01/23/writing-an-android-sync-provider-part-2/
but the custom provider does not appear on my contact list,
I have tried to change my MIME_TYPE to vnd.com.google.cursor.item/contact_user_defined_field
that didnt help either (when using third party app it showed my provider but without my icon)
my contact definition is this:
<ContactsSource xmlns:android="http://schemas.android.com/apk/res/android">
 <ContactsDataKind
  android:icon="@drawable/ic_launcher"
  android:mimeType="vnd.android.cursor.item/vnd.MyPackageName.profile"
  android:summaryColumn="data2"
  android:detailColumn="data3"
  android:detailSocialSummary="true" />
</ContactsSource>

and my relevant code is this:
String MIME_TYPE  "vnd.android.cursor.item/vnd.MyPackageName.profile";

ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
int rawContactInsertIndex =ops.size();//(int)Contact_RAW_ID;
ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
   .withValue(RawContacts.ACCOUNT_TYPE, null)
   .withValue(RawContacts.ACCOUNT_NAME,null )
   .build());

ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
   .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
   .withValue(Data.MIMETYPE,Phone.CONTENT_ITEM_TYPE)
   .withValue(Phone.NUMBER, "9X-XXXXXXXXX")
   .build());

ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
   .withValueBackReference(Data.RAW_CONTACT_ID, 0)
   .withValue(Data.MIMETYPE,StructuredName.CONTENT_ITEM_TYPE)
   .withValue(StructuredName.DISPLAY_NAME, "John Doe")
   .build());

ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
   .withValueBackReference(Data.RAW_CONTACT_ID, 0)
   .withValue(Data.MIMETYPE,Email.CONTENT_ITEM_TYPE)
   .withValue(Email.ADDRESS, "John Doe")
   .build());

ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
   .withValueBackReference(Data.RAW_CONTACT_ID, 0)
   .withValue(Data.MIMETYPE,Phone.CONTENT_ITEM_TYPE)
   .withValue(Phone.NUMBER, "1234567890")
   .build());

ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
    .withValueBackReference(Data.RAW_CONTACT_ID, 0)
    .withValue(Data.MIMETYPE,MIME_TYPE)
    .withValue(Data.DATA1, "Custom Field")
    .withValue(Data.DATA2, "Custom Field Header")
    .withValue(Data.DATA3, "Custom Field Body")
    .build());

ContentProviderResult[] res = CallerActivity.getContentResolver().applyBatch
 (ContactsContract.AUTHORITY, ops);

Edit (06/01/2013):
managed to fix it,
if you want to make your contact visible make sure that the account name you give the provider
is the name as the account of the contact.
now I have a diferent problem, in 4.0 devices the contacts becomes duplicates of each other
I tried to do manually aggregation but in some devices it works and in some it doesn't.


text:
Q: Optimise multiple OR query I have a Database table where I need to validate if a user has entered in the same or partly the same information.
Here is what I'm thinking
The db layout
rec_id (pk), user_id,
name, phone, address_1, address_2, zip,
company, co_phone, co_address_1, co_address_2, co_zip,
billing, bi_phone, bi_address_1, bi_address_2, bi_zip

The Query
SELECT rec_id
FROM tbl_name
WHERE user_id = '123456789'
OR '1112223333' IN (phone, co_phone, bi_phone)
OR 'John Doe' IN (name, business, billing)
OR '12345' IN (zip, co_zip, bi_zip)
OR '123 main street' IN (address_1, co_address_1, bi_address_1)
OR 'po box 123' IN (address_2, co_address_2, bi_address_2)

If any of the data matches (and yes the will be false positives) I need the old rec_id.
Wanted to know if there is a better way to do this?
Thanks

A: For this query to perform well you will need separate indexes for each of the columns you are testing. A combined index on all columns won't help at all for OR conditions (it would help if you had ANDs though).
However I would imagine that your query result in a full table scan regardless of which indexes you add. You might want to try using UNIONs instead of OR to see if that makes a difference:
SELECT rec_id FROM tbl_name WHERE tax_id = '123456789'
UNION
SELECT rec_id FROM tbl_name WHERE phone = '1112223333'
UNION
SELECT rec_id FROM tbl_name WHERE co_phone = '1112223333'
UNION
SELECT rec_id FROM tbl_name WHERE bi_phone = '1112223333'
UNION
SELECT rec_id FROM tbl_name WHERE name = 'John Doe'
UNION
SELECT rec_id FROM tbl_name WHERE business = 'John Doe'
UNION
SELECT rec_id FROM tbl_name WHERE billing = 'John Doe'
UNION
-- etc...

The idea of rewriting it like this is that now each subquery will be able to use an index (assuming of course that you have added the necessary indexes).


text:
Q: Check if a dependency is being injected in Angular As discussed here, IE is bad about caching things when using ajax (i.e., $route and $http).  A brilliant solution to this problem can be found here.
We use many angular apps on our site, so in an effort to ensure the caching issue doesn't occur for other developers working on other angular apps, I would like to add the above proposed solution to every Angular app on our site as a matter of course.  If our style guide included the following, a developer would be more likely to include it when building his own app, and would successfully avoid the very dangerous IE issue.  After all, not many developers I know actively develop in IE anymore.
var myApp = angular.module('myApp', ['ngRoute']);

myApp.config(['$routeProvider', '$httpProvider', function($routeProvider, $httpProvider) {
    $httpProvider.defaults.cache = false;
    if (!$httpProvider.defaults.headers.get) {
      $httpProvider.defaults.headers.get = {};
    }
    // disable IE ajax request caching
    $httpProvider.defaults.headers.get['If-Modified-Since'] = '0';
    // routes go here...
}]);

What this code does is force IE not to cache templates and to issue server requests for $http calls instead of pulling the results from its cache (which can be really bad if your data is dynamic -- which it may very well be).
The problem with adding the code above for every Angular app is that the app may or may not be injecting ngRoute into the app's dependencies.  If the ngRoute is not present, an injection error will occur.
So, the question is this:  Is it possible to do a check for the presence of an injected dependency in Angular?  I would love to be able to do something like the following:
var myapp = angular.module('ordersApp', [
    'ngTouch',
    'ngRoute',
    'ngAnimate',
    'myController'
]);

if(myapp.has_ngRoute) {
     myapp.config(['$routeProvider', '$httpProvider', function($routeProvider, $httpProvider) {
    $httpProvider.defaults.cache = false;
         if (!$httpProvider.defaults.headers.get) {
             $httpProvider.defaults.headers.get = {};
         }
         // disable IE ajax request caching
        $httpProvider.defaults.headers.get['If-Modified-Since'] = '0';
        // routes go here...
    }]);
}

A: There are two ways to address this:
1. Check if a service exists and run behaviour based on that
This answers your specific question - only run code if a service exists
You can use $injector.has(...) to see if a provider/service has been registered.
You can check to see if $routeProvider has been registered and configure the HTTP headers if it does exist.
Here is an example where we check for $routeProvider before configuring the $httpProvider.
// Cache configuration behaviour.
var configureCache = ['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.cache = false;
        if (!$httpProvider.defaults.headers.get) {
            $httpProvider.defaults.headers.get = {};
        }
        // disable IE ajax request caching
        $httpProvider.defaults.headers.get['If-Modified-Since'] = '0';
}];

angular.module('testApp', [
        // Test this by commenting this out.
        'ngRoute'
    ])
    .config(['$injector', function($injector){
        if ($injector.has('$routeProvider')){
            // If $routeProvider has been registered then
            // configure the $httpProvider.
            console.log('Has $routeProvider: configuring cache.');

            // Use `$injector.invoke(...)` so we can use
            // Angular dependency injection in our
            // configuration function above.
            $injector.invoke(configureCache);
        } else {
            // Otherwise don't do anything.
            console.log('Skipping cache configuration.');
        }
}]);

Here is the example in a Plunker:
http://plnkr.co/edit/orXOjMg0YZXDfwoqf9OD

2. Split your code into modules
Don't check if a module/service exists, use module dependencies to control this instead
With this method we get more flexibility. You define the caching behaviour
in its own module that has a dependency on ngRoute.
That way when you include your cache customisation behaviour you know ngRoute must exist because it's one of the dependencies!
This gives you three ways of controlling the routing/caching behaviour in your
application depending only on which modules you include:
No routes
angular.module('testApp', [
        // Don't add 'ngRoute' module dependency here
        // or alter the caching behaviour.
    ])

Routes but with default caching behaviour
angular.module('testApp', [
        'ngRoute'
    ])

Routes with custom caching behaviour
angular.module('testApp', [
        'noCacheRoutes'
    ])

In each case we've only had to change the module dependencies but have
changed the behaviour of the application in a known way.
Here is the example of splitting the cache configuration behaviour
into a separate module:
/**
 * We decide that it only make sense to use this
 * module along with `ngRoute` so define it as
 * a dependency here.
 */
angular.module('noCacheRoutes', [
        'ngRoute'
    ])
    .config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.cache = false;
        if (!$httpProvider.defaults.headers.get) {
            $httpProvider.defaults.headers.get = {};
        }
        // disable IE ajax request caching
        $httpProvider.defaults.headers.get['If-Modified-Since'] = '0';
    }]);

/**
 * Don't reference `ngRoute` here, let `noCacheRoutes`
 * bring it in as a transitive dependency.
 *
 * If later on you decide you don't need to change
 * the caching behaviour you can just replace `noCacheRoutes`
 * with `ngRoute` and don't need to make any further changes.
 */
angular.module('testApp', [
        'noCacheRoutes'
    ])
    .config(['$routeProvider', function($routeProvider) {
        // Configure your application routes here.
    }]);

A: As dicussed here AngularJs - get list of all registered modules, there is no method for getting module list, but you can extend angular's module method (see the accepted answer).


text:
Q: Using variables as classes in the HTML I have a several variables in my SASS file and i want to use them directly in my HTML as class or style.
I know i can use mapping function but, it's pretty tedious.
is there any other way to achieve it? simple way?
for example:
sass file:
$margin-base-vertical:30px 0;

html file:

 some things

A: That is not a good idea. You gonna end up with a really unmantainble code if you use classes that describe styles. Each time you want to change your style, you have to change the markup (HTML) and the CSS.
A best practice is to use semantic markup.
This is where sass turns out really powerful, you can use your variables like this way:
.some-container {
    margin: $margin-base-vertical;
}

EDIT:
The only alternative I can think about for your problem, is to declare a variable, and then use it on your class, after that, you will have the class you need for your markup.
SASS file
$margin-base-vertical: 30px 0;
.margin-base-vertical { margin: $margin-base-vertical; }

HTML

 some things


text:
Q: KOJS Binding Manual Subscription with Mapping Plugin I have a checkbox bound to my KOJS model.
<input type="checkbox" data-bind="checked:settings.remember">

I'm trying to update the database when the user changes the value of the checkbox. However, the viewmodel is updated after these jQuery functions:
$("input[type='checkbox']").click(function(){ });

$("input[type='checkbox']").change(function(){ });

$("input[type='checkbox']").mouseup(function(){ });

To put it another way, when I peek into my viewModel inside of those functions, it will return the value of the checkbox's value before the user had changed it. So if the checkbox was once true and now tells me false (and displays as false), the viewModel will still say true.
Is there some other jQuery function I could use that might occur after the binding occurs? Or can you think of any other clever way to call a function after my viewModel variable has changed? Note that my current viewModel declaration is:
var viewModel = {};
//...get some data from AJAX calls
ko.mapping.fromJSON(data, viewModel.'+file+');

where file is some dynamic value (I draw my viewModel from multiple databases)
I can solve the above problem with a hacky solution below (see my answer), but RP Niemeyer's answer suggests there is a better way with manual subscriptions. So far I haven't been able to figure out defining things within my viewModel along with using the mapping plugin.
Here's my code so far, though, of course, it won't work on the JSFiddle.

A: Generally, a good choice for this type of thing is to handle it in your view model itself.  For example, you can use a manual subscription against settings.remember (if it is an observable) and trigger your database call.
settings = {
  remember: ko.observable(false)
};

settings.remember.subscribe(function(newValue) {
    //run your logic here
}, settings);

The second argument to the subscribe call determines the value of this when the function runs.
If you are really forced to interact with your field changing outside of Knockout, then you would want to hook up a "change" handler, but not until after ko.applyBindings has been called.  Then your change event handler will run after the change handler that Knockout has already added to the element. However, if your content is in a template and gets re-rendered, then your handler would be lost.
I would highly recommend using the manual subscription approach.

A: RP Niemeyer's answer above might be much better than this, but here is my temporary fix that has solved my problem:
$("input[type='checkbox']").click(function() {
  viewModel.settings.remember($(this).is(":checked"));';
  //...AJAX it away
});


text:
Q: How to parameterize exceptions in JUnit5 with hemcrest? i want to test all different exceptions with one parameterized test using hemcrest for one method. So that means that Exception1.class, Exception2.class should be parameters. How do i parameterize them, and do it by using hemcrest?

A: Suppose your method under test returns distinct exceptions according to scenarios, you should parameterize both fixture (for scenarios) and expected (for exceptions).
With a Foo.foo(String input) method to test such as :
import java.io.FileNotFoundException;

public class Foo {
  public void foo(String input) throws FileNotFoundException {

    if ("a bad bar".equals(input)){
       throw new IllegalArgumentException("bar value is incorrect");
    }

    if ("inexisting-bar-file".equals(input)){
      throw new FileNotFoundException("bar file doesn't exit");
    }

  }
}

it could look like :
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.stream.Stream;

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.api.Assertions;

public class FooTest {

  @ParameterizedTest
  @MethodSource("fooFixture")
  void foo(String input, Class<Exception> expectedExceptionClass, String expectedExceptionMessage) {
    Assertions.assertThrows(
        expectedExceptionClass,
        () -> new Foo().foo(input),
        expectedExceptionMessage
    );

  }

  private static Stream<Arguments> fooFixture() {
    return Stream.of(
        Arguments.of("a bad bar", IllegalArgumentException.class, "bar value is incorrect"), Arguments.of("inexisting-bar-file", FileNotFoundException.class, "bar file doesn't exit"));

  }
}


text:
Q: jQuery ajaxSetup with ES6 How do I replicate the behavior of jQuery's ajaxSetup with vanilla JS (ES6 in this case)?
Here's what I'm trying to achieve. Currently I have in my app.js:
$(document).ready(()=>{
    $.ajaxSetup({
        data: {'_token': $('meta[name="csrf-token"]').attr('content')}
    });
 })

So when I perform any ajax request in any other file, _token will be include to the data json object that I'm providing, that way I don't have to specify _token on every call making sure that it's never missed.
How to do this with ES6 only?

A: Wrap the Fetch api and store your base data and merge that with whatever you send with it.

class MyFetch {
  constructor(data) {
    this.data = data
  }

  post(url, data) {
    let requestData = {
      ...this.data,
      ...data
    }
    return fetch(url, {
      method: 'POST',
      body: JSON.stringify(requestData)
    })
  }
}

let myFetch = new MyFetch({
  _token: 'helloworld'
})

myFetch.post('https://httpbin.org/post',{moreData:'more'})
  .then((res) => res.json())
  .then(json => {
    console.log('Data sent:', json.data)
  })


text:
Q: Check if limit exists and its value How to check if this limit exists: $$\lim_{(x,y)\rightarrow (0,0)}{ \frac{x^4y^4}{(x^2 + y^4)^3}}$$
Can I convert it to polar form ?
$$\frac{r^8 (\cos^4 (\theta)\sin^4(\theta)}{r^6 (\cos^6 (\theta) + r^6 \sin^{12} (\theta))} = \frac{r^2}{\cos^6(\theta) + 0} = 0$$

A: The limit does not exist.
If we appoach along either $x=0$ or $y=0$ we get a limit of zero, if we approach along $x=t^2$, $y=t$ we get a limit of $\frac{1}{8}$.

A: Consider $x(t)=t^2$, $y(t)=t$, so that the fraction behaves, as $t \to 0$, like a nonzero constant.


text:
Q: .HTACCESS subdomain redirecting I am having an issue with subdomain.. i have a subdomain content.domain.com
which i want to use for cookieless domain content..
but when i wrote it in website.. its automatically add full website url.. which i have added in .htaccess
can you please let me know how can i stop redirecting the subdomain ....
Please help......
here is code for htaccess for domain redicretion
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

A: *

*You can combine both rules into a single rule

*Using a RewriteCond you can omit a subdomain.

Have it like this:
RewriteEngine On

RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} !on
RewriteCond %{HTTP_HOST} ^(?!content\.domain\.com)(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NE]

Make sure you clear your browser cache while testing this change.


text:
Q: Implementing simple priority queue using vector in C++ The following gives an error for the code mentioned below.
Where I have gone wrong ?
error: 'function' is not a member of 'std'

I want to make priority queue using C++ std lib queue, and min the queue is that IceCream which takes least time to prep. I have tried implementing this -> declaring a priority_queue in c++ with a custom comparator
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <map>
#include <vector>
#include <queue>
#include <deque>
#include <iterator>
#include <string>
#include <sstream>

using namespace std;

class IceCream
{
 public:
   int time_to_prep;
    IceCream(int flav) {
          time_to_prep = flav;
       }
};

bool Compare(IceCream a, IceCream b)
{
    return a.time_to_prep > b.time_to_prep;
}

int main()
{
    priority_queue<IceCream, vector<IceCream>, std::function<bool(IceCream a, IceCream b)> > my_pq(Compare);
    my_pq.push(IceCream(4));
    my_pq.push(IceCream(33));
    my_pq.push(IceCream(9));
    cout << my_pq.top() << endl;
    return 0;
}

A: #include <functional>

You need this include to get access to std::function
See: http://en.cppreference.com/w/cpp/utility/functional/function


text:
Q: Parsing a string to an array? I'm trying to get the average of up to 25 numbers. Right now, I'm confused on how to parse a String into an array. Here is the code as it stands:
final int SIZE = 25;
gradeArray = new double[SIZE];
String s;
int numElem = 0;
double average = 0;

do {
    s = (String) JOptionPane.showInputDialog("Enter Grade", "");
    if (s == null || s == ("")) {

    } else {
        try {
            grades = Double.parseDouble(s);
            if (grades > SIZE)

        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(null, "Your input must be numeric!",
                    "Bad             Data!", 0);
        }
    }
} while (s != null || !s.equals(""));

The SIZE constant is for testing purposes.

A: for(int i=0;i<SIZE;i++)
{
 s = (String)JOptionPane.showInputDialog("Enter Grade","");
    if(s != null && !(s.trim().equals(""))){
        gradeArray[i] = Double.parseDouble(s);
    }
    else{
        gradeArray[i] = 0;
    }

}

double sum=0;
for(int j=0;j<gradeArray.length;j++)
{
      sum+=gradeArray[j];
}

System.out.println("avaerage of grades ="+SIZE+" is ="+(sum/SIZE));

A: As I understand you want to read up to 25 double constants as a single string and parse them into a double array.
final int SIZE = 25;
gradeArray = new double[SIZE];
String s;
int numElem = 0;
double average = 0;

do {
s = (String) JOptionPane.showInputDialog("Enter Grade", "");
if (s == null || s == ("")) {

} else {
    try {
       // this will find double values in your string but ignores non double values
       Matcher m = Pattern.compile("(?!=\\d\\.\\d\\.)([\\d.]+)").matcher(s);
       int temp = 0;
       while (m.find())
       {
         gradeArray[temp] = Double.parseDouble(m.group(1));
         temp ++;
         if(temp >= SIZE){
             break;
         }
       }

    } catch (NumberFormatException e) {
        JOptionPane.showMessageDialog(null, "Your input must be numeric!",
                "Bad             Data!", 0);
    }
}
} while (s != null || !s.equals(""));


text:
Q: Do I have to recompile my Gan every batch, to prevent the discriminator from learning? I have a Gan like so
generator = Model(g_in, g_out)
generator.compile(...)

discriminator = Model(d_in, d_out)
discriminator.trainable = True
discriminator.compile(..)

discriminator.trainable = False

gan = Model(inputs=.., outputs=..)
gan.compile(..)

#iterate over epochs and batches, without compiling

It learns and gives acceptable output. However I get the warning:
"keras\engine\training.py:490: UserWarning: Discrepancy between trainable weights and collected trainable weights, did you set model.trainable without calling model.compile after ?
  'Discrepancy between trainable weights and collected trainable'"
If I recompile the discriminator and gan every batch, the warning disappears, but one iteration takes much longer and training speed is slower.
for epoch:
  for batch:

    fakes=generator.predict_on_batch(batch)

    discriminator.trainable = True
    discriminator.compile(..)

    discriminator.train_on_batch(batch, ..)
    discriminator.train_on_batch(fakes, ..)

    discriminator.trainable = False
    discriminator.compile(..)
    gan.compile(..)

    gan.train_on_batch(batch,..)

Which one of them is correct?

A: That's expected and there's no need to recompile every batch. Keras has an open bug about this: https://github.com/keras-team/keras/issues/8585
The replies there have some examples of how to by pass the warning, I'm not going to repeat them here. There's also a reply which gives great advice on how to verify you're really training what you're supposed to be training if you feel unsure about the specifics of your model: https://github.com/keras-team/keras/issues/8585#issuecomment-385729276


text:
Q: IE7, inline-block и float: right Есть следующий код: http://jsfiddle.net/XyQ75/2/. Его смысл:
 принимает ширину таблицы,
 таким образом выравнивается по правому краю таблицы. Работает в Chrome, Firefox, IE8+. В IE7
 уползает в правый край экрана. Хак с hasLayout для эмуляции display: inline-block (в IE7 такое значение свойства display не поддерживается) не помогает. Вопрос: можно ли добиться описанного результата в IE7 не прибегая к JavaScript?
A: Может так http://jsfiddle.net/XyQ75/3/


text:
Q: How to handle a division by zero in Linq In the following linq query I have a division by zero exception wich I can't seem to code around. It occurs when the Sum of fldDevider returns 0.
Dim lstToReturn As List(Of MonthData)

lstToReturn = (
 From myRow In dtSpotData.AsEnumerable()
 Group myRow By myRow.Field(Of DateTime)(fldstartdate).Month Into Group
 Select New MonthData() With {
 .Month = Month,
 .ValuePerMonth =
 (
  Group.Sum(Function(dr) dr.Field(Of [Decimal])(fldSomeGeneralValue)) /
  (
   Group.Sum(Function(dr) CDec(dr.Field(Of String)(fldDevider)))
  )
 )
 }
).ToList()

How can I Make sure the ValuePerMonth field is 0 when the Group.Sum(Function(dr) CDec(dr.Field(Of String)(fldDevider))) function returns a 0. Or how do I return a 1 for Sum fldDevider if it is actually 0.
Some tips on how to do better conversions from string to decimal are welcome too.

A: I am used to C# syntax but I would use a 'let' to capture the value of the dividing number and only use it if it is greater than zero, and otherwise use 1.
Dim lstToReturn As List(Of MonthData)

lstToReturn = (
 From myRow In dtSpotData.AsEnumerable()
 Group myRow By myRow.Field(Of DateTime)(fldstartdate).Month Into Group
 Let div = Group.Sum(Function(dr) CDec(dr.Field(Of String)(fldDevider)))
 Select New MonthData() With {
 .Month = Month,
 .ValuePerMonth =
 (
  Group.Sum(Function(dr) dr.Field(Of [Decimal])(fldSomeGeneralValue)) / If(div > 0, div, 1)
 )
 }
).ToList()


text:
Q: Pysparkling 2 reset monotonically_increasing_id from 1 I want to split a spark dataframe into two pieces and defined the row number for each of the sub-dataframe. But I found that the function monotonically_increasing_id will still define the row number from the original dataframe.
Here is what I did in python:
# df is the original sparkframe
splits = df.randomSplit([7.0,3.0],400)

# add column rowid for the two subframes
set1 = splits[0].withColumn("rowid", monotonically_increasing_id())
set2 = splits[1].withColumn("rowid", monotonically_increasing_id())

# check the results
set1.select("rowid").show()
set2.select("rowid").show()

I would expect the first five elements of rowid for the two frames are both 1 to 5 (or 0 to 4, can't remember clearly):
set1: 1 2 3 4 5
set2: 1 2 3 4 5

But what I actually got is:
set1: 1 3 4 7 9
set2: 2 5 6 8 10

The two subframes' row id are actually their row id in the original sparkframe df not the new ones.
As a newbee of spark, I am seeking helps on why this happened and how to fix it.

A: First of all, what version of Spark are you using? The monotonically_increasing_id method implementation has been changed a few times. I can reproduce your problem in Spark 2.0, but it seems the behavior is different in spark 2.2. So it could be a bug that was fixed in newer spark release.
That being said, you should NOT expect the value generated by monotonically_increasing_id to be increase consecutively. In your code, I believe there is only one partition for the dataframe. According to http://spark.apache.org/docs/2.2.0/api/python/pyspark.sql.html

The generated ID is guaranteed to be monotonically increasing and
  unique, but not consecutive. The current implementation puts the
  partition ID in the upper 31 bits, and the record number within each
  partition in the lower 33 bits. The assumption is that the data frame
  has less than 1 billion partitions, and each partition has less than 8
  billion records.
As an example, consider a DataFrame with two partitions, each with 3
  records. This expression would return the following IDs: 0, 1, 2,
  8589934592 (1L << 33), 8589934593, 8589934594.

So if you code should not expect the rowid to be increased consecutively.
Besides, you should also consider caching scenario and failure scenarios. Even if monotonically_increase_id works as what you expect -- increase the value consecutively, it still will not work. What if your node fails? The partitions on the failed node will be regenerated from the source or last cache/checkpoint, which might have a different order thus different rowid. Eviction out of cache also causes issue. Assuming that after generating a dataframe and you cache it to memory. What if it is evicted out of memory. Future action will try to regenerate the dataframe again, thus gives out different rowid.


text:
Q: How to change the cursor hoving on a datatable in flutter? The default cursor is a hand when hoving the mouse on the table. You can see in the simple demo of the offical document.
How can I change it to an arrow? The little hand implies that when you click on a row something will happen, which is misleading.

A: put dataTable inside AbsorbPointer()

A: There is already a feature request for this: https://github.com/flutter/flutter/issues/70755
In the comments, someone mentioned a workaround, which is basically wrapping the whole DataTable into an IgnorePointer widget:
IgnorePointer(
   child: DataTable(
     headingRowHeight: 0,
     showCheckboxColumn: false,
     columns: [DataColumn(label: Container()), DataColumn(label: Container())],
     rows: [...]
   ),
);

It might have some drawbacks depending on your use case, but definitely working for now.


text:
Q: An array that takes the size depending on what I enter import java.util.Scanner;
public class Singleton{
    public static void main(String args[]){
        Scanner input = new Scanner(System.in);
        System.out.println("Enter number of students: ");
        int number = input.nextInt();
        String names[] = new String[number];
        for(int counter = 0; counter < 100; counter++){
            System.out.print("Enter name: ");
            names[counter] = input.nextLine();
            names[counter] = names[counter].toLowerCase();
        }
        int grades[] = new int[names.length];
        int count = 0;
        for(String x: names){
            System.out.print(x + "'s grade: ");
            grades[count] = input.nextInt();
            count++;
        }
        count = 0;
        for(String x: names){
            System.out.println(x + "'s grade is " + grades[count] + ".");
            count++;
        }
    }
}

can you help me to get something so I can put any number of values in the array without asking how many students there are?

A: If you want an array that you can add a variable number of elements to you could use an ArrayList. i.e.
import java.util.ArrayList;

    ArrayList<String> names = new ArrayList<String>();
    for(int counter = 0; counter < 100; counter++){
        System.out.print("Enter name: ");
        names.add(input.nextLine());
    }

A: Java has fixed length array and it is not possible to change size of array dynamically. To do what you need there is  java.util.ArrayList class.
(look at Reginol_Blindhop's answer. Regardless is it ArrayList or LinkedList code is the same).
But if you need array you can create new array with +1 size for every input, copy previous values there and put new into last element. To do that there is System.arraycopy method.
code may look like:
         String[] names = new String[1];

         for(int counter = 0; counter < 100; counter++){
                System.out.print("Enter name: ");
                String nextName = input.nextLine();

                String[] tempNames = new String[names.length + 1];
                System.arraycopy(names, 0, tempNames, 0, names.length);
                tempNames[names.length] = nextName;
                names = tempNames;
         }

PS. Of course for any solution it is better to use while loop and check if user finishes input by putting something special like "exit", "end", "bye", ":q" or whatever you'd like.

A: You should use a List for something like this, not an array. As a general rule of thumb, when you don't know how many elements you will add to an array before hand, use a List instead. Most would probably tackle this problem by using an ArrayList.


text:
Q: How to make setVerticalScrollBarEnabled(false) when you have scroll in gridView? I have this gridview
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridView1"
android:numColumns="3"
android:gravity="center"
android:columnWidth="50dp"
android:stretchMode="columnWidth"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

but I don't know how to make
setVerticalScrollBarEnabled(false);

A: If i am getting you right then you just need to add the following line in your gridview in xml
android:scrollbars="none"

Hop this is what you want.
Mark as up if it is. :)


text:
Q: Scaling x axis and y axis with VegaLite.jl I have plotted a scatter plot in VegaLite.jl, however, the x-axis and y-axis don't get scaled automatically like other plotting packages (plots, plotly etc.)
For example in the following example, the plot starts x-axis from 0, whereas it would make more sense to start from a value such as 125 since x-values are clustered between 150-200. The same thing applies to the y-axis. This results in a plot that has only utilized the top right section. Any ideas on how to scale the x and y axes?
using VegaLite
x = Array{Int64}([150,175,200])
y = Array{Int64}([225,250,275])

@vlplot(
    :point,
    x = x,
    y = y
)

A: You can add a scale specification, as documented in the Vega-Lite documentation or demonstrated e.g. here in the VegaLite.jl documentation.
For example:
using VegaLite
using DataFrames

data = DataFrame(x = [150,175,200], y = [225,250,275])

data |> @vlplot(
    :point,
    x = {:x, scale = {zero = false}}, # Auto scale, without enforcing that zero be in the domain
    y = {:y, scale = {domain = (200, 300)}}, # Explicit domain
)


text:
Q: Creating a second website tree inside a typo3 backend for test purpose? I have a typo3 backend with a page tree.
I want to future change the structure of that website. For that purpose i want to copy&paste the existing page tree and make changes there for testing purpose. And if everything works out, i want to replace the existing page tree with the new one.
How do i do that?
I did try to just copy the existing page. But the copy option doesnt show up.


text:
Q: How to emulate BACnet communication protocol on raspberry pi stacks I am currently working on my senior design project. I have made the stack of raspberry pi's. I am just wondering on how to create a BACnet stack where each raspberry pi device is a unique device, with a unique device ID. Additionally, we plan to use a cisco switch to connect with other raspberry pi stacks. I understand that there is a bacpypes module, which is amazing but it is mainly for dealing with a bacnet device. In my scenario, I need to create a stack of raspberry pi's emulating the BACnet communication protocol.
It would be really helpful

A: Quickest way:

*

*Compile Steve Karg's BACnet stack by following this: "How to build a FOSS BACnet Server based on Steve Karg's SourceForge project" on the BITS blog.

*Run the BACnet SErver sample executable on each of your Pis:
cd /demo/server
./bacserv

A: May I suggest trying BAC0, a python implementation of BACnet.
BAC0 is a high level wrapper around bacpypes. And when launched, becomes a BACnet device on any network.
https://github.com/ChristianTremblay/BAC0
https://bac0.readthedocs.io/en/latest/


text:
Q: Cannot center view in RelativeLayout I am trying to center a view within a parent RelativeLayout:
private void addLoadingAnimation() {
    RelativeLayout mainView = (RelativeLayout) findViewById(R.id.medical_supply_tile_activity);
    mainView.removeAllViews();
    GifView gifView = new GifView(this);
    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
    gifView.setId(R.id.loading_gif);
    mainView.setBackgroundColor(getResources().getColor(android.R.color.background_light));
    mainView.addView(gifView,layoutParams);
}

I have also tried adding layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 0); before the CENTER_IN_PARENT line. Nothing seems to be working. It is always aligned to the bottom right.
Here is my parent view:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/background_light"
    tools:context=".MedecineTileActivity"
    android:id="@id/medical_supply_tile_activity"
    android:layout_gravity="left">
</RelativeLayout>

The gravity=left is because when the loading animation is removed, I insert fragments and want them to go to the left.

A: I have achieved this with TextViews and ImageViews by aligning the child View's right to the parent's right and also aligning the child View's left to the parent's left.
<TextView
            style="@style/NewTextM2"
            android:id="@+id/soft_dialog_info_item_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/<Parent>"
            android:layout_alignLeft="@+id/<Parent>"
            android:layout_alignRight="@+id/<Parent>"
            android:gravity="center"
            android:tag="item_text"
            android:text="@string/text"
            android:maxLines="1" />

This will align the view to the bottom center of the parent.


text:
Q: Passing Thrift service as argument Is it possible to pass a service as an argument to a method in another service in Thrift?
service MyService {
  void foo(1: MyOtherService),
}

service MyOtherService {
  void bar(),
}

A: Service isn't Thrift serializable (in other words: no sense to transmit service via network - Your foo function to be executed on remote machine with transmitted arguments).
I think not.
What is real goal?
I have intuition You want good OO pattern.
Is this kind of parametrisation?


text:
Q: Integral of Characteristic Function times measurable function is a measure I want to verify my proof for the following problem:
Suppose $\mu$ is a measure on a measurable space $(X, \mathcal{S})$ and $f: X \rightarrow[0, \infty]$ is an $\mathcal{S}$ -measurable function. Define $v: \mathcal{S} \rightarrow[0, \infty]$ by
$$
v(A)=\int \chi_{A} f d \mu
$$
for $A \in \mathcal{S}$. Prove that $\nu$ is a measure on $(X, \mathcal{S})$.
Attempt The part that $v(\varnothing)=0$ is trivial. Given a countable union of disjoint sets $A=A_1\cup \ldots \cup A_n$, we know that any $x\in X$ can only belong to one $A_i$. Hence $\chi_A(x) = \chi_{A_1\cup \ldots \cup A_n}(x) = \chi_{A_1}(x) +\ldots +\chi_{A_n}(x)$. Plugging this into v:
$v(\bigcup_{i=1}^n A_i)=v(A)  = \int \chi_A f d\mu  =\sum_{i=1}^n \int \chi_{A_i}fd\mu = \sum_{i=1}^n v(A_i) $


text:
Q: phonegap: JQuery document.ready or Phonegap deviceready I am creating phonegap app first time. I have below code which i used to fetch data from server. Problem is this code is working fine if i use document.ready.
But I read somewhere that i need to use deviceready for phonegap app.
document.addEventListener("deviceready", function(){
    $.ajax({
        type: 'post',
        url: 'uid.php',
        cache: false,
        dataType: 'json',
        data: '&uid=' +uid,
        success: function(data) {

          alert(data.count);
});
});

I tried above code but it is not working. I mean ajax call not firing.
$(document).ready(function() {
        $.ajax({
            type: 'post',
            url: 'uid.php',
            cache: false,
            dataType: 'json',
            data: '&uid=' +uid,
            success: function(data) {

              alert(data.count);
    });
    });

A: Use IP address of your computer instead of localhost.And make sure your mobile is also connected in the same network whatever you computer is connected.
Sample code:
document.addEventListener("deviceready", function(){
    $.ajax({
        type: 'post',
        url: 'http://yourIpAddress/uid.php',
        cache: false,
        dataType: 'json',
        data: '&uid=' +uid,
        success: function(data) {

          alert(data.count);
});
});


text:
Q: Binding to AD Objects (with varying locations) We are undergoing a migration from several domains into a single domain.  As part of that process, user accounts are being moved around the various ADs a fair bit.  This has resulted in some scripts breaking because they are trying to get the User objects from a specific location in AD.
How would I amend the following to not be AD location specific?
Set objBlahUser = GetObject("LDAP://CN=" & objNetwork.UserName & ",OU=ADMigration,OU=Blah Users,DC=blah,DC=loc")

Thanks in advance

A: The simplest way to do this is use the NameTranslate object which is built-in to Windows
Const ADS_NAME_INITTYPE_GC = 3
Const ADS_NAME_TYPE_NT4 = 3
Const ADS_NAME_TYPE_1779 = 1

strNTName = "MyDomain\TestUser"
Set objTrans = CreateObject("NameTranslate")
objTrans.Init ADS_NAME_INITTYPE_GC, ""
objTrans.Set ADS_NAME_TYPE_NT4, strNTName
strUserDN = objTrans.Get(ADS_NAME_TYPE_1779)

There is a great write up on this object here:
http://www.rlmueller.net/NameTranslateFAQ.htm

A: Do you just want to specify the hostname?  Assuming that the rest of the AD structure is identical then you can just specify the server name in your binding string:
Set objBlahUser = GetObject("LDAP://yourserver.com/CN=" & objNetwork.UserName & ",OU=ADMigration,OU=Blah Users,DC=blah,DC=loc")

A: So, there is no way to intrinsically search and select the object from the directory.  I had to employ a separate function to search and return the DN of the object for later use.
userDN = GetUserDN(objNetwork.UserName,"server001","blah.loc")
If Not userDN = "Error" Then
    Set objBlahUser = GetObject("LDAP://" & userDN)
End if

Function GetUserDN(strUserName, strServer, strDomain)
    On Error Resume Next

    Set objConnection = CreateObject("ADODB.Connection")
        objConnection.Provider = "ADsDSOObject"
        objConnection.Properties("User ID") = strDomain & "\ReadADAccount"
        objConnection.Properties("Password") = "ReadADAccountPwd"
        objConnection.Open "Active Directory Provider"

    Set objCommand = CreateObject("ADODB.Command")
    objCommand.ActiveConnection = objConnection

    objCommand.CommandText = _
        "<LDAP://" & strServer & ">;(&(objectCategory=User)" & _
             "(samAccountName=" & strUserName & "));distinguishedname;subtree"

    Set objRecordSet = objCommand.Execute

    If objRecordset.RecordCount = 0 Then
        GetUserDN = "Error"
    Else
        GetUserDN = objRecordSet(0).value
    End If

    objConnection.Close
End Function


text:
Q: sufficient amount of computer science a pure mathematics student would need to know I am a master's pure mathematics student. Recently I have been studying just a bit of discrete geometry (e.g. configurations of points) and I seem to be enjoying it in that its ideas are simply expressed while inside many relavant open problems abound.
However, I think that in order to better appreciate discrete geometry and facilitate problem solving in this area one should know computer science.
As most of my time is devoted to smooth geometry, I do not have enough time for delving into computer science. How much of computer science and of a programming language like Python I should learn in order to study discrete geometry more professionally?
Thanks in advance

A: Rather than Python, you might choose software that has built-in rich 2D & 3D graphics, for quick investigations to see if a lemma might be true are often more useful in research than writing industrial-strength code for a larger task. Some possibilities:

*

*Mathematica

*Sage

*Matlab

*Even though Geogebra is not a general-purpose language, it is still quite useful for explorations.

I know one can add libraries to Python to create high-quality graphics, but they are less built-in so there is generally more overhead in usage.


text:
Q: Why folder size differs so much between the folder alone and all of the folder contents? In Windows 10, I go to 'C:\Users' and right-click on the folder with my username and select "Properties".
The file size is 5.92GB, 44,507 files and 10,457 folders.
I open up this folder with my username and I use the key combination CTRL + A and then right-click, and select "Properties".
The file size is 1.41GB, 10,721 files, 721 folders.
Why is that? Why the folder alone and the whole contents of the folder size differs so much?

A: This is probably due to hidden files and folders.
You need in folder click to bookmarks View in top menu and click to checkbox hidden elements.  When you enable hidden element you can use CTRL + A and then right-click, and select "Properties".


text:
Q: How do I do this "If n is 3, return `1+..1+2+..1+2+3+..`" Define a function named nested_increasing_additions(n) which receives one positive integer (n) and returns a string as illustrated in the following examples:
If n is 3, the function should return the string:
1+..1+2+..1+2+3+..
If n is 5, the function should return the string:
1+..1+2+..1+2+3+..1+2+3+4+..1+2+3+4+5..+
What I think is, I can make n to a list [1,2,3] and use while loop or for loop to repeat n times. For the first loop it returns 1+.., for the second loop it returns 1+2.. somehow (which i don't know) it stops at 2 which is the same as the repeating time.
I don't know if I'm thinking it right. Need some help and explanations! Thank you!

A: Consecutive evaluations of these strings results in a sequence of tetrahedral numbers.  For example, for input 5, the output evaluates to 35.  This is the number of spheres you would need to build a tetrahedron of side length 5.

To see how it relates to the sum in the question, note that the discrete "volume" of the tetrahedron would be equal to the sum of the triangle "slices" from top to bottom.
35 = 1 + 3 + 6 + 10 + 15
   = 1 + (1+2) + (1+2+3) + (1+2+3+4) + (1+2+3+4+5)

By a similar argument, the triangular numbers are made up of slices of consecutive integers.

Please excuse the maths, it was difficult (but not impossible) to adapt a closed-form solution into the desired output format.
def tetrahedral(n):
    return n*(n+1)*(n+2)//6

def string_generator(n):
    x = tetrahedral(n)
    n = N = 1
    while x > 0:
        while n <= N:
            yield str(n) + '+'
            n += 1
        x -= N*(N+1)//2
        n = 1
        N += 1
        yield '..'

def nested_increasing_additions(n):
    return ''.join(string_generator(n))

A: You can build the complete string step by step, and remember at each step what you have added last:
def nested_increasing_additions(n):
    complete_string = ""
    add_string = ""
    for i in range(1,n+1):
        add_string += str(i) + "+"
        complete_string += add_string + ".."
    return complete_string

print(nested_increasing_additions(1))
print(nested_increasing_additions(3))
print(nested_increasing_additions(5))

The output with python3 is:
1+..
1+..1+2+..1+2+3+..
1+..1+2+..1+2+3+..1+2+3+4+..1+2+3+4+5+..

A: def nested_increasing_additions(n):
    l=['']
    for i in range(1, n+1):
        l.append(l[-1]+str(i)+'+')
    return '..'.join(l[1:])

This returns a string without the .. at the end.  If you want that, just do return '..'.join(l[1:]) + '..'

A: you can use something like this.
def nested_increasing_additions(n):
    string = ""
    for i in range(1,n+1): #1
        for j in range(1,i+1): #2
            string += str(j)+"+" #4
        string += ".." #5
    print(string)

here is a printout of nested_increasing_additions(4)
1+..1+2+..1+2+3+..1+2+3+4+..
i think it's self explanatory, nothing complicated.

A: Assuming you did want the ".." at the end of each returned string and that recursion is OK, here's a solution:
def nested_increasing_additions(n):
    if n == 1:
        return "1+.."
    else:
        return nested_increasing_additions(n-1) + '%s+..' % '+'.join(str(i) for i in range(1, n+1))

print(nested_increasing_additions(3))
print(nested_increasing_additions(5))
type(nested_increasing_additions(1))

Prints:
1+..1+2+..1+2+3+..
1+..1+2+..1+2+3+..1+2+3+4+..1+2+3+4+5+..
<type 'str'>

Explanation:

*

*The first return and if (true) block ends the recursive call when the passed in argument value reaches 1 via subtraction from the other half.

*The second half (else block) calls the next iteration with n subtracted by 1 and the string build of the current iteration (if n!=1).

*The complicated looking code '%s+..' % '+'.join(str(i) for i in range(1, n+1)) is just concatenation of a list of numbers generated by the range function, turned into strings and "+.."

*

*range(1, n+1) returns a list of integers starting with 1 until n+1 so range(1,3) yields [1,2]. This is passed to join which places a + between each number.

A: How's this:
def nested_increasing_additions(n):

    string = ""
    new_string = ""
    dot = ".."

    for i in range(1, n+1):
        new_string+=('{}+'.format(i))
        string = string+new_string+dot
        print(string)

    return (string)

Output:
nested_increasing_additions(3)

'1+..1+2+..1+2+3+..'


text:
Q: Using own user repository/ database table for IdentitiyServer3 to authenticate against Can you please help me with some insight on using my own User repository/ database table for Identity server (IdentityServer3) to authenticate against?
I know other people have done it, but can't seem to figure out how?

A: You need to write a user service.  The docs and samples have very good coverage of that.
https://identityserver.github.io/Documentation/docs/advanced/userService.html