text:
Q: Why is @ referring to Window object in Coffeescript? Having a bit of hardtime understanding coffeescript. Why is this the window object in the set_position function?
window.App = {}

$ ->
  driver = new Driver if ($('#drivers_become').length >= 1)
  window.App.driver = driver

class Driver
  constructor: ->
    @get_position()
  get_position: ->
    if navigator.geolocation
      navigator.geolocation.getCurrentPosition(@set_position)
  set_position: (pos) ->
    # this refers to window object in this case. why?
    @latitude = pos.coords.latitude
    @longitude = pos.coords.longitude
  get_latitude: ->
    @latitude
  get_longitude: ->
    @longitude

get_latitude and get_longitude return undefined in this case.

A: If you are using aDriverInstance.set_position as an event handler function, the browser will invoke it as a regular function not a method. To fix that, use a "fat arrow" when defining it: set_position: (pos) =>. But more broadly it is a question of invoking via dot notation and invoking via direct reference:
aDriverInstance.set_position(pos) will have this set to aDriverInstance and all is well
set_position_reference = aDriverInstance.set_position;set_position_reference(pos) will have this set to the window object.

A: This is a classic binding issue, and applies as much to Javascript as Coffeescript.
You are passing a Driver method, set_position to a Windows function,
navigator.geolocation.getCurrentPosition(@set_position)

That function evaluates set_position in the global, windows, context.  In effect it ends up setting global latitude and longitude variables, not the attributes of the Driver instance.  In your console see if those variables are defined.
What you want to do is define set_position so @is bound to the Driver instance.  To do that, use the fat arrow, =>.  http://coffeescript.org/#fat-arrow
set_position: (pos) =>
    # this refers to window object in this case. why?
    @latitude = pos.coords.latitude
    @longitude = pos.coords.longitude

If you use this, and look at the compiled Coffee, you will see a line that does:
this.set_position = __bind(this.set_position, this);

Packages like jquery and underscore also have a bind function, as do recent browsers.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
get_position: ->
   if navigator.geolocation
       navigator.geolocation.getCurrentPosition(@set_position.bind(this))

Uses the browser's bind


text: Q: Importar CSV a SQL SERVER error tildes y eñes Estoy intentando subir mis ficheros de csv a SQl Server. Se me importa correctamente pero cuando hago una consulta a estos ficheros importados, los acentos y eñes aparecen con simbolo raro, ¿ cómo puedo hacer para qué me respete mis tildes y eñes? Muchas gracias,

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to estimate the infinitesimal generator of a Markov chain? I am working on an 8 state (8th state absorbing) multi-state markov model, and what I am having difficulty understanding is, how sensitive are the results to the initial qmatrix and what is the best way to go about creating the initial matrix?
For example, in http://leg.ufpr.br/~silvia/papers/mmm.pdf, the matrix is:
-(q12+q14)   q12           0     q14
 q21        -(q21+q23+q24) q23   q24
.......

But when the Q matrix is created immediately below using the following code
Q <- rbind ( c(0, 0.25, 0, 0.25),
+ c(0.166, 0, 0.166, 0.166),
+ c(0, 0.25, 0, 0.25),
+ c(0, 0, 0, 0) )

there are no negative values. In fact, for Q[1,1], the value is zero, not the negative of the sums of q12+q14. Also, the fourth row, which is the absorbing state, is entered as all zeros. Why wouldn't Q[4,4] be 1?
How would I go about creating that initial matrix, given the frequency of times the subjects are observed moving between states?  (For another example, please see the state table provided below.)
On a more general note, if someone could recommend a good primer for understanding and using Markov models (skewed towards a general audience), and interpreting their results, I would be grateful.

Here is a the state table for my data (in R):
 dput(mm2myTrajectoryStateTable)
structure(c(13295L, 946L, 126L, 6L, 1L, 1L, 0L, 3461L, 15035L,
937L, 100L, 19L, 17L, 2L, 636L, 2014L, 3977L, 146L, 4L, 16L,
4L, 46L, 153L, 518L, 1141L, 0L, 10L, 19L, 84L, 109L, 16L, 3L,
257L, 25L, 0L, 18L, 117L, 62L, 13L, 72L, 446L, 11L, 0L, 4L, 12L,
31L, 1L, 28L, 139L, 12909L, 15089L, 4377L, 680L, 146L, 193L,
38L), .Dim = 7:8, .Dimnames = structure(list(from = c("1", "2",
"3", "4", "5", "6", "7"), to = c("1", "2", "3", "4", "5", "6",
"7", "8")), .Names = c("from", "to")), class = "table")

A: Synopsis
The construction of the transition matrix $P(t)$ from $Q$ and $t$ is explained (with a simple $2\times 2$ example) at Solving the Kolmogorov forward equation for transition probabilities.  Obtaining $Q$ from $P=P(t)$ is effected by reversing the process.
Methods
To summarize, that thread shows that $P(t) = \exp(tQ)$ (the matrix exponential) can be computed by diagonalizing $Q$ and exponentiating the diagonal terms (all multiplied by the time $t$).  Thus, $Q$ is a matrix logarithm which can be computed by diagonalizing $P$ and taking the logs of its diagonal terms.
Specifically, upon finding a matrix $V$ for which
$$P(t) = V\ \Lambda\ V^{-1}$$
with $\Lambda$ having the values $\lambda_1, \lambda_2, \ldots, \lambda_n$ on the diagonal (for $n$ states, including all absorbing states) and zeros elsewhere, compute that
$$Q = V\ \frac{1}{t}\log(\Lambda)\ V^{-1}$$
where $\log(\Lambda)$ has the values $\log(\lambda_1), \log(\lambda_2), \ldots, \log(\lambda_n)$ on its diagonal and zeros elsewhere.
There is a technical complication: it can require matrices with complex coefficients to achieve the diagonalization.  However, after the calculation is complete, all the results will be real numbers.  Dealing with this will, in practice, merely require taking the real part of the answer (and perhaps checking that the imaginary parts are all very small in comparison, just as a double-check).
The matrix of the question has this $8\times 8$ matrix for its infinitesimal generator.

As expected, the rows sum to zero.  I have rounded the values to three decimal places, colored the backgrounds according to the rounded values, and desaturated those colors to reflect the magnitudes of the entries (so that grayish entries are small).  The patterns clearly stand out.
Assessing uncertainty
When $P$ is estimated from data, its entries--and therefore the entries of $Q$--experience sampling variation.  Perhaps the most straightforward way to assess that uncertainty is through simulation (a parametric bootstrap).  For the matrix $P$ given in the question here are simple summaries of the $7\times 8$ deviations between $9999$ bootstrapped values of $Q$ and the computed value of $Q$:

The full $56$-variate distribution can be estimated from the simulation data if desired.
Code
The following R code performs the calculations and simulations.  The essential part is performed by the function q.matrix, which computes the matrix logarithm of its argument (presumed to be a square matrix) after row-normalizing it to sum to unity along the rows.  The key lines obtain the eigenvectors and values, compute the logarithms of the eigenvalues, and reassemble the result into $Q$:
s <- eigen(p)
q <- Re(s$vectors %*% diag(clog(s$values)) %*% solve(s$vectors))

(Edit November 2019: clog is a complex logarithm; for positive real $x,$ $\operatorname{clog}(-x) = \log(x) + \pi i$.  It is needed in order to handle negative eigenvalues.)
The full code follows.  The simulation requires about six seconds.  A simulation with just $999$ iterations would produce helpful results and take less than one second.
x <- structure(c(13295L, 946L, 126L, 6L, 1L, 1L, 0L, 3461L, 15035L,
                 937L, 100L, 19L, 17L, 2L, 636L, 2014L, 3977L, 146L, 4L, 16L,
                 4L, 46L, 153L, 518L, 1141L, 0L, 10L, 19L, 84L, 109L, 16L, 3L,
                 257L, 25L, 0L, 18L, 117L, 62L, 13L, 72L, 446L, 11L, 0L, 4L, 12L,
                 31L, 1L, 28L, 139L, 12909L, 15089L, 4377L, 680L, 146L, 193L,
                 38L), .Dim = 7:8,
           .Dimnames = structure(list(from = c("1", "2", "3", "4", "5", "6", "7"),
                                     to = c("1", "2", "3", "4", "5", "6", "7", "8")),
                                     .Names = c("from", "to")), class = "table")
clog <- function(z) log(Mod(z)) + Arg(z) * 1i # Complex logarithm
q.matrix <- function(x, tt=1) {
  p <- x / rowSums(x)
  s <- eigen(p)
  q <- s$vectors %*% diag(clog(s$values)) %*% solve(s$vectors)
  return(Re(q / tt))
}
#
# Simulation
#
counts <- rowSums(x)
probs <- t(x/counts)
set.seed(17)
n.iter <- 9999
system.time(
  sim <- array(replicate(n.iter, {
    y <- t(sapply(1:dim(x)[1], function(i) {
      rmultinom(1, counts[i], x[i, ])
    }))
    q.matrix(rbind(y, c(rep(0,7), 1)))
  }), dim=c(8, 8, n.iter))
  )
#
# Compute the infinitesimal generator.
#
q <- q.matrix(p <- rbind(x+1, c(rep(0,7), 1)))
library(Matrix)
sum((expm(q) - p/rowSums(p))^2) # Check that exp(q) = p
#
# Compute and plot the bootstrap statistics.
#
q.mean <- apply(sim, c(1,2), mean)  # The mean bootstrapped values
q.mu2 <- apply(sim^2, c(1,2), mean)
q.sd <- sqrt(q.mu2 - q.mean^2)      # Standard deviations of the bootstrapped values
par(mfrow=c(1,2))
hist((q.mean - q)[1:7, ], freq=FALSE, main="Mean Deviation", xlab="Value")
hist(q.sd[1:7, ], freq=FALSE, main="SD", xlab="Value")
#
# Plot Q
#
par(mfrow=c(1,1))
j <- matrix(rep(1:8, 8), 8)
i <- as.vector(t(j))
j <- 9 - as.vector(j)
q.scale <- (q-min(q))/diff(range(q))
plot(c(0,9), c(0,9), type="n",
     main="Infinitesimal Generator",
     xlab="To", ylab="From", asp=1,
     bty="n", xaxt="n", yaxt="n")
points(i, j, col="#e0e0e0")
points(i, j, pch=22, cex=6, col="#d0d0d0", bg=hsv(q.scale, abs(q), 0.9))
text(i, j, paste(round(q, 3)), cex=0.75)
text(0, 1:8, paste(8:1))
text(1:8, 0, paste(1:8))


text:
Q: How to configure a VPN on Linux GUI given just a configuration file? I received one configuration file from my university technical staff to configure an OpenVPN connection. According to the staff, I must open the connection manually in command line through the following command

openvpn --config configuration_file.conf

However, I must keep a terminal opened with that command running (probably through screen I can less disturbance). However, can I use the VPN connection GUI from Ubuntu to configure that VPN using the information found in the configuration file? how to do that?
The contents of the configuration file are below:
#############################################
# Sample client-side OpenVPN 2.0 config file.
# for connecting to multi-client server.
##############################################

#tls-cipher "DEFAULT:@SECLEVEL=0"

# Specify that we are a client and that we
# will be pulling certain config file directives
# from the server.
client

dev tun
proto udp

# The hostname/IP and port of the server.
remote <ip-adress> <port>

# host name of the OpenVPN server.  Very useful
# on machines which are not permanently connected
# to the internet such as laptops.
resolv-retry infinite

# Most clients don't need to bind to
# a specific local port number.
nobind

# Try to preserve some state across restarts.
persist-key
persist-tun

comp-lzo

# Certificate Authority
<ca>
-----BEGIN CERTIFICATE-----
BLABLABLA
-----END CERTIFICATE-----
</ca>

# Username/Password authentication is used on the server
auth-user-pass

# Verify server certificate by checking
# that the certicate has the nsCertType
# field set to "server".  This is an
# important precaution to protect against
# a potential attack discussed here:
#  http://openvpn.net/howto.html#mitm
#
# To use this feature, you will need to generate
# your server certificates with the nsCertType
# field set to "server".  The build-key-server
# script in the easy-rsa folder will do this.
ns-cert-type server

# Set log file verbosity.
verb 3

A: You are able to import a VPN configuration using GNOME's network management GUI.  Just click "Import from file..." under Settings -> Network -> Add VPN


text:
Q: renaming many fields in mongodb/meteor I'm attempting to update many field titles in my meteor database (mongodb) and I'm struggling with syntax. Here is an example of one entry in my collection called 'Lessons':
{
"_id": "R6AnePqKecNNe7dkr",
"title": "A Title Name",
"categoryA": "Category Name"
}

I'm trying to update every file within the 'Lessons' collection to replace 'categoryA' with 'category0' and this is the code I'm running based on the answer here:
Lessons.update({}, {$rename:{"categoryA":"category0"}}, { upsert:false, multi:true });

I tried running it within the client shell but it came up with an error "Not permitted. Untrusted code may only update documents by ID." which I attribute to this.
Then I tried running it within the server shell but it said 'Lessons.update' is not recognized as an internal or external command"
Then I made a button within my site and when clicked it would run that code in a method on the server side. There are no errors or warnings when the button is pressed but the database remains unchanged.
I've also tried using 'updateMany' instead of 'update' but that just just comes up with an 'internal server error [500]'

A: the solution is to run the mongo shell on the server
meteor mongo

then select the meteor database
use meteor

then use the following syntax
db.lessons.update({},{$rename:{"categoryA":"category0"}}, {multi:true})


text:
Q: What's the difference between InvalidationListener and ChangeListener? As you know an ObservableValue in java can generate two types of events: Invalidation and Change. I don't know what's the difference between them?
When we should use Invalidation or Change Listener?

A: As per documentation:

An ObservableValue generates two types of events: change events and invalidation events. A change event indicates that the value has changed. An invalidation event is generated, if the current value is not valid anymore.This distinction becomes important, if the ObservableValue supports lazy evaluation, because for a lazily evaluated value one does not know if an invalid value really has changed until it is recomputed. For this reason, generating change events requires eager evaluation while invalidation events can be generated for eager and lazy implementations.

ChangeListener enforces eager computation even when the observable value supports lazy evaluation.
If you want to find the change that happened in observed property, you use a change listener. Where as the InvalidationListener only helps us know some change has happened, if you want to know the difference between old and new values, you have to compute that yourself or simply use change listener.


text:
Q: Problems with serialization in java, calling a stateless javabean from a primefaces baking bean First of all: sorry for my english, I'll try to do my best :)
I have a Java EE application, with javabeans providing the logic via remote interfaces and a primefaces interface with his baking beans. For example I have this in my ejb project:
@Stateless
@LocalBean
public class reporteService implements reporteServiceRemote {
    [...]
    public LinkedList<LineaBalanceteSaldosClientesTransport> balanceteSaldosClientes(...parameters...) {
        LinkedList<LineaBalanceteSaldosClientesTransport> lineas = new LinkedList<>();
        // execute a native query and return the results
        // the query return about 6/700 rows
        List results = this.balanceteSaldosClientes(...parameters...);
        Iterator it = results.iterator();
        while (it.hasNext()) {
            Object[] result = (Object[])it.next();
            String codigoCliente        = (String) result[0];
            Integer idCliente           = (Integer) result[1];
            Integer nombreCliente       = (String) result[2];
            // generate new line
            linea = new LineaBalanceteSaldosClientesTransport();
            linea.setIdCliente(idCliente);
            linea.setCodigoCliente(codigoCliente);
            linea.setNombreCliente(nombreCliente);
            lineas.add(linea);
        }
        return lineas;
    }
    [...]
}

@Remote
public interface ReporteServiceRemote {
    [...]
    public LinkedList<LineaBalanceteSaldosClientesTransport> balanceteSaldosClientes(...parameters...);
    [...]
}

This works fine, I've tried outputting the lines and the final linkedlist in the log and the method ends fine. The point is calling the method from the war, using his remote interface. This is the baking bean for a primefaces page that is supposed to show the results:
@ManagedBean
@ViewScoped
public class ReporteBean implements Serializable {
    [...]
    @EJB
    private ReporteServicesRemote reporteServices;
    [...]

    public LinkedList<LineaBalanceteSaldosClientesTransport> obtenerBalanceteSaldosClientes() {
        try {
            LinkedList<LineaBalanceteSaldosClientesTransport> lbsct = reporteServices.balanceteSaldosClientes(
                            this.getFechaSaldo(),
                            this.getIdsMonedas(),
                            cliente != null ? cliente.idCliente : null
            );
            return lbsct;
        } catch (Exception ex) {
            LOG.log(Level.SEVERE, "ERROR", ex);
            this.messagesBean.message(FacesMessage.SEVERITY_ERROR, "ERROR", "Error al intentar generar Balancete de Saldos: " + ex.getLocalizedMessage());
        }
        return null;
    }

    [...]
}

when it call the method reporteServices.balanceteSaldosClientes it ends fine, but (I think) the serialization of the resulting object fail, throwing this exception:
javax.ejb.EJBException: java.rmi.ServerError: Error occurred in server thread; nested exception is:
    java.lang.NoClassDefFoundError: Could not initialize class org.glassfish.pfl.dynamic.copyobject.impl.Exceptions
    at com.myproject.services.reportes._ReporteServicesRemote_Wrapper.balanceteSaldosClientes(com/myproject/services/reportes/_ReporteServicesRemote_Wrapper.java)
    at com.tecytal.utils.servlets.testServlet.processRequest(testServlet.java:124)
    at com.tecytal.utils.servlets.testServlet.doGet(testServlet.java:158)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.rmi.ServerError: Error occurred in server thread; nested exception is:
    java.lang.NoClassDefFoundError: Could not initialize class org.glassfish.pfl.dynamic.copyobject.impl.Exceptions
    at com.sun.corba.ee.impl.javax.rmi.CORBA.Util.wrapException(Util.java:699)
    at com.sun.corba.ee.impl.presentation.rmi.StubInvocationHandlerImpl.privateInvoke(StubInvocationHandlerImpl.java:257)
    at com.sun.corba.ee.impl.presentation.rmi.StubInvocationHandlerImpl.invoke(StubInvocationHandlerImpl.java:150)
    at com.sun.corba.ee.impl.presentation.rmi.codegen.CodegenStubBase.invoke(CodegenStubBase.java:226)
    at com.myproject.services.reportes.__ReporteServicesRemote_Remote_DynamicStub.balanceteSaldosClientes(com/myproject/services/reportes/__ReporteServicesRemote_Remote_DynamicStub.java)
    ... 32 more
Caused by: java.lang.NoClassDefFoundError: Could not initialize class org.glassfish.pfl.dynamic.copyobject.impl.Exceptions
    at org.glassfish.pfl.dynamic.copyobject.impl.ClassCopierBase.copy(ClassCopierBase.java:131)
    at org.glassfish.pfl.dynamic.copyobject.impl.ClassCopierOrdinaryImpl$ClassFieldCopierUnsafeImpl$17.copy(ClassCopierOrdinaryImpl.java:810)
    at org.glassfish.pfl.dynamic.copyobject.impl.ClassCopierOrdinaryImpl$ClassFieldCopierUnsafeImpl.copy(ClassCopierOrdinaryImpl.java:1008)
    at org.glassfish.pfl.dynamic.copyobject.impl.ClassCopierOrdinaryImpl.doCopy(ClassCopierOrdinaryImpl.java:1128)
    at org.glassfish.pfl.dynamic.copyobject.impl.ClassCopierBase.copy(ClassCopierBase.java:129)
    at org.glassfish.pfl.dynamic.copyobject.impl.ClassCopierOrdinaryImpl$ClassFieldCopierUnsafeImpl$17.copy(ClassCopierOrdinaryImpl.java:810)
    at org.glassfish.pfl.dynamic.copyobject.impl.ClassCopierOrdinaryImpl$ClassFieldCopierUnsafeImpl.copy(ClassCopierOrdinaryImpl.java:1008)
    at org.glassfish.pfl.dynamic.copyobject.impl.ClassCopierOrdinaryImpl.doCopy(ClassCopierOrdinaryImpl.java:1128)
    at org.glassfish.pfl.dynamic.copyobject.impl.ClassCopierBase.copy(ClassCopierBase.java:129)
    [...]
    (lot of similar lines repeated)

Someone pointed me to a memory problem, but in this case java was running with 8GB of dedicated memory (Xmx8192m, Xms8192m, MaxPermSize=4096m) and the linkedlist in this case contains only 600/700 objects. If I put i.e. a LIMIT 100 in the native query that returns the first list of results I get no exception and all works flawlessy.
I'm doing it wrong? Is there a more efficient way to pass datas between beans? Or there's another bug I cannot see?
Thank you for every suggestion.

A: This problem can be resolved using the Value List Handler pattern, more informations and working examples can be found here

*

*Core J2EE Patterns - Value List Handler -
http://www.oracle.com/technetwork/java/valuelisthandler-142464.html

*EJB 3.0 Stateful Session Bean Example -
http://www.go4expert.com/articles/ejb-30-stateful-session-bean-example-t4212/
Hope this can help someone.


text:
Q: Are you open to a new project? or Are you open for a new project? These two statements seem correct, but actually, which one is the proper statement? And can you explain how the usage of to & for changes the meaning of the statement?
Hey, are you open to a new project?
or
Hey, Are you open for a new project?

A: 1

Hey, are you open to a new project?

2

Hey, are you open for a new project?

In this context, we should use your example (1), with open to.
open to means willing to consider as shown in Cambridge Dictionary, definition C1 for open.

I'd like to think I'm open to (= willing to consider) any reasonable suggestion.

for is found in an example under another definition for open, meaning not decided.

We can leave our offer open for another week, but we have to have your decision by then.

This definition is not applicable to your example.
Edit:
open for is an idiom, which means

to perform before (the main performer at a concert, show, etc.)

That definition is also not applicable to your example.


text:
Q: Parsing var-args style commands with Bison I'm fairly new to Flex/Bison and I'm trying to parse a string in the format:
COMMAND ARG1, ARG2, ARGn (, ARGn+1, ARGn+2 ...);

such that args 1, 2 and n are required, but n+1, n+2, ... are optional without limit.
How would I do this in Flex/Bison?
When I define my grammar as:
args:
  ARG
  |
  ARG COMMA args
;

var_command:
  COMMAND ARG COMMA ARG COMMA args SEMICOLON
  {
    printf("arg1: %s, arg2: %s\n", $2, $4);
  }

I can only (as above) reference the first 2 arguments, how do I reference what is being matched in the args: definition?
I've tested the grammar and I can throw any number of arguments at it, it is matching correctly, it's simply getting a handle on that data that escapes me.

A: In this case, probably the list of ARGs needs to be created explicitly by
the programmer.
For example(fictitious code):
%union { args_data *ad; }
%type <ad> args

%%

args:
  ARG
  {
    args_data *ad = alloc_args_data();
    append_arg(ad, $1);
    $$ = ad;
  }
  |
  args COMMA ARG
  {
    append_arg($1, $3);
    $$ = $1;
  }
;


text:
Q: IBM Content Navigator: Difference between NonServiceLogger and ServiceLogger I see there are 2 logging classes mainly used in ICN plugin customization, viz. NonServiceLogger and ServiceLogger. Does anybody know the difference between them? I checked the documentation of the classes in help portal, but that's not clear enough. What would be the ideal scenario to use them individually?
thanks in advance.

A: The plug in can be used to create a service functionality  or any other functionality. The logger are specifically differentiated according to that.
Service plugin - like calling a service in fuse to validate the data entered by the user. The servicelogger is preferred here as compared to non service one.
https://www.ibm.com/support/knowledgecenter/SSEUEX_3.0.5/com.ibm.developingeuc.doc/eucso006.htm
nonservice plugin is used when no service is being called via the plugin.
The difference is nominal but when you use the nonservice logger in service plugin.. the logs are generated in a temp folder(not known location) which will increase the size of that drive and it will not be cleared off (like if service logger is used). This is what we faced recently and have to change the logger to service one..
thanks ..


text:
Q: redux selector is not filtering nested array accordingly I'm trying to filter posts where Likes userId is equal to params.userId, as of now im getting an empty array. Ideally it should get all posts, that the params.userId has liked.
selector
export const getUserPosts = (params) => {
    return createSelector(
        postSelector,
        (state) => {
            const findIndex = state.posts.findIndex((x) => x.userId == params.userId);
            console.log(findIndex)
            // const likedPosts = state.posts.reduce((acc, cv) => {
            //     const newPosts = {
            //         Likes: cv.Likes.filter((item) => item.userId == params.userId)
            //     }
            //     const newerPosts = newPosts.Likes.length !== 0 ? newPosts.Likes : []
            //     console.log(newerPosts)

            //     return { acc, newerPosts }
            // }, [])
            // console.log(likedPosts)
            return state.posts.filter((item) => item.Likes.userId == params.userId)
        }
    )
}

Array shape
{
  "id": 7,
  "title": "another testf",
  "postContent": "fsfsfsfsfssfsf",
  "likedByMe": false,
  "likeCounts": 1,
  "userId": 81,
  "createdAt": "2020-01-22T02:59:17.763Z",
  "updatedAt": "2020-01-23T02:49:40.801Z",
  "author": {
    "username": "barnowl2",
    "gravatar": "https://i.pravatar.cc/150?img=11",
    "bio": null
  },
  "Likes": [
    {
      "id": 11,
      "userId": 81,
      "resourceId": 7,
      "createdAt": "2020-01-23T02:32:52.761Z",
      "updatedAt": "2020-01-23T02:32:52.761Z"
    }
  ],
  "Comments": []
}

A: You have a multi-level array of Posts and their Likes. If you need to find all the Posts with Likes that match a particular userId, I think it would be like this:
state.posts.filter(post => {
  return post.Likes.find(like => like.userId === params.userId)
})

.find() will run through the Likes and return the object or null, which will inform .filter() whether or not to include the Post


text:
Q: Button Doesn't Show Correct Color - Android Studio In my Android Studio application, I have a button for which I set a drawable as the background. The drawable rounds the corners and changes the color of the button.
However, when I look at the resulting design of the activity, the color I want doesn't show up. Instead, the button assumes colorPrimary (orange, #ED3616). The same occurs when I run the application.
Note: the other attributes of the drawable file translate perfectly to the button (i.e. the rounded corners). The problem is only with the color.
I have tried using a MaterialButton, and setting the color with android:backgroundTint. Then, the color does show up as I want to, but the design looks odd (there is a different colored rectangle inside of the button(Picture of MaterialButton if you'd like to see it)
How can I make the regular button have the color I desire?
Button:
<Button
    android:background="@drawable/round2"
    android:id="@+id/signIn"
    android:layout_width="256dp"
    android:layout_height="66dp"
    android:text="@string/logIn"
    android:textColor="#FFFFFF"
    android:textSize="25sp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.496"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.878" />

Drawable: round2.xml:
    <?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid
        android:color="#B30C44"
        android:paddingLeft="6dp"
        android:paddingTop="6dp" />
    <corners
        android:bottomRightRadius="20dp"
        android:bottomLeftRadius="20dp"
        android:topLeftRadius="20dp"
        android:topRightRadius="20dp"/>
    <padding
        android:bottom="6dp"
        android:left="6dp"
        android:right="6dp"
        android:top="6dp" />
</shape>

What shows up:
What the Button looks like

A: It happens because the default style of the MaterialButton (the Button is replaced with a MaterialButton automatically if your are using a MaterialComponents theme) tints the background with the colorPrimary.
You have to use:
<Button
    android:background="@drawable/round2"
    app:backgroundTint="@null"
    ... />


text:
Q: return join table but group by only main table id I'm trying to return a join of 4 tables, but group them by "commentcount". however i keep gettng an error telling me to add the 'id' of each table to the GROUP BY clause. But doing so gives '1' for each "commentcount"
tables:

*

*Users

*Profiles (joined to Users (has user_id column))

*Posts(joined to Users (has user_id column))

*Comments(joined to Posts and Users (has user_id and post_id column))

here is my query:
SELECT
    "Post".*,
    COUNT(*) AS "CommentCount",
    "PostComments"."id" AS "PostComments.id",
    "User"."id" AS "User.id",
    "User"."email" AS "User.email",
    "User"."password" AS "User.password",
    "User.Profile"."id" AS "User.Profile.id",
    "User.Profile"."user_id" AS "User.Profile.user_id",
    "User.Profile"."username" AS "User.Profile.username",
    "User.Profile"."gender" AS "User.Profile.gender"
FROM
    "posts" AS "Post"
LEFT OUTER JOIN
    "post_comments" AS "PostComments"
       ON     "Post"."id" = "PostComments"."post_id"
          AND "PostComments"."deleted_at" IS NULL
LEFT OUTER JOIN
    "users" AS "User"
       ON     "Post"."user_id" = "User"."id"
          AND "User"."deleted_at" IS NULL
LEFT OUTER JOIN
    "profiles" AS "User.Profile"
       ON  "User"."id" = "User.Profile"."user_id"
WHERE "Post"."deleted_at" IS NULL
GROUP BY
    "Post"."id";

I am getting the error column "User.id" must appear in the GROUP BY clause or be used in an aggregate function but when i add that, columncount is wrong.

*How Do I group by the Post.id column and still get the corresponding data from the join tables? *
N.B. I would like to convert the correct query to sequelize.js once I've got it figured out, so if anyone happens to know how to do it with sequelize, I'd be more more than welcome :)

A: I'd expect the number of comments per post to be given by this query.
select "post_id", count(*) as num_comments
from "PostComments"
group by "post_id";

Now, no matter what the rest of your query does, you can join on "post_id" from the query above. Something along these lines should work.
select ..., comment_count.num_comments
from ...
-- other joins go here . . .
left outer join (select "post_id", count(*) as num_comments
                 from "PostComments"
                 group by "post_id") comment_count
    on "Post"."id" = comment_count.post_id
where "Post"."deleted_at" is null;


text:
Q: Hachoir - Retrieving data from a group Trying to use Hachoir to retrieve metadata from a video file.  Working reasonably well except when using 'get' or similar to return the width and height values.
I assumed it would be:
metadata.get('width')

But this throws an error (object does not have 'width' property).
When I run the following:
for data in sorted(metadata):
    if len(data.values ) > 0:
        print data.key, data.values[0].value

All that is returned is the information from the "Common" Group.
When I use the:
metadata.exportPlaintext

... the information from "Common", "Video stream" and "Audio stream" is returned.  I could simply parse over the resulting 'text' item and strip out the height and width values, but I would rather try to do it properly using metadata.get('width') or similar.
Looking at the source code, I thought I could use the following:
for key, metadata in metadata.__groups.iteritems():

To iterate through the ._groups in the metadata, but it then throws a "'AsfMetadata' object has no attribute '_groups' - which I'm sure shouldn't be the case as I thought 'AsfMetadata' was a subclass of MultipleMetadata() which does have such a variable.
Probably missing something quite obvious.

A: This seems less straightforward for a WMV file. I have turned the metadata for such videos into a defaultdict, and it is more straightforward to get the image width now:
from collections import defaultdict
from pprint import pprint

from hachoir_metadata import metadata
from hachoir_core.cmd_line import unicodeFilename
from hachoir_parser import createParser

# using this example http://archive.org/details/WorkToFishtestwmv
filename = './test_wmv.wmv'
filename, realname = unicodeFilename(filename), filename
parser = createParser(filename)

# See what keys you can extract
for k,v in metadata.extractMetadata(parser)._Metadata__data.iteritems():
    if v.values:
        print v.key, v.values[0].value

# Turn the tags into a defaultdict
metalist = metadata.extractMetadata(parser).exportPlaintext()
meta = defaultdict(defaultdict)
for item in metalist:
    if item.endswith(':'):
        k = item[:-1]
    else:
        tag, value = item.split(': ')
        tag = tag[2:]
        meta[k][tag] = value

print meta['Video stream #1']['Image width'] # 320 pixels

A: To get width x height from the first top-level metadata group that has the size info in the media file without accessing private attributes and without parsing the text output, you could use file_metadata.iterGroups():
#!/usr/bin/env python
import sys
from itertools import chain

# $ pip install hachoir-{core,parser,metadata}
from hachoir_core.cmd_line import unicodeFilename
from hachoir_metadata import extractMetadata
from hachoir_parser import createParser

file_metadata = extractMetadata(createParser(unicodeFilename(sys.argv[1])))
it = chain([file_metadata], file_metadata.iterGroups())
print("%sx%s" % next((metadata.get('width'), metadata.get('height'))
                     for metadata in it
                     if metadata.has('width') and metadata.get('height')))

To convert metadata into a dictionary (non-recursively, i.e., iterate groups manually if needed):
def metadata_as_dict(metadata):
    return {item.key: (len(item.values) > 1 and
                       [v.value for v in item.values] or
                       item.values[0].value)
            for item in metadata if item.values}


text:
Q: Can I capture an alien in the XCOM: Enemy Unknown demo? I can't find any abilities that aren't related to either killing or healing.  How can I capture an enemy alien?

A: I don't believe there are any stun-capable weapons/soldiers in the demo - which is weird since they make a big deal out of asking you to capture one alive.  In the full game soldiers have specific gear that allows them to stun and capture aliens (although from what I read, it ain't easy!)

A: Actually, there is a pretty awesome demo editor available you can use to mod the Arc Thrower into the demo (it replaces some other item your soldiers would usually have, grenades I think).
Be warned, this is a fan made thing so it might break your demo.


text:
Q: I'm having trouble using the delete operator in C++. I keep getting a "double free or corruption (fasttop)" error when running void clear() {
  while(1)
  {
    BSTNode<Data> *current = root;
      if(!current)
      {
        return;
      }

    while(current->left)
    {
      current = current->left;
    }

    while(current->right)
    {
      current = current->right;
    }
    delete current;
    current = nullptr;
    //std::cout << current->parent->data << std::endl;
  }
}

So I'm pretty confident I did everything else right with the BST as in sorting, and inserting and what not. If we assume that all that is correct. I am just trying to delete all the nodes in the tree. But i get and error when running through the while loop a second time. I doesn't detect that the current which I thought I delete, is null or not there, so it goes into that pointer again and tries to call delete on it which then gives me the "double free or corruption (fasttop)" error.
*** glibc detected *** ./bst: double free or corruption (fasttop): 0x083770b0 ***
======= Backtrace: =========
/lib/libc.so.6[0x975e31]
/software/common/gcc/lib/libstdc++.so.6(_ZdlPv+0x1f)[0x266b8f]
./bst[0x804976e]
./bst[0x804919a]
./bst[0x8048ff4]
/lib/libc.so.6(__libc_start_main+0xe6)[0x91bd26]
./bst[0x8048981]
======= Memory map: ========
0021f000-002fa000 r-xp 00000000 00:14 3229873    /software/common/gcc-     4.8.1/lib/libstdc++.so.6.0.18
002fa000-002fe000 r--p 000db000 00:14 3229873    /software/common/gcc-4.8.1/lib/libstdc++.so.6.0.18
002fe000-002ff000 rw-p 000df000 00:14 3229873    /software/common/gcc-4.8.1/lib/libstdc++.so.6.0.18
002ff000-00306000 rw-p 00000000 00:00 0
0045c000-0045d000 r-xp 00000000 00:00 0          [vdso]
00752000-00770000 r-xp 00000000 fd:00 42112      /lib/ld-2.12.so
00770000-00771000 r--p 0001d000 fd:00 42112      /lib/ld-2.12.so
00771000-00772000 rw-p 0001e000 fd:00 42112      /lib/ld-2.12.so
00774000-0079c000 r-xp 00000000 fd:00 44717      /lib/libm-2.12.so
0079c000-0079d000 r--p 00027000 fd:00 44717      /lib/libm-2.12.so
0079d000-0079e000 rw-p 00028000 fd:00 44717      /lib/libm-2.12.so
00905000-00a96000 r-xp 00000000 fd:00 42155      /lib/libc-2.12.so
00a96000-00a98000 r--p 00191000 fd:00 42155      /lib/libc-2.12.so
00a98000-00a99000 rw-p 00193000 fd:00 42155      /lib/libc-2.12.so
00a99000-00a9c000 rw-p 00000000 00:00 0
00b20000-00b3b000 r-xp 00000000 00:14 3229870    /software/common/gcc-4.8.1/lib/libgcc_s.so.1
00b3b000-00b3c000 rw-p 0001a000 00:14 3229870    /software/common/gcc-4.8.1/lib/libgcc_s.so.1
08048000-0804d000 r-xp 00000000 00:1a 31125426   /home/linux/ieng6/cs100w/bhn013/P1/bst
0804d000-0804e000 rw-p 00004000 00:1a 31125426   /home/linux/ieng6/cs100w/bhn013/P1/bst
08377000-08398000 rw-p 00000000 00:00 0          [heap]
b77d1000-b77d4000 rw-p 00000000 00:00 0
b77ec000-b77ef000 rw-p 00000000 00:00 0
bfa01000-bfa17000 rw-p 00000000 00:00 0          [stack]
Aborted (core dumped)

This is the full error message.
That's pretty much it... I am calling clear with these few lines of code:
virtual ~BST() {
clear();
}

I haven't the slightest clue as to how to approach this.

A: current = nullptr; this line doesn't do anything. It changes a local variable which immediately falls out of scope.
In the next iteration, you will find the same node again, but you freed (delete) it, so accessing it is undefined behaviour.
You want to update the pointer to this node in the BST to nullptr.

A: If you are simply trying to free the tree, then simply do
void clear() {
    delete root;
    root = nullptr;
}

The destructor for BST() should just delete left and right. Recursion will take care of the rest.

A: The variable "current" is defined inside the while (1) {} block, and is initialized at each iteration through the loop with the value of "root", so the first time through the loop, you delete the left/right branches and then you delete the "root", setting current == nullptr. However, you then repeat the loop and re-define current back to the value of "root" again. This causes you to attempt to delete the branches and "root" all over again, a double free.
Move the definition of "current" outside of the while(1) loop. Or better yet, remove the while(1) loop as its not needed, you always exit on one iteration.

A: while(current->left || current->right)
{
  if(current->left)
  {
    current = current->left;
  }
  else if(current->right)
  {
    current = current->right;
  }
}
delete current;

I guess this part performs the deletion process iteratively


text:
Q: HPE J9265A 6600-24XG switches & java for the web interface? Does the latest firmware for HPE J9265A 6600-24XG switches still require java for the web interface?

A: According to the old release notes (PDF, page 16), your switch stopped requiring Java in software version K.15.01.0031 which was released in May 2010.
As of this writing, the most recent software version for this switch is K.15.18.0021 which was released in March 2019.


text:
Q: Problem concerning null safety in functions I have this function called add which adds two numbers and returns the result in dart.
void main() {
  int step1Result = add(n1: 5, n2: 9);
  int step2Result = multiply(step1Result, 5);
  double finalResult = step2Result / 3;
  print(finalResult);
}

int add({int n1, int n2}){
  return n1 + n2;
}

but it keeps on throwing the error that n1 and n2 can't have a value of 'null' because of its type, but the implicit default value is 'null'.
I tried adding the ? mark but the it threw another error saying
The operator '+' can't be unconditionally invoked because the receiver can be 'null'.

A: The error comes from the declaration of your add function:
Here
int add({int n1, int n2}){
    // ...
}

Here you're declaring two optional parameters to the functions.
But n1 and n2 are int and not int?
To fix this issue, you can either transform your function to take int? types.
Or to add the required keyword to tell that the function will only work if both parameters will be given.
void main() {
    int step1Result = add(n1: 5, n2: 9);
    int step2Result = multiply(step1Result, 5);
    double finalResult = step2Result / 3;
    print(finalResult);
}

int add({required int n1,required int n2}){
    return n1 + n2;
}

You can learn more about null-safety syntax and principles on the official documentation: https://flutter.dev/docs/null-safety.
https://api.flutter.dev/flutter/material/DropdownButton-class.html.


text:
Q: Extract certain lines from CLOB column I have a CLOB column where there are lines like this:
[2019-01-24 11:57:05]: Serial.no is: 12330

[2019-01-24 11:57:05]: Buyers: 3

[2019-01-24 11:57:06]: Serial.no is: 23340

[2019-01-24 11:57:06]: Buyers: 6

Now I would like a Select on that column and extract only lines where "Serial.no" is, example:
[2019-01-24 11:57:05]: Serial.no is: 12330
[2019-01-24 11:57:06]: Serial.no is: 23340

I'm hoping for some easy solution because I don't quite understand everything I found so far, thanks in advance.
EDIT:
This returns me one row, first one:
select regexp_substr(My_CLOB, 'Serial.no.*',1) as clob_data from MyTable
WHERE id='1163753';

It returns column in CLOB datatype, but that wouldn't be a problem If I could retrieve all rows.

A: This is a trick to use the connect by clause to increment the regexp index.  Seems to work
WITH test AS (
     SELECT
         '[2019-01-24 11:57:05]: Serial.no is: 12330
[2019-01-24 11:57:05]: Buyers: 3
[2019-01-24 11:57:06]: Serial.no is: 23340
[2019-01-24 11:57:06]: Buyers: 6'
         my_clob
     FROM
         dual
 )
 SELECT
     regexp_substr(my_clob,'Serial.no.*',1,level) AS clob_data
 FROM
     test
 CONNECT BY
     level <= regexp_count(my_clob,'Serial.no.*')


text:
Q: Order of adjectives in terms of characterizing the red beetroot as a raw material for scientific research I have an issue with a proper description of red beetroot as a research material.
During my experiment the fresh red beetroot is grated in shreds.
Following such kind of treatment, does it become the fresh grated red beetroot or the fresh red grated beetroot? Consider that a red beetroot and a beetroot are synonyms.

A: First of all, you are confusing adjectives and adverbs.
When you say grated and put descriptive words in front of that word, those words normally end up acting as adverbs.
Although it's possible to argue for a flat adverb, the following would be more common:

The freshly grated red beetroot.

You put adverbs before the verb and adjective after the verb but before the noun.
So, in the case of the previous sentence, you have this:

The freshlyadv gratedverb redadj beetrootnoun.

But you mean to use fresh as an adjective.
This would normally be expressed as:

The freshadj redadj beetrootnoun.

If you add the verb grated to that sentence, the verb comes before everything else. So, it would become:

The gratedverb freshadj redadj beetrootnoun.

Based on this, here is your original sentence followed by your rephrased sentence:

During my experiment, the fresh red beetroot was grated [into shreds].
  → During my experiment, I grated the fresh red beetroot [into shreds].

Further, if you want to specify fresh as both an adjective and an adverb, you would say:

During my experiment, I used freshly grated fresh red beetroot.

A: The standard order is: opinion, size, physical quality, shape, age, colour, origin, material, type, purpose.
Thus, delicious (opinion) tiny (size), grated (physical quality) oval (shape) fresh (age) red (colour) German (origin) beetroot
Adjective order


text:
Q: Eloquent many to many relationship is always empty I know this question has been asked a lot but all answers didn't seem to work for me - or at least the questions I found were about the pivot table.
I have a many to many relationship (User - Appointment) which is joined by the pivot table "apointment_user", see migrations below.
Schema::create('appointment_user', function (Blueprint $table) {
   $table->unsignedInteger('user_id')->nullable();
   $table->foreign('user_id')->references('id')->on('users');
   $table->unsignedInteger('appointment_id')->nullable();
   $table->foreign('appointment_id')->references('id')->on('appointments');
   $table->primary(['user_id','appointment_id']);
   $table->timestamps();
});
Schema::create('appointments', function (Blueprint $table) {
  $table->increments('id');
  $table->string('title');
  $table->dateTime('date');
  $table->string('location');
  $table->dateTime('departure');
  $table->timestamps();
});
Schema::create('users', function (Blueprint $table) {
  $table->increments('id');
  $table->string('name');
  $table->string('email')->unique();
  $table->string('password');
  $table->date('last_login')->nullable();
  $table->rememberToken();
  $table->timestamps();
  $table->softDeletes();
});

class User extends Model {
  protected $with = ['appointments'];
  public function appointments() : BelongsToMany {
    return $this->belongsToMany(Appointment::class);
  }
}

class Appointment extends Model {
  public function users() : BelongsToMany {
    return $this->belongsToMany(User::class);
  }
}

I have a user with the ID 1 and about 10 appointments, which I do attach to the relationship in a seeder. The pivot table has 10 records, as intended (User ID is always 1).
However, if I dump my User object using dd(User::find(1)), the relationship is always an empty collection. However, a 1:n relationship (between a role works well).
Does anybody see what I'm missing? Any help is appreciated.
Many thanks and kind regards

Edit
I just tried some other kind of dumping. I've simply returned my User-Object as JSON-response and there the relationship is filled with 10 appointments... strange.

A: Though it seems that your table and column names are as Laravel would guess, have you tried expliciting the names?
class User extends Model {
  protected $with = ['appointments'];
  public function appointments() : BelongsToMany {
    return $this->belongsToMany(Appointment::class, 'appointment_user', 'user_id', 'appointment_id');
  }
}

class Appointment extends Model {
  public function users() : BelongsToMany {
    return $this->belongsToMany(User::class, 'appointment_user', 'appointment_id', 'user_id');
  }
}


text:
Q: C++ limit of unsigned int through template I'm using a template to convert integral types into a string representation of their binary values. I used the following:
template<typename T>
std::string ToBinary(const T& value)
{
    const std::bitset<std::numeric_limits<T>::digits + 1> bs(value);
    const std::string s(bs.to_string());

    return s;
}

It works for int but doesn't compile with unsigned int :
unsigned int buffer_u[10];
int buffer_i[10];
...
ToBinary(buffer_i[1]); //compile and works
ToBinary(buffer_u[1]); //doesn't compile -- ambiguous overload

Could you explain why?
EDIT:
Yes, I'm using VS2010

A: Not your ToBinary call is ambiguous, its the constructor call of bitset with an unsigned value. Unfortunately this is a VC++ Bug: http://connect.microsoft.com/VisualStudio/feedback/details/532897/problems-constructing-a-bitset-from-an-unsigned-long-in-the-vc-rc
Edit - Workaround:
template<>
std::string ToBinary<unsigned int>(const unsigned int& value)
{
    const std::bitset<std::numeric_limits<unsigned int>::digits> bs(static_cast<unsigned long long>(value));
    return bs.to_string();
}

A: Are you using VC10? There is already an issue reported: Microsoft connect. Also I'd guess that you might be able to fix it by casting the type to int if it is 32 bit, like this:
string s = ToBinary(*reinterpret_cast<int*>(&buffer_u[1]));

This can be done inside of the method as well if needed. The result of the reinterpret should not be used for arithmetics anymore, though. ;)
Works fine as workaround for me (but looks quite ugly)
template<typename T>
std::string ToBinary(const T& value)
{
    switch (sizeof(T))
    {
    case 8:
        return std::bitset<std::numeric_limits<T>::digits + 1>(*reinterpret_cast<const long*>(&value)).to_string();
    case 4:
        return std::bitset<std::numeric_limits<T>::digits + 1>(*reinterpret_cast<const int*>(&value)).to_string();
    case 2:
        return std::bitset<std::numeric_limits<T>::digits + 1>(*reinterpret_cast<const short*>(&value)).to_string();
    case 1:
        return std::bitset<std::numeric_limits<T>::digits + 1>(*reinterpret_cast<const char*>(&value)).to_string();
    }
    return "n/a";
}

A: If you look at the standard (FDIS n3290), then you see that std::bitset has multiple constructors:
First there is this one:
20.5.1 bitset constructors [bitset.cons]

constexpr bitset(unsigned long long val) noexcept;
Effects: Constructs an object of class bitset, initializing the
  first M bit positions to the corresponding bit values in val. M is the
  smaller of N and the number of bits in the value representation (3.9)
  of unsigned long long. If M < N, the remaining bit positions are
  initialized to zero.

Then there is also this one, which I suspect might be might cause things to become ambigious, when you call it with unsigned int

template <class charT>
explicit bitset(
const charT* str,
typename basic_string<charT>::size_type n = basic_string<charT>::npos,
charT zero = charT('0'), charT one = charT('1'));

Effects: Constructs an object of class bitset as if by
bitset( n == basic_string<charT>::npos ? basic_string<charT>(str) :
basic_string<charT>(str, n), 0, n, zero, one)


text:
Q: Algebraically closed field and it's characteristic Ok so my question is motivated by the theory of Lie algebras, and seeing as I'm not that familiar with a lot of group theoretic notions, just the basics really, my question is as follows.
What can be said about a fields characteristic if we know that it is algebraically closed?
Cheers

A: Nothing because any field has got an algebraic closure i.e., an extension $\mathbb{K}\subset\mathbb{L}$ such that $\mathbb{L}$ is algebraically closed and obviously the two fields have the same characteristic.


text:
Q: b2Edgeshape is not detecting in groundbox I want to create line box2d at runtime(touch event)
I have created the above.  But  i have issue on that.  The issue is line shape(b2EdgeShape) is not detected or collision in groundbox which is also b2EdgeShape.
Here is the coding:
Init Function:
       b2EdgeShape groundBox;

        // bottom

        groundBox.Set(b2Vec2(0,0), b2Vec2((s.width)/PTM_RATIO,0));
        groundBody->CreateFixture(&groundBox,0);

CCTouch Event:
        b2EdgeShape shape1;
        b2FixtureDef fdf;
        fdf.density = 1.0;
        fdf.friction = 0.3;
        fdf.restitution = 0.2;
        fdf.shape=&shape1;
        shape1.Set(b2Vec2(s.x, s.y), b2Vec2(e.x, e.y));
        body->CreateFixture(&shape1,0.0f);

Is any wrong or logic issues?

A: Two edge shapes cannot collide with each other.

According to Box2d manual.......
A major limitation of edge shapes is that they can collide with circles and polygons but
not with themselves. The collision algorithms used by Box2D require that at least one of two colliding
shapes have volume. Edge shapes have no volume, so edge-edge collision is not possible.


text:
Q: ASP.NET: URI handling I'm writing a method which, let's say, given 1 and hello should return http://something.com/?something=1&hello=en.
I could hack this together pretty easily, but what abstraction functionality does ASP.NET 3.5 provide for building URIs?  I'd like something like:
URI uri = new URI("~/Hello.aspx"); // E.g. ResolveUrl is used here
uri.QueryString.Set("something", "1");
uri.QueryString.Set("hello", "en");
return uri.ToString(); // /Hello.aspx?something=1&hello=en

I found the Uri class which sounds highly relevant, but I can't find anything which does the above really. Any ideas?
(For what it's worth, the order of the parameters doesn't matter to me.)

A: As far I know nothing here. So everybody has its own implementation.
Example from LinqToTwitter.
    internal static string BuildQueryString(IEnumerable<KeyValuePair<string, string>> parameters)
    {
        if (parameters == null)
        {
            throw new ArgumentNullException("parameters");
        }

        StringBuilder builder = new StringBuilder();
        foreach (var pair in parameters.Where(p => !string.IsNullOrEmpty(p.Value)))
        {
            if (builder.Length > 0)
            {
                builder.Append("&");
            }

            builder.Append(Uri.EscapeDataString(pair.Key));
            builder.Append("=");
            builder.Append(Uri.EscapeDataString(pair.Value));
        }

        return builder.ToString();
    }

UPDATE:
You can also create extension method:
public static UriBuilder AddArgument(this UriBuilder builder, string key, string value)
{
 #region Contract

 Contract.Requires(builder != null);
 Contract.Requires(key != null);
 Contract.Requires(value != null);

 #endregion

 var query = builder.Query;

 if (query.Length > 0)
 {
      query = query.Substring(1) + "&";
 }

 query += Uri.EscapeDataString(key) + "="
      + Uri.EscapeDataString(value);

 builder.Query = query;

 return builder;
}

And usage:
var b = new UriBuilder();
b.AddArgument("test", "test");

Please note that everything here is untested.

A: Just combined answers=>
public static class UriBuilderExtensions
{
    public static void AddQueryArgument(this UriBuilder b, string key, string value)
    {
        key = Uri.EscapeDataString(key);
        value = Uri.EscapeDataString(value);

        var x = HttpUtility.ParseQueryString(b.Query);
        if (x.AllKeys.Contains(key)) throw new ArgumentNullException
                ("Key '{0}' already exists!".FormatWith(key));
        x.Add(key, value);
        b.Query = x.ToString();
    }

    public static void EditQueryArgument(this UriBuilder b, string key, string value)
    {
        key = Uri.EscapeDataString(key);
        value = Uri.EscapeDataString(value);

        var x = HttpUtility.ParseQueryString(b.Query);
        if (x.AllKeys.Contains(key))
            x[key] = value;
        else throw new ArgumentNullException
                ("Key '{0}' does not exists!".FormatWith(key));
        b.Query = x.ToString();
    }

    public static void AddOrEditQueryArgument(this UriBuilder b, string key, string value)
    {
        key = Uri.EscapeDataString(key);
        value = Uri.EscapeDataString(value);

        var x = HttpUtility.ParseQueryString(b.Query);
        if (x.AllKeys.Contains(key))
            x[key] = value;
        else
            x.Add(key, value);
        b.Query = x.ToString();
    }

    public static void DeleteQueryArgument(this UriBuilder b, string key)
    {
        key = Uri.EscapeDataString(key);
        var x = HttpUtility.ParseQueryString(b.Query);
        if (x.AllKeys.Contains(key))
            x.Remove(key);
        b.Query = x.ToString();
    }
}

Half baked code. But should work well enough.

A: Edited to correct massively incorrect code
Based on this answer to a similar question you could easily do something like:
UriBuilder ub = new UriBuilder();

// You might want to take more care here, and set the host, scheme and port too
ub.Path = ResolveUrl("~/hello.aspx"); // Assumes we're on a page or control.

// Using var gets around internal nature of HttpValueCollection
var coll = HttpUtility.ParseQueryString(string.Empty);

coll["something"] = "1";
coll["hello"] = "en";

ub.Query = coll.ToString();
return ub.ToString();
// This returned the following on the VS development server:
// http://localhost/Hello.aspx?something=1&hello=en

This will also urlencode the collection, so:
coll["Something"] = "1";
coll["hello"] = "en&that";

Will output:
Something=1&hello=en%26that

A: There's also the UriBuilder class

A: This is something that might appeal to you- recently at work I was looking at a way to "type" commonly used URL query string variables and so developed this interface:
   'Represent a named parameter that is passed from page-to-page via a range of methods- query strings, HTTP contexts, cookies, session, etc.
Public Interface INamedParam

    'A key that uniquely identfies this parameter in any HTTP value collection (query string, context, session, etc.)
    ReadOnly Property Key() As String

    'The default value of the paramter.
    ReadOnly Property DefaultValue() As Object

End Interface

You can then implement this interface to describe a query string parameter, such an implementation for your "Hello" param might look like this:
Public Class HelloParam
    Implements INamedParam

    Public ReadOnly Property DefaultValue() As Object Implements INamedParam.DefaultValue
        Get
            Return "0"
        End Get
    End Property

    Public ReadOnly Property Key() As String Implements INamedParam.Key
        Get
            Return "hello"
        End Get
    End Property
End Class

I developed a small (and very, very basic) class to help build URLs using these strongly typed parameters:
Public Class ParametrizedHttpUrlBuilder

    Private _RelativePath As String
    Private _QueryString As String

    Sub New(ByVal relativePath As String)
        _RelativePath = relativePath
        _QueryString = ""
    End Sub

    Public Sub AddQueryParameterValue(ByVal param As INamedParam, ByVal value As Object)
        Dim sb As New Text.StringBuilder(30)
        If _QueryString.Length > 0 Then
            sb.Append("&")
        End If
        sb.AppendFormat("{0}={1}", param.Key, value.ToString())
        _QueryString &= sb.ToString()
    End Sub

    Public Property RelativePath() As String
        Get
            Return _RelativePath
        End Get
        Set(ByVal value As String)
            If value Is Nothing Then
                _RelativePath = ""
            End If
            _RelativePath = value
        End Set
    End Property

    Public ReadOnly Property Query() As String
        Get
            Return _QueryString
        End Get
    End Property

    Public ReadOnly Property PathAndQuery() As String
        Get
            Return _RelativePath & "?" & _QueryString
        End Get
    End Property

End Class

A: Here's my version (needs .NET4 or a ToArray() call on the Select)
var items = new Dictionary<string,string> { { "Name", "Will" }, { "Age", "99" }};

String query = String.Join("&", items.Select(i => String.Concat(i.Key, "=", i.Value)));

I thought the use of Dictionary might mean the items can get reordered, but that doesn't actually seem to be happening in experiments here - not sure what that's about.


text:
Q: Canvas HTML | Track a line perpendicular to two point and passing through a point In a html canvas I draw a line starting from point A and ending at point B.
I should, given a point C, draw a line perpendicular to the line from A and B and that passes from C.
Below is how I create the line that passes from A and B (the points are taken as input, for convenience in this example they are supplied by variable.

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.moveTo(50, 100);
ctx.lineTo(150, 100);
ctx.stroke();
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

Now given C (for example C = 80, 130) I would like to draw a line that is perpendicular to the line between A and B and that passes from C
How can I calculate points that allow me to create this line?
For example this:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.moveTo(50, 100);
ctx.lineTo(150, 100);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(80, 10);
ctx.lineTo(80, 130);
 ctx.arc(80, 130, 2, 0, 360, false); // C
ctx.stroke();
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

Thanks so much for helping!

A: In the not trivial (line isn't vertical or horizontal) case, you just need to know that the gradient of the perpendicular line is minus one over the gradient of the line. I hope the below code snippet helps.

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var pointA = {
  x: 0.0,
  y: 0.0
};
var pointB = {
  x: 200.0,
  y: 150.0
};
var pointC = {
  x: 80.0,
  y: 130.0
};
var pointD = {
  x: 0.0,
  y: 0.0
};

if (pointA.y == pointB.y) { // AB is horizontal
  pointD.x = pointC.x
  pointD.y = pointA.y
} else if (pointA.x == pointB.x) { // AB is vertical
  pointD.x = pointA.x
  pointD.y = pointC.y
} else { // need some geometry
  var gradientOfAB = (pointA.y - pointB.y) / (pointA.x - pointB.x);
  var interceptOfAB = pointA.y - gradientOfAB * pointA.x;

  var gradientOfCD = -1 / gradientOfAB;
  var interceptOfCD = pointC.y - gradientOfCD * pointC.x;

  pointD.x = (interceptOfAB - interceptOfCD) / (gradientOfCD - gradientOfAB);
  pointD.y = gradientOfCD * pointD.x + interceptOfCD;
}

ctx.beginPath();
ctx.moveTo(pointA.x, pointA.y);
ctx.lineTo(pointB.x, pointB.y);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(pointD.x, pointD.y);
ctx.lineTo(pointC.x, pointC.y);
ctx.arc(pointC.x, pointC.y, 2, 0, 360, false);
ctx.stroke();
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
  Your browser does not support the HTML5 canvas tag.
</canvas>


text:
Q: Using the same connection (NATS) within a service I have a service which will publish messages to NATS on two different occasions - on entity created and on entity updated.
In the official NATS tutorial, the publisher always creates a new connection and inside the using block it publishes the message and flushes the connections, e.g:
using (IEncodedConnection connection = new ConnectionFactory().CreateEncodedConnection(options))
{
    c.OnSerialize = jsonSerializer;
    connection.Publish(subject, payload);
    connection.Flush();
}

However reading about this and from my own prespective I really need only one connection which I can reuse throughout the life of my service. Implementing this seems like a trivial work:
public class EncodedConnection
{
    private static IEncodedConnection encodedConnection;

    private EncodedConnection()
    {

    }

    public static IEncodedConnection GetEncodedConnection()
    {
        if (encodedConnection != null)
        {
            return encodedConnection;
        }

        encodedConnection = new ConnectionFactory().CreateEncodedConnection();
        encodedConnection.OnSerialize = jsonSerializer;

        return encodedConnection;
    }
}

My questions are

*

*since I don't provide a using block for the connection is it safe to pass it around like this.

*Also should I call connection.Flush(); everytime i publish a message and if I call flush do I need to create new connection which basically means that I have to create a new connection everytime nevertheless.


text:
Q: pyspark - Check if shuffle caused when joining 2 DFs repartitioned on same column
*

*Spark Version: 2.4.7

*spark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1) is set

I have two pyspark dataframes which I want to co-partition and hence avoid shuffling. I tried to
repartition them, giving same number of partitions and same column for repartitioning, and wrote as
parquet files. Now I'm trying to check if a shuffle is actually happenning or not when I subsequently
use these tables.
Stats on initial dataframes
>>> initital_df1.count(), initial_df1.select('id').distinct().count()  # distinct rows per id
(1000, 1000)
>>> initital_df2.count(), initial_df2.select('id').distinct().count()  # 300 rows per id (25 yrs of data, 1 row for each month)
(300000, 1000)
>>> initial_df1.rdd.getNumPartitions(), initial_df2.rdd.getNumPartitions()
(2, 8)
>>> initial_df1.rdd.glom().map(len).collect()
[500, 500]
>>> initial_df2.rdd.glom().map(len).collect()
[56400, 50700, 45000, 40800, 36300, 30000, 25200, 15600]

Step 1: repartition the initital dataframes with same number of partitions and same partitioner column
>>> initial_df1.repartition(4, 'id').write.parquet(df1_write_path)
>>> initial_df2.repartition(4, 'id').write.parquet(df2_write_path)

Step 2: read the previously repartitioned dataframes at a later point of time to perform some computation
>>> repartitioned_df1 = spark.read.parquet(df1_write_path)
>>> repartitioned_df2 = spark.read.parquet(df2_write_path)

Stats on repartitioned dataframes

>>> repartitioned_df1.rdd.getNumPartitions(), repartitioned_df2.rdd.getNumPartitions()
(4, 4)
>>> initial_df1.rdd.glom().map(len).collect()
[279, 255, 238, 228]
>>> initial_df2.rdd.glom().map(len).collect()
[83700, 76500, 71400, 68400]

Step 3: join the repartitioned dataframes read above to perform aggregations and write the aggregated dataframe
>>> agg_df = repartitioned_df1.join(repartitioned_df2, 'id').groupBy('id').agg(F.sum(col1_df1), F.avg(col1_df2))
>>> agg_df.write.parquet(agg_df_write_path)

Tested two scenarios:

*

*repartitioned_df1 and repartitioned_df2 are used in step (3)

*initial_df1 and initial_df2 are used in step (3)

Observarions:

*

*agg_df.explain() gives the same spark plan in both the cases

*Shuffle read and write data in SparkUI shows the same set of values for both cases

*scenario (1) is at least 2x faster than scenario (2)

Question: How do I check if a shuffle is being caused (i.e. the dataframes are hash partitioned again) or the initial repartitioning caused the two dataframes to be co-partitioned and hence there would just be movement of partitions already created during initial writing step?


text:
Q: Lazy Loading not working on setting scrollable: {virtual: true} in Kendo Grid I am a beginner working on Kendo Grid. I wanted to load the data on demand in the grid, like :

*

*I set the page size to 50, when a user scrolls down to 50 rows, the grid should retrieve next 50 rows from database and display it on demand.

*To do this, I changed "scrollable: true" to "scrollable: {virtual: true}". But this disables scrolling in the grid.

I am stuck, let me know if anyone has faced the same issue and found any solution for it.
Thanks for your help.

A: You need to set few true serverpaging as true in your datasource as well. I will post a demo of Datasource portion, hope that helps someone.
  var sharedDataSource = new kendo.data.DataSource({
            autoSync: true,
            transport: {
                read: {
                    url: "/Home/GetJson",
                    dataType: "json"
                }

            },
            schema: {
                type: "json",
                data: "data",
                total: "total",
                model: {
                    id: "Id",
                    fields: {
                        Id: { editable: false },
                        HostName: { editable: false },
                        Scope: { editable: true },
                    }
                }
            },
            serverPaging: true,
            serverSorting: true,
            pageSize: 50
        });


text:
Q: How can I do a redirect from the process_payment function in a custom gateway in wordpress? I am trying to develop a custom gateway where I need to get order information such as value, credit card number, card owners name, address etc. After getting this, I will send a request using the API provided by Centinel 3D Secure. If successful they will return a url for the credit card bank along with some other information which I am to POST to the bank URL.
The bank will then post data using a form to my callback URL. I can't seem to get it to work however. This is a sample of my code:
function process_payment( $order_id ) {
            global $woocommerce;
            //code to get data using API
            if( (strcasecmp('Y', $_SESSION['Centinel_Enrolled']) == 0){

                 echo '<form action="'.$_SESSION["ACSUrl"].'"" method="post">
                  <input type=hidden name="PaReq" value="'.$_SESSION["RandomValue"].'"/>
                  <input type=hidden name="TermUrl" value="'$myWPCallbackUrl.'?>"/>
                  <input type=hidden name="MD" value="Data"/>
                  <input type="submit" value="Submit" id="submit_centinel_payment_form"/>

                  </form>

            }

This doesn't do a redirect to the server. Does anyone have any idea why this doesn't work?

A: This is an old question, but for all of you struggling with the same problem now, I hope my answer will help. I had the exact same problem and this is how I solved it.
I don't know much what is happening in the background of process_payment( $ order_id ) function that is causing this kind of behavior, but you can not redirect from the function via php echo, nor via javascript, but only via function return statement, like in example below:
function process_payment( $order_id ) {
    global $woocommerce;
    $order = new WC_Order( $order_id );

    // Mark as on-hold (we're awaiting the cheque)
    $order->update_status('on-hold', __( 'Awaiting cheque payment', 'woocommerce' ));

    // Reduce stock levels
    $order->reduce_order_stock();

    // Remove cart
    $woocommerce->cart->empty_cart();

    // Return thank you redirect
    return array(
        'result' => 'success',
        'redirect' => $this->get_return_url( $order )
    );
}

(example pasted from Wocommerce Payment Gateway API)
So, for your specific problem I would put your form in separate file, secure_form.php. All needed data will be accessible via get parameters:
<!DOCTYPE html>

    <title>3D Secure Verification</title>

    Invoking 3-D secure form, please wait ...
    <form name="form" action="<?php echo rawurldecode( $_GET[ 'acs_url' ] ); ?>" method="post">
    <input type="hidden" name="PaReq" value="<?php echo rawurldecode( $_GET[ 'pareq' ] ); ?>">
    <input type="hidden" name="TermUrl" value="<?php echo rawurldecode( $_GET[ 'term_url' ] ); ?>">
    <input type="hidden" name="MD" value="<?php echo rawurldecode( $_GET[ 'authencity_token' ] ); ?>">

Please click
<input id="to-asc-button" type="submit">

    </form>

And then, in your process_payment( $ order_id ) function you set the variables, and call your form (don't forget to pass get parameters):
function process_payment( $order_id ) {
    global $woocommerce;
    //code to get data using API
    if( (strcasecmp('Y', $_SESSION['Centinel_Enrolled']) == 0){
        // Set variables and redirect to 3DS check form
        $acs_url          = rawurlencode( $_SESSION["ACSUrl"] );
        $pareq            = rawurlencode( $_SESSION["RandomValue"] );
        $authencity_token = rawurlencode( 'Data' );
        $term_url         = rawurlencode( $myWPCallbackUrl );
        $url              = path_to_secure_form.php . "?acs_url=$acs_url&pareq=$pareq&authencity_token=$authencity_token&term_url=$term_url";

        return [
            'result'   => 'success',
            'redirect' => $url
        ];
    }
}

A: using pur javascript you can achieve this goal. Instead of using this code

You can use this code

provided you add an id to your form.
You also have syntax error in your form and I would suggest to take out the javascript code outside of form element. You can finally have this code
echo '<form action="'.$_SESSION["ACSUrl"].'" method="post" id="paymentForm">
                  <input type=hidden name="PaReq" value="'.$_SESSION["RandomValue"].'"/>
                  <input type=hidden name="TermUrl" value="'.$myWPCallbackUrl.'"/>
                  <input type=hidden name="MD" value="Data"/>
                  <input type="submit" value="Submit" id="submit_centinel_payment_form"/>

                  </form>

';


text:
Q: send() method not working right? In Laravel 5.2, I'm using send() method to return [] only from construct:
In the same controller:
public function __construct() {
   return response()->json()->send();
}
public function index() {
       return 22;
    }

But actually, when call function index, I get []22;
How can I fix this, or another method can do that?


text:
Q: boost::asio UDP broadcasting I want to broadcast UDP messages to all computers in a local network using boost::asio. Working through the examples I came up with
try {
    socket.open(boost::asio::ip::udp::v4());
    boost::asio::socket_base::broadcast option(true);
    socket.set_option(option);
    endpoint = boost::asio::ip::udp::endpoint(
        boost::asio::ip::address::from_string("192.168.1.255"),
        port);
}
catch(std::exception &e) {
}

and want to broadcast messages from my queue with
while(!queue.empty()) {
    std::string message = queue.front();
    boost::system::error_code ignored_error;
    socket.send_to(
        boost::asio::buffer(message),
        endpoint,
        0, ignored_error);
    queue.pop_front();
}

but my code throws an exception invalid argument exception in the first code block. It works fine for 127.0.0.1 though. What am I doing wrong?

A: Try the following code snippet to send a UDP broadcast, utilizing the ba::ip::address_v4::broadcast() call to get an endpoint:
    bs::error_code error;
    ba::ip::udp::socket socket(_impl->_ioService);

    socket.open(ba::ip::udp::v4(), error);
    if (!error)
    {
        socket.set_option(ba::ip::udp::socket::reuse_address(true));
        socket.set_option(ba::socket_base::broadcast(true));

        ba::ip::udp::endpoint senderEndpoint(ba::ip::address_v4::broadcast(), port);

        socket.send_to(data, senderEndpoint);
        socket.close(error);
    }


text:
Q: Previous day function Is there a function for previous day in discoverer/oracle? I need to run a daily report for data through the previous day. I was hoping there is a formula using system date -1, but I haven't been able to find anything to help.

A: You are very close
select trunc(sysdate) -1 yesterday
from dual

trunc() strips out the time portion.  You could also put the -1 inside the brackets if you want.  The results will be the same.


text:
Q: R Studio package installation problems: clang version doesn't match? I'm on a Mac OS Sierra WITHOUT admin privileges (ugh). There's a bunch of packages I really need to install, but for the vast majority, when I try to install, I get the following error:
make: x86_64-apple-darwin13.4.0-clang: No such file or directory
make: *** [base64.o] Error 1
ERROR: compilation failed for package 'RCurl'

I have clang installed but it's a different version:
clang --version
clang version 4.0.1 (tags/RELEASE_401/final)
Target: x86_64-apple-darwin16.7.0
Thread model: posix

I suspect this mismatch is the problem, but not being particularly savvy with installs and the innards of the computer, I really have no idea how to resolve it. I haven't been able to find a similar enough issue that someone else that that's helped my situation.
I've tried editing my path to include all the possibilities that occur to me. I've also tried installing devtools (same error, essentially). My sessionInfo() and r --version information are below.
r --version
R version 3.4.2 (2017-09-28) -- "Short Summer"
Copyright (C) 2017 The R Foundation for Statistical Computing
Platform: x86_64-apple-darwin13.4.0 (64-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under the terms of the
GNU General Public License versions 2 or 3.
For more information about these matters see
http://www.gnu.org/licenses/.

... and sessionInfo():
R version 3.4.2 (2017-09-28)
Platform: x86_64-apple-darwin13.4.0 (64-bit)
Running under: macOS Sierra 10.12.6

Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libLAPACK.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
[1] compiler_3.4.2 tools_3.4.2


text:
Q: Opening link in new tab from Polymer Modal Hi just a very simple question. I have a Modal in my Polymer 3 page. I want to add a link in the model and open the link in new Tab, but its not working. The link opens in the same window, where the popup is opened?

${item.title}

${item.content}

        Read more

     <button on-click="${() => this._closeModal()}">Close</button>

A: Please try this

${item.title}

${item.content}

        Read More

    <button on-click="${() => this._closeModal()}">Close</button>

A: Try adding this line. It works!
Read more


text:
Q: Can not fit training data feature to match label data after Vectorizing i have school project that demand me to use machine learning, after several troubleshoot i meet deadend, don't know how to solve it.
i have this code:

db_connection = 'mysql+pymysql://root:@localhost/databases'
conn = create_engine(db_connection)

df = pd.read_sql("SELECT * from barang", conn)

cth_data = pd.DataFrame(df)

#print(cth_data.head())
cth_data = cth_data.dropna()

y = cth_data['kode_aset']
x = cth_data[['merk','ukuran','bahan','harga']]
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3)
clf=RandomForestClassifier(n_estimators=100)

vectorizer = CountVectorizer( max_features = 50000, ngram_range = ( 1,50 ) )

d_feture = vectorizer.fit_transform(x_train)
#d_label = vectorizer.transform(y_train)

clf.fit(d_feture, y_train)
t_data = vectorizer.transform(x_test)

y_pred=clf.predict(t_data)
print ("Model_Accuracy: " + str(np.mean(y_pred == y_test)))

i fetched the data from mysql database here is  the database:
Screenshot of database:

ended up with this kind of error:

File "Machine_learn_V_0.0.1.py", line 41, in <module>
    clf.fit(d_feture, y_train)
  File "C:\Python35\lib\site-packages\sklearn\ensemble\forest.py", line 333, in fit
    for i, t in enumerate(trees))
  File "C:\Python35\lib\site-packages\sklearn\externals\joblib\parallel.py", line 917, in __call__
    if self.dispatch_one_batch(iterator):
  File "C:\Python35\lib\site-packages\sklearn\externals\joblib\parallel.py", line 759, in dispatch_one_batch
    self._dispatch(tasks)
  File "C:\Python35\lib\site-packages\sklearn\externals\joblib\parallel.py", line 716, in _dispatch
    job = self._backend.apply_async(batch, callback=cb)
  File "C:\Python35\lib\site-packages\sklearn\externals\joblib\_parallel_backends.py", line 182, in apply_async
    result = ImmediateResult(func)
  File "C:\Python35\lib\site-packages\sklearn\externals\joblib\_parallel_backends.py", line 549, in __init__
    self.results = batch()
  File "C:\Python35\lib\site-packages\sklearn\externals\joblib\parallel.py", line 225, in __call__
    for func, args, kwargs in self.items]
  File "C:\Python35\lib\site-packages\sklearn\externals\joblib\parallel.py", line 225, in <listcomp>
    for func, args, kwargs in self.items]
  File "C:\Python35\lib\site-packages\sklearn\ensemble\forest.py", line 119, in _parallel_build_trees
    tree.fit(X, y, sample_weight=curr_sample_weight, check_input=False)
  File "C:\Python35\lib\site-packages\sklearn\tree\tree.py", line 801, in fit
    X_idx_sorted=X_idx_sorted)
  File "C:\Python35\lib\site-packages\sklearn\tree\tree.py", line 236, in fit
    "number of samples=%d" % (len(y), n_samples))
ValueError: Number of labels=223 does not match number of samples=4

A: CountVectorizer takes strings, it can not process columns as you wished it would, which means you should concatenated strings from cth_data[['merk','ukuran','bahan','harga']] into a single column, e.g.:
cols = ['merk','ukuran','bahan','harga']
cth_data['combined'] = cth_data[cols].apply(lambda row: '_'.join(row.values.astype(str)), axis=1)

x = cth_data["combined"]

from there on your code should work


text:
Q: Replace explicit `virtual_alias_domains` by domains in `virtual_alias_maps` I have a working Postfix config with some local mailboxes, some local aliases and a handful of purely virtual alias domains. Because I find it tedious to add all to virtual_alias_domains I'm asking: How to define them by simply using them in virtual_alias_maps?
Example:
### /etc/postfix/main.cf
myhostname = mx.example.com
virtual_alias_domains =
    foo.example
    bar.example
virtual_alias_maps = hash:/etc/postfix/virtual

### /etc/postfix/virtual
single-user@foo.example single-user@example.com
@bar.example            whole-domain@example.com

# this one is missing in virtual_alias_domains and won't work
@baz.example            me@example.com

When adding new entries like baz.example I will probably forget to list them in virtual_alias_domains. This also breaks the common rule of Don't repeat yourself.
How to get rid of virtual_alias_domains or "compile it dynamically"?
http://www.postfix.org/postconf.5.html#virtual_alias_domains says the default of virtual_alias_domains is $virtual_alias_maps:

The default value is $virtual_alias_maps so that you can keep all information about virtual alias domains in one place.

But this seems not to work for me.
Jan 31 00:09:25 HOSTNAME postfix/smtpd[5064]: NOQUEUE: reject: RCPT from FROM_HOSTNAME[185.XXX.XXX.XXX]: 454 4.7.1 <FROM_ADDRESS>:
  Relay access denied; from=<FROM_ADDRESS> to=<TO_ADDRESS> proto=ESMTP helo=<FROM_HOSTNAME>

(anonymized log, inserted newline for readability)
My actual configuration:
# postconf -n | egrep ^virtual_
virtual_alias_maps = hash:/etc/postfix/virtual

# postconf | egrep ^virtual_alias
virtual_alias_address_length_limit = 1000
virtual_alias_domains = $virtual_alias_maps
virtual_alias_expansion_limit = 1000
virtual_alias_maps = hash:/etc/postfix/virtual
virtual_alias_recursion_limit = 1000

Unfortunately I don't know to dump the configuration of virtual_alias_domains after variable expansion.

A: I ran into this same problem.  This answer is correct but I wasn't quite understanding what it meant.
To use a single file for both virtual_alias_maps and virtual_alias_domains, you need to separately include each domain that you are forwarding for, without an @.  To keep Postfix happy, both a key and value are required, but for these domain entries the value can be anything you want, since Postfix is only checking for the existence of the key (the domain).
Example /etc/postfix/virtual:
# These are the virtual aliases:
single-user@foo.example single-user@example.com
@bar.example            whole-domain@example.com
@baz.example            me@example.com

# Repeat the bare domains:
foo.example             LITERALLY_ANYTHING
bar.example             LITERALLY_ANYTHING
baz.example             LITERALLY_ANYTHING

You could conceivably keep a file of just the alias mappings, and run it through a script to extract the domains and create the combined output file, but at that point you could also pass the domains to postconf -e, or put the domain entries in a separate file and run postmap on it, then tell virtual_alias_domains to use that file.  For me, adding the extra domain entries manually is fine, but it is nice to have it all in one place.


text:
Q: LED chaser using as few wires as possible I need to create a cable that has 4 LEDs attached every 3m.
The cable will be 40m long and will have some control electronics at the beginning.
The purpose of the cable will be a LED chaser.
I've read whatever I could find here and elsewhere about LED chaser and they all focus on CD4017 and 555's. My requirement is anything that is efficient.
I was thinking of some cheap MCU and 15 miniature PCB's connected with SPI, but at best that would give me about 20 wires in the cable to create a LED chaser.
Is there a better way with less wires?? I don't need the complete solution I just need someone to point me to a better solution.
Anything is acceptable, LED driver chips, I2C, SPI, CAN, whatever can get me to as few wires as possible.

A: You could do it with three wires (power, ground and signal) and a set of MCU's. You have one master node which send data out of the UART TX pin. The others all pick it up at their RX pin. You make a 2-byte protocol. e.g. first byte always has MS bit set which indicates an address giving you 128 slaves to talk to. Second byte has MS bit clear which is the LED pattern to output giving you control of 7 LEDs per MCU. You may need to boost the output of the master TX with a good driver IC but that depends on your baudrate.

Just though of an alternative: chain the MCU's up. The first one picks up the data and re-transmit it at it's tx if it is not for him. This makes that each MCU needs to talk only to the next one: lower driver strength. Note that both schemes give you more then a simple LED chaser as you can make any pattern you want.

A: Cable signals Power, Ground, Reset, Shift clock, Shift Signal. Shift signal is daisychained from MCU to MCU.
No need for SPI. First MCU generates a low frequency shift clock at chase frequency and every no of leds shift clocks creates a Shift signal. It also creates the reset at the start of each chase cycle to guarantee the state of the devices in the chain.
All the other MCUs read their shift signal in on the rising edge of the shift clock and if present raise their own shift signal out and turn on the led if no shift signal in turn off the LED and turn off the shift signal out. You can do that with one D type but MCUs are probably cheaper these days and give you some flexibility in what you can do particularly for noise rejection in this application.


text:
Q: SSIS Invalid character "." in filename error in script task I have a task to split a single file into two separate files which I have done. However, afterward I need to move the source file from the source directory into an Archive folder so it does not get picked up again the next day.
The file name is quite bad, something like "DFG.AE234125.HDS932.H001.U001", but is out of my control to rename as we receive the file like that from external. My loop works fine in the sense that it picks up all files and splits them as it should by iterating using a User::SelectedFile variable. When it reaches the newly added "move file to archive" script task it gets stuck in loading for almost a full minute and returns error like "Filename cannot contain character like '/\=,.'" Script is in C# and it declaring two strings one for the archive path and the other for the file name and uses the User::SelectedFile variable.
Things I have considered/tried:

*

*Checking the file paths (they are correct as I am using a test
directory on my C Drive as I do not have access to the server
location)

*As I am using local location it can't be a permission problem
especially as it is picking up the file for the split.

*This is a standalone process that uses flat file connections, so
there is not server connection issue.

*I have also tried using File System Task for this but get the same
error for the name.

*The C# script itself is copy&pasted from another package that needs
to move the processed file to an archive folder. It works there. All
I have done in the new script is changing the variables for the
path.

*I have added breakpoints and can see that the variables have the
correct values when they reach the script task.

The issue seems to be at the point where the process lands at the script task. At this point the split has already been done successfully. Can someone advise on a workaround to ignore the "."s in the filename so I can move the damn thing to the archive folder?
This is my first post on Stackoverflow so any feedback on the post itself is welcome.
Many thanks in advance.
IP


text:
Q: SQL*Loader-522: lfiopn failed for file I am getting below error in my script which is running a SQLLDR :
SQL*Loader-522: lfiopn failed for file (/home/abc/test_loader/load/badfiles/TBLLOAD20150520.bad)

As far my knowledge this is the error related to permission,but i am wondering in the folder "/load" there is no "badfiles" folder present .i have already define badfiles folder outside the load folder,but why in the error it is taking this location ?
is it like my input file having some problem and SQLLDR trying to create a bad file in the mention location ?
below is the SQLLDR command :
$SQLLDR $LOADER_USER/$USER_PWD@$LOADER_HOSTNAME control=$CTLFDIR/CTL_FILE.ctl BAD=$BADFDIR/$BADFILE$TABLE_NAME ERRORS=
0 DIRECT=TRUE PARALLEL=TRUE LOG=$LOGDIR/$TABLE_NAME$LOGFILE &

below is the control file temp :
LOAD DATA
INFILE '/home/abc/test_loader/load/FILENAME_20150417_001.csv' "STR '\n'"
APPEND
INTO TABLE STAGING.TAB_NAME
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
(
  COBDATE,
--
--
--
  FUTUSE30 TERMINATED BY WHITESPACE
)

A: Yes, your input file is having a problem so the sqlldr wants to create a file containing rejected rows (BAD file). The BAD file creation fails due to insufficient privileges - the user who runs the sqlldr does not have rights to create file in the folder you defined to contain BAD files.
Add write privileges on the BAD folder to the user who runs the sqlldr or place the BAD folder elsewhere.

A: This is likely some kind of permissions issue on writing the log file, maybe after moving services to a different server.
I ran into the same error.  Problem was resolved by changing the name of the existing log file in filesystem and rerunning process.  Upon rerunning, the SQLLDR process was able to recreate the log file, and subsequent executions were able to rewrite the log.


text:
Q: Multi sports tournament $10$ teams $6$ sports simultaneous I'm hosting a bar sports tournament with $10$ teams and $6$ different sports (pool, darts, table tennis, foosball, beer pong and cornhole). Trying to get the fixtures as fair as possible so that each team plays each sport twice and playing against the same team multiple times is minimised. Are there any formulas to follow? There is potential for $11$ or $12$ teams to end up competing. I feel like having $12$ or $13$ would make this task a lot easier!
Edit: The plan is to have 12 rounds with each sport being played in each round. There is only one pool table, dart board etc available so the same sport cannot be played in the same round. Are there simpler solutions for say 12 teams?
Edit 2: I haven't done any mathematics beyond high school 10 years ago. I've just tried to figure it out as best I can drawing up tables and assigning teams against each other in different slots but ending up with teams playing the same sport or against each other again as there are limited playing slots. Ideally I'd like to know if there is a formula that can be applied to x amount of teams/sports/rounds for multi sports tournaments as all the fixture generators I've tried using only account for one sport being played.

A: Label the teams $0$ to $9$ and the sports $0$ to $5$. Here $k\,\%\,6$ denotes the remainder of $k$ modulo $6$.
First let each team  $i$ play each other team $j$ in the sport $i+j\,\%\,6$:
$$
\matrix{&1&2&3&4&5&0&1&2&3}\\
\matrix{1&&3&4&5&0&1&2&3&4}\\
\matrix{2&3&&5&0&1&2&3&4&5}\\
\matrix{3&4&5&&1&2&3&4&5&0}\\
\matrix{4&5&0&1&&3&4&5&0&1}\\
\matrix{5&0&1&2&3&&5&0&1&2}\\
\matrix{0&1&2&3&4&5&&1&2&3}\\
\matrix{1&2&3&4&5&0&1&&3&4}\\
\matrix{2&3&4&5&0&1&2&3&&5}\\
\matrix{3&4&5&0&1&2&3&4&5&}\\
$$
The three sports that each team is missing are the ones that would have been on the diagonal and in the two columns you'd get if you'd extend the table to the right. With the diagonal in the first column and the two extension columns in the second and third column, this is:
$$
\matrix{
0&4&5\\
2&5&0\\
4&0&1\\
0&1&2\\
2&2&3\\
4&3&4\\
0&4&5\\
2&5&0\\
4&0&1\\
0&1&2
}
$$
Now let each team $i$ for $0\le i\le8$ play team $i+1$ in sport $i+5\,\%\,6$. That takes care of the second and third columns, except for the game in sport $4$ for team $0$ and the game in sport $2$ for team $9$. These two games together with the ten missing games from the diagonal in the first column are four games each in the sports $0$, $2$ and $4$, and you can form two pairs for each of these sports in whatever way you like because none of the possible pairs have played a second game yet.

A: I've spent a good deal of time on this, and I haven't been able to do it,  so in one sense, this isn't an answer at all, more of a progress report.   On the other hand, someone may be able to suggest a modification to the method that will allow for solution.  I tried it with both $10$ teams and $12$ teams, without success.  I don't even have a viable approach in mind for an odd number of teams.
With $10$ teams each playing $12$ games, we will have $60$ matches.  I determined a possible set of $60$ where each team played $9$ teams once and $3$ teams twice, and no two matches were identical.  I then computed all possible rounds of $5$ matches chosen from among these $60,$ where a legitimate round includes all teams, and no game is played twice.  With $10$ players, there were $172$ such rounds.  Then I tried to choose $12$ rounds from among these $172$ that would partition the $60$ matches, but that was impossible.  The result for $12$ teams was similar.
My program uses Knuth's dancing links algorithm for (generalized) set exact cover problems, so it's not apparent how to come up with some kind of approximate solution.
I've been wondering about trying different sets of $60$ matches, but there are so many isomorphisms!  The program runs in a second or so, so trying lots of sets of matches isn't a concern, but of course, I'd like to generate non-isomorphic sets, if possible.  At the moment, I don't see any quick way even to tell if two sets are isomorphic.  (By isomorphic, I mean that one set of matches can be obtained from the other by permutation of the sports and of the teams.)  I would welcome any suggestions about the isomorphism problem.
Failing this, there may be some acceptable relaxation of the conditions.
One thing that occurs to me is to go for as many full rounds as possible, and then hope that there aren't too many conflicts at the end.  For example, suppose we could go for $11$ rounds, but not $12$.  If the last $5$ games were all pool, that would be a problem, but if two were pool and the remaining ones were different games, that wouldn't be so bad.  I'd like to know the OP's opinion of this approach.
EDIT
I modified the program to keep track of the maximum number of compatible rounds, and it was only $5$.  Very discouraging.  It is, however, possible to do this for an $8-$team tournament.
Round 1
   T0 vs T2 at table tennis
   T3 vs T6 at beer pong
   T1 vs T4 at darts
   T7 vs T5 at cornhole
Round 2
   T0 vs T1 at beer pong
   T4 vs T2 at table tennis
   T6 vs T7 at pool
   T5 vs T3 at foosball
Round 3
   T0 vs T4 at foosball
   T7 vs T3 at darts
   T2 vs T5 at beer pong
   T1 vs T6 at cornhole
Round 4
   T0 vs T3 at table tennis
   T7 vs T5 at darts
   T4 vs T2 at pool
   T1 vs T6 at beer pong
Round 5
   T0 vs T4 at pool
   T5 vs T6 at table tennis
   T1 vs T2 at darts
   T7 vs T3 at foosball
Round 6
   T0 vs T6 at darts
   T2 vs T7 at beer pong
   T1 vs T4 at cornhole
   T5 vs T3 at pool
Round 7
   T0 vs T6 at cornhole
   T4 vs T7 at table tennis
   T2 vs T3 at darts
   T5 vs T1 at pool
Round 8
   T0 vs T5 at foosball
   T7 vs T1 at pool
   T6 vs T4 at darts
   T2 vs T3 at cornhole
Round 9
   T0 vs T3 at pool
   T6 vs T7 at table tennis
   T4 vs T5 at beer pong
   T1 vs T2 at foosball
Round 10
   T0 vs T7 at beer pong
   T3 vs T1 at table tennis
   T2 vs T5 at cornhole
   T6 vs T4 at foosball
Round 11
   T0 vs T7 at cornhole
   T3 vs T4 at beer pong
   T6 vs T2 at foosball
   T5 vs T1 at table tennis
Round 12
   T0 vs T5 at darts
   T3 vs T4 at cornhole
   T6 vs T2 at pool
   T7 vs T1 at foosball

Here each team plays $5$ teams twice and $2$ teams once.