text:
Q: How can you use a trait's associated type for const generics and the length of arrays? I have a situation that would ideally be structured as following:
pub struct ConstraintProperties<const COUNT: usize> {
    particles: [ParticleReference; COUNT],
}

pub trait Constraint {
    fn project(&self, particle_source: &mut [Particle], dt: f64, static_pass: bool);
}

pub trait ConstraintData {
    const COUNT: usize;
    fn properties(&self) -> ConstraintProperties<{ Self::COUNT }>;
    fn constraint(&self, particles: [&Particle; { Self::COUNT }]) -> f64;
    fn gradients(&self, particles: [&Particle; { Self::COUNT }]) -> [Vec3; { Self::COUNT }];
}

impl<C: ConstraintData> Constraint for C {
    fn project(&self, particle_source: &mut [Particle], dt: f64, static_pass: bool) {
        ...
    }
}

However, I am running into the following error: "type parameters may not be used in const expressions."
How can I get around this so that I can use the associated constant of the trait to govern the const generic and the lengths of arrays that the trait's functions take?

A: On nightly, you can use #![feature(generic_const_exprs)]:
#![feature(generic_const_exprs)]

pub trait ConstraintData {
    const COUNT: usize;
    fn properties(&self) -> ConstraintProperties<{ Self::COUNT }>;
    fn constraint(&self, particles: [&Particle; Self::COUNT]) -> f64;
    fn gradients(&self, particles: [&Particle; Self::COUNT]) -> [Vec3; Self::COUNT];
}

But note that this feature is highly experimental and not recommended in production.


text:
Q: Describing Cosets in $R/A$ In a worked example in my textbook, we are describing the cosets in $R/A$, where $R=\mathbb{Z}[i]$, the Gaussian integers, and $A = (2+i)R$, the ideal of all multiples of $2 + i$.
It starts by stating that a typical coset $x$ in $R/A$ will have the form $x=(m + ni) + A$, with integers $m,n$. This makes sense to me, but I do not understand the following part:

"Since $2 + i \in A$, we have $i + A = -2 + A$"

Can someone walk me through how we arrive at $i+A = -2+A$?

A: Well, as you have said, an element in $R/A$ looks like $(m+ni) + A$. So $2+i \in A$ means $2+i +A = A$ (this is an equality of elements in $R/A$). So $(2+i)+A - (2+A) = A - (2+A)$, giving $i+A = -2+A$. (If you are unsure how to get the last equality, think about what addition (and hence subtraction) means in $R/A$.)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using a CASE statement in a WHERE clause in SQL Server I am trying to create query form on a website.  First object is a dropdown list with operators. Default first value in the dropdown list is NULL(1), second value is LIKE(2), etc...  Second object is a textbox where the user can enter a string like "A".
Therefore, I am trying to build the below SQL query to simulate the variables coming from the website.  It runs and returns all values when the @op = 1.  But I keep getting the following error when I change @op = 2:

Conversion failed when converting the nvarchar value 'Tom LIKE A%' to data type int."

DECLARE @StartDate DATETIME2(7) = '2017-11-08 00:00:00.0000000 +00:00'
DECLARE @EndDate DATETIME2(7) = '2017-11-08 00:00:00.0000000 +00:00'
DECLARE @Op INT = 2
DECLARE @name NVARCHAR(25) = 'A'
SELECT
    name,
    dttm
FROM
    tableName
WHERE
    dttm BETWEEN @StartDate AND @EndDate
    AND CASE @Op
        WHEN 1 THEN 1
        WHEN 2 THEN name + ' LIKE ' + @name +'%'
        END <> 0

A: Don't use case.  Just use regular boolean logic:
WHERE dttm BETWEEN @StartDate AND @EndDate AND
      ( (@op = 1) OR
        (@op = 2 AND name LIKE @name + '%')
      )

Your specific issue involves constructing a LIKE comparison in a string.  However, the above appears to be what you want to do.


text:
Q: Invalid SSL certificate on localhost (MAMP) only on Nginx I created a self-signed certificate with MAMP and set the trust level to "always trust" in my keychain. That works well for a local Wordpress site that is running on an Apache server. The other (a Wordpress multisite – maybe an issue, too?) is running on Nginx. That certificate, although created the same way, throws an error. In Chrome:
NET::ERR_CERT_AUTHORITY_INVALID
When I click on the certificate in the browser, it shows a default certificate – not the one I created:
certificate shown after click on SSL infos in browser
The default one cannot be set to trusted.


text:
Q: State not resetting. Why is it running concurrently when reset is pressed? I am learning react. When I click the reset timer button, instead of resetting the timer, a new second timer starts running concurrently. If I click the same button the third time, a new third timer starts at zero also running concurrently.
The same is happening when I click another button that says Jump 10 seconds. It's like its creating a new state instead of resetting the state.
Here is my app.jss code
function App() {

  const [timeSpent, setTimeSpent] = useState(0);

  setTimeout(() => setTimeSpent(timeSpent + 1),
    1000
  )

  //Reset the timer
  const resetTimer = () => setTimeSpent(0);

  return (
    <>

      <Timer secondsPassed={timeSpent} />

      <button onClick={resetTimer}>Reset Timer</button>
      <button onClick={() => setTimeSpent(timeSpent +10)}>Jump 10 Seconds</button>
    </>
  );
}

export default App;

Here is my Timer.js code
function Timer({secondsPassed}) {

    const formatting = () => {
        if (secondsPassed < 60) {
            return secondsPassed + ' Sec';
        } else {
            return Math.floor(secondsPassed/60) + ' Mins';
        }
    }

    return (

Time Spent: {formatting()}

    )
}

A: Based on @Emile Bergeron comment, you should use setInterval inside a useEffect and for updating the state you should get the latest timeSpent which has been passed into the callback function that I passed to setTimeSpent.

 const {useState, useEffect} = React;

function App() {
  const [timeSpent, setTimeSpent] = useState(0);
  useEffect(() => {
    setInterval(() => setTimeSpent((time) => time + 1), 1000);
  }, []);

  //Reset the timer
  const resetTimer = () => setTimeSpent(0);

  return (

      <Timer secondsPassed={timeSpent} />

      <button onClick={resetTimer}>Reset Timer</button>
      <button onClick={() => setTimeSpent(timeSpent + 10)}>
        Jump 10 Seconds
      </button>

  );
}

function Timer({ secondsPassed }) {
  const formatting = () => {
    if (secondsPassed < 60) {
      return secondsPassed + " Sec";
    } else {
      return Math.floor(secondsPassed / 60) + " Mins";
    }
  };

  return (

Time Spent: {formatting()}

  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(
    <App />,
  rootElement
);


text:
Q: easy functions on data in a dataframe My example df:
a = c(2,2,4)
b = c(3,4,5)
c = c(3,5,7)
d = c(3,5,8)
df = data.frame(a, b, c, d)

I want to normalize col b-d by dividing it through column a.
Like this (for the specific example of col b)
df$b <- df$b / df$a

But I have so many columns in reality. So I want to use some loop.
Something like this:
for (x in df[c(2:4)]){
  df$x <- df$x / df$a
}

Do I need an apply function here? Or am I missing some comma or bracket?

A: Here is an option using data.table.  Convert the 'data.frame' to 'data.table' (setDT(df)), specify the columns in .SDcols, divide the Subset of Data.table (.SD) by the 'a' column and assign (:=) to columns of interest
library(data.table)
setDT(df)[, (2:4) := .SD/a,.SDcols = 2:4]
df
#   a    b    c   d
#1: 2 1.50 1.50 1.5
#2: 2 2.00 2.50 2.5
#3: 4 1.25 1.75 2.0


text:
Q: NodeJS: Get Current VM Context Node JS executes the codebase in the Javascript VX (V8 currently) engine, and executes every asynchronous context in its own VM.
Given this information, is there an API that allows to find in which VM context the current code execution is taking place?
I am attempting to create context-specific globals.
Is this possible?
Is my understanding of Node correct?

A: Your understanding of node is incorrect. Specifically you said:

Javascript VX (V8 currently) engine, and executes every asynchronous context in its own VM

No. Javascript has only one context. The current VM. There are multithreading extensions in node.js such as webworker-threads but they're not often used because:

*

*They rarely improve throughput and almost always increase latency

*They're almost never necessary because almost nothing in node.js blocks

If you want a slightly more low-level technical detail of how asynchronous execution work in node.js see my answer to this question: I know that callback function runs asynchronously, but why?

A: Context specific globals?  Isn't that a contradiction?
Javascript uses closures.  So you want to declare and create functions within functions and this will establish and preserve your concept of "context specific globals".


text:
Q: Deeply nested data objects in multidimensional object I have a multidimensional object and using Vue, I am trying to make the inner object reactive.
My object looks like this:
data() {
   return {
       myObject: {}
   }
}

And the filled data looks like this:
myObject: {
   1: {         // (client)
     0: "X",    // (index) : (value)
     1: "Y"
   },
   2: {
     0: "A",
     2: "B"
   }
}

If I try using:
let value = "X";
let client = 1;
let index = 1;

let obj = {};
obj[client][index] = value;
this.myObject = Object.assign({}, this.myObject, obj);

It throws an error:

TypeError: Cannot set property '0' of undefined

And if I try below, it overwrites the initial values as it is initially setting the object to {}
let obj = {};
obj[index] = value;
let parentObj = {};
parentObj[client] = obj;
this.myObject = Object.assign({}, this.myObject, parentObj);

What is the proper way of adding the values to the multidimensional object?

A: In javascript, dim2Thing[1][1] = ... expressions require dim2Thing[1] to exist. This is why you get the error you mentioned. So you can do two expressions, which should work fine:
dim2Thing[1] = dim2Thing[1] || {}
dim2Thing[1][1] = otherThing
For the last block, you mention that it "overwrites the initial values"
I think what's actually happening here is just that Object.assign is not recursive. It only merges top-level keys. So if parentObj has a key that over-laps with this.myObj, then sub-keys will be lost.
Object.assign({ a: { b: 2} }, { a: { c: 3 } }) // returns { a: { c: 3 }  }

This is what I interpret your code as trying to do - though I am unfamiliar with vue.js at this time, so I cannot assure it will have the desired result to your webpage:
let value = "X";
let client = 1;
let index = 1;

const newObj = Object.assign({}, this.myObject);
// if you have lodash _.set is handy
newObj[client] = newObj[client] || {}; // whatever was there, or a new object
newObj[client][index] = value
this.myObject = newObj

A: Just use an array, thats reactive by design.
If you need to get elements from the array in your template or anywhere just add a find method
// temp
late

{{find(obj => obj.id === idx)}}

methods: {
  find (searchFunction) {
    return this.myArray.find(searchFunction)
  }
}


text:
Q: Repositorio devuelve lectura nulo y genera un error en clase que recibe - Sprint Boot Hice una consulta con JPA que dependiendo de los datos devuelve un valor nulo. Trato de obtener una diferencia de fechas en minutos y construí una clase para para captar el resultado. Realice pruebas visualizando los resultados por debug y la segunda interacción no encontró datos y por consiguiente la clase "Conteo" quedo con nulo y lógicamente me manda un error. Cómo hago para resolver esto?
Mi clase que debe obtener el resultado
public class Conteo {

    private int conteo = 0;

    public Conteo(int conteo) {
        this.conteo = conteo;
    }

    public Conteo() {
        this.conteo = 0;
    }

    public int getConteo() {
        return conteo;
    }

    public void setConteo(int conteo) {
        this.conteo = conteo;
    }
}

El repositorio
public interface TransaccionRepository extends CrudRepository<Transaccion, Long> {

      @Query("SELECT new com.innova507.tempuswebserver.dao.Conteo(MINUTE(max(m.fechaTiempoGps)) -  MINUTE(min(m.fechaTiempoGps))) FROM Transaccion m WHERE m.usuario.usuarioId = ?1 AND m.fechaTiempoGps >= ?2 AND (m.velocidad >= ?3 AND m.velocidad <= ?4)")
      Conteo findByUsuarioFechaVelocidadConteo(Long usuarioId, Date fecha, float v1, float v2);

}

El método que lo llama
    public boolean detectoAlarma(Long usuarioId, int d, Date dt, float v1, float v2) {
        boolean r = false;
        Conteo c  = transaccion.findByUsuarioFechaVelocidadConteo(usuarioId, dt, v1, v2);
        if (c != null) {
            if (c.getConteo() >= d) {
                r = true;
            }
        }
        return r;
    }

Importante: Al ejecutar transaccion.findByUsuarioFechaVelocidadConteo(usuarioId, dt, v1, v2); se genera el error.
El error

org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.QueryException: could not instantiate class [com.innova507.tempuswebserver.dao.Conteo] from tuple; nested exception is java.lang.IllegalArgumentException: org.hibernate.QueryException: could not instantiate class [com.innova507.tempuswebserver.dao.Conteo] from tuple
    at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:384) ~[spring-orm-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:246) ~[spring-orm-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:488) ~[spring-orm-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59) ~[spring-tx-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213) ~[spring-tx-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147) ~[spring-tx-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133) ~[spring-data-jpa-1.11.7.RELEASE.jar:na]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) ~[spring-aop-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57) ~[spring-data-commons-1.13.7.RELEASE.jar:na]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) ~[spring-aop-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at com.sun.proxy.$Proxy111.findByUsuarioFechaVelocidadConteo(Unknown Source) ~[na:na]
    at com.innova507.tempuswebserver.api.LocalizacionService.detectoAlarma(LocalizacionService.java:86) ~[classes/:na]
    at com.innova507.tempuswebserver.api.LocalizacionService$$FastClassBySpringCGLIB$$fbceb2fe.invoke(<generated>) ~[classes/:na]
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:669) ~[spring-aop-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at com.innova507.tempuswebserver.api.LocalizacionService$$EnhancerBySpringCGLIB$$84ea5ce4.detectoAlarma(<generated>) ~[classes/:na]
    at com.innova507.tempuswebserver.websocket.TempusHandler.lambda$0(TempusHandler.java:86) ~[classes/:na]
    at java.util.ArrayList.forEach(Unknown Source) ~[na:1.8.0_281]
    at com.innova507.tempuswebserver.websocket.TempusHandler.localizacionUsuarioTransaccion(TempusHandler.java:82) ~[classes/:na]
    at com.innova507.tempuswebserver.websocket.TempusHandler.handleBinaryMessage(TempusHandler.java:52) ~[classes/:na]
    at org.springframework.web.socket.handler.AbstractWebSocketHandler.handleMessage(AbstractWebSocketHandler.java:46) ~[spring-websocket-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.web.socket.handler.WebSocketHandlerDecorator.handleMessage(WebSocketHandlerDecorator.java:75) ~[spring-websocket-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.web.socket.handler.LoggingWebSocketHandlerDecorator.handleMessage(LoggingWebSocketHandlerDecorator.java:56) ~[spring-websocket-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.web.socket.handler.ExceptionWebSocketHandlerDecorator.handleMessage(ExceptionWebSocketHandlerDecorator.java:58) ~[spring-websocket-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter.handleBinaryMessage(StandardWebSocketHandlerAdapter.java:120) [spring-websocket-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter.access$100(StandardWebSocketHandlerAdapter.java:42) [spring-websocket-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter$4.onMessage(StandardWebSocketHandlerAdapter.java:87) [spring-websocket-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter$4.onMessage(StandardWebSocketHandlerAdapter.java:84) [spring-websocket-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.apache.tomcat.websocket.WsFrameBase.sendMessageBinary(WsFrameBase.java:582) [tomcat-embed-websocket-8.5.20.jar:8.5.20]
    at org.apache.tomcat.websocket.server.WsFrameServer.sendMessageBinary(WsFrameServer.java:131) [tomcat-embed-websocket-8.5.20.jar:8.5.20]
    at org.apache.tomcat.websocket.WsFrameBase.processDataBinary(WsFrameBase.java:541) [tomcat-embed-websocket-8.5.20.jar:8.5.20]
    at org.apache.tomcat.websocket.WsFrameBase.processData(WsFrameBase.java:300) [tomcat-embed-websocket-8.5.20.jar:8.5.20]
    at org.apache.tomcat.websocket.WsFrameBase.processInputBuffer(WsFrameBase.java:133) [tomcat-embed-websocket-8.5.20.jar:8.5.20]
    at org.apache.tomcat.websocket.server.WsFrameServer.onDataAvailable(WsFrameServer.java:82) [tomcat-embed-websocket-8.5.20.jar:8.5.20]
    at org.apache.tomcat.websocket.server.WsFrameServer.doOnDataAvailable(WsFrameServer.java:171) [tomcat-embed-websocket-8.5.20.jar:8.5.20]
    at org.apache.tomcat.websocket.server.WsFrameServer.notifyDataAvailable(WsFrameServer.java:151) [tomcat-embed-websocket-8.5.20.jar:8.5.20]
    at org.apache.tomcat.websocket.server.WsHttpUpgradeHandler.upgradeDispatch(WsHttpUpgradeHandler.java:148) [tomcat-embed-websocket-8.5.20.jar:8.5.20]
    at org.apache.coyote.http11.upgrade.UpgradeProcessorInternal.dispatch(UpgradeProcessorInternal.java:54) [tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:53) [tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1457) [tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.20.jar:8.5.20]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_281]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_281]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.20.jar:8.5.20]
    at java.lang.Thread.run(Unknown Source) [na:1.8.0_281]
Caused by: java.lang.IllegalArgumentException: org.hibernate.QueryException: could not instantiate class [com.innova507.tempuswebserver.dao.Conteo] from tuple
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1679) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1602) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.internal.QueryImpl.getSingleResult(QueryImpl.java:560) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_281]
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_281]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_281]
    at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_281]
    at org.springframework.orm.jpa.SharedEntityManagerCreator$DeferredQueryInvocationHandler.invoke(SharedEntityManagerCreator.java:372) ~[spring-orm-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at com.sun.proxy.$Proxy145.getSingleResult(Unknown Source) ~[na:na]
    at org.springframework.data.jpa.repository.query.JpaQueryExecution$SingleEntityExecution.doExecute(JpaQueryExecution.java:206) ~[spring-data-jpa-1.11.7.RELEASE.jar:na]
    at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:85) ~[spring-data-jpa-1.11.7.RELEASE.jar:na]
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:116) ~[spring-data-jpa-1.11.7.RELEASE.jar:na]
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:106) ~[spring-data-jpa-1.11.7.RELEASE.jar:na]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:483) ~[spring-data-commons-1.13.7.RELEASE.jar:na]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461) ~[spring-data-commons-1.13.7.RELEASE.jar:na]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:56) ~[spring-data-commons-1.13.7.RELEASE.jar:na]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) ~[spring-tx-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282) ~[spring-tx-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) ~[spring-tx-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    ... 44 common frames omitted
Caused by: org.hibernate.QueryException: could not instantiate class [com.innova507.tempuswebserver.dao.Conteo] from tuple
    at org.hibernate.transform.AliasToBeanConstructorResultTransformer.transformTuple(AliasToBeanConstructorResultTransformer.java:41) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.hql.internal.HolderInstantiator.instantiate(HolderInstantiator.java:75) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.loader.hql.QueryLoader.getResultList(QueryLoader.java:469) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2429) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.loader.Loader.list(Loader.java:2424) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:501) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:371) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:216) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1326) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.internal.QueryImpl.list(QueryImpl.java:87) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.internal.QueryImpl.list(QueryImpl.java:606) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.internal.QueryImpl.getSingleResult(QueryImpl.java:529) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    ... 64 common frames omitted
Caused by: java.lang.IllegalArgumentException: null
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_281]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) ~[na:1.8.0_281]
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) ~[na:1.8.0_281]
    at java.lang.reflect.Constructor.newInstance(Unknown Source) ~[na:1.8.0_281]
    at org.hibernate.transform.AliasToBeanConstructorResultTransformer.transformTuple(AliasToBeanConstructorResultTransformer.java:37) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    ... 75 common frames omitted

A: Intenta modificando lo siguiente:
@Query("SELECT new com.innova507.tempuswebserver.dao.Conteo(MINUTE(max(m.fechaTiempoGps)) -  MINUTE(min(m.fechaTiempoGps))) FROM Transaccion m WHERE m.usuario.usuarioId = :usuarioId AND m.fechaTiempoGps >= :fecha AND (m.velocidad >= :v1 AND m.velocidad <= :v2)")
Conteo findByUsuarioFechaVelocidadConteo(Long usuarioId, Date fecha, float v1, float v2);

Te recomiendo que te fijes en los tipos de datos que están en tu tabla vs lo que les estas pasando a nivel de código, estos deben ser equivalentes, ejemplo: varchar == String.
Saludos


text:
Q: @synthesize syntax when overriding accessors I am doing a value object / Entity, that holds data for my model.
I get the data from a web service as JSON, now, instead of moving all the different objects from the parsed JSON over into different properties on my Entity. i.e. reading out the NSString for the @"name" key and setting it to [Entity setName:[JSONDictionary objectForKey:@"name"] etc. My Entity has one actual property,
NSDictionary *dataDictionary, this property hold the JSON dictionary as it left the parser.
Now when I need the name value I write an accessor that looks like this:
- (NSString*) name {
    return [self.dataDictionary objectForKey:@"name"];
}

This is nice, I don't have to do any work unless there is a request for that particular property.
Now my question is how do I best tell the compiler that the accessor exists, but does not hold a "real" property.
I have this in my interface:
@property(nonatomic, retain) NSString *name;

And the @synthesize in my implementation, but this seems to create an overhead in my logic. Objective C will, as far as I understand, make a room in memory for me to store an object of type NSString when I do the @property(nonatomic, retain) and technically I don't need this as I am already storing this value in the the NSDictionary *dataDictionary
If I make it @dynamic I guess I would also have to provide a setter, which I would never need.
So, Is there a syntax that lets me create the illusion to all objects accessing the Entity that these are "normal" properties, but internally in the Entity not alloc/store unnecessary objects or write more code than is needed?

A: Declare a name method in your interface, not a property.
- (void)name;


text:
Q: Entity Framework - tracking changes on non-virtual property I'm writing because currently I'm trying to implement object change tracking on a sample class. I got into using proxies and this approach fits my needs.
Definition of a class where methods and properties are defined as virtual, afterwards proxy creation suits me.
But apart from that, I am really curious how Entity Framework (with a code-first approach) manages to track changes on an object where property is NOT defined as virtual.
I do understand that creation a proxy (without defining an interface; ef does not require that) is not possible. So how does EF track changes? If I am right and creation of a proxy is not possible, so how does it work?
Does it compare object state to the database on save action, or get changes?
Thanks for your replies!

A: After the object is in the context there are 2 copies of the state. It's used also for optimistic concurrency.
EDIT
It means, that Entity compares the object which I modified to its copy like property by property.


text:
Q: PyroCMS - Loading a custom library in a module I'm writing a PyroCMS module which involves image upload and thumbnail generation. I'm aware codeigniter has a built in image manipulation class that's capable of making thumbnails, but I'm a big for of phpThumb'ss adaptive resize function. For this reason I'd like to try and get phpThumb working.
I've placed the phpThumb files in ./addons/shared_addons/modules/mymodule/libraries
and I'm trying to load using the following:
$this->load->library('phpThumb/ThumbLib.inc.php');

I'm including the extension because an .inc.php file is not a .php file right? Either way if I keep the extension or not I get this error:
Class 'ThumbLib.inc.php' not found in .../htdocs/system/cms/libraries/MX/Loader.php on line 160

Anyone know what I'm doing wrong?
Thanks, Ed.

A: The loader naming conventions are probably stricter, so you may need to rename your file to something like 'Thumblib.php' and then declare your class as so class Thumblib {. You may also need to check the library doesn't conflict with anything as is suitable to use in CI.
Also, I think as long as you are loading the library from a controller in the same module folder tree as the library, the load line should be something like:
$this->load->library('Thumblib');

Or if not:
$this->load->library('othermodule/Thumblib');

Good luck.

A: This is a CodeIgniter question, not a PyroCMS question.
Simple solution:
 include 'whatever/the/hell/you.like.php';

Remember guys it's just PHP. You don't need a special method for everything!


text:
Q: Rendering two div in a div horizantally I have a parent div having two child divs which are in horizantal ,Now I want to add  other div such that the pagination should come.
Here is the code.

Here, If i add other div to 'parent',It will append at last,but should not be shown and pagination should come.
Using floats, I am making the div's horizantal.I have to show only two div's,After that pagination should come.

A: This is just a DEMO:
HTML:

window 1

window 2

PreviousNext

CSS:
#parent {
    width: 850px;
    overflow: hidden;
    padding: 10px;
    height: 320px;
    border: 1px solid #f00
}
#wrapper div {
    width: 400px;
    border: 1px solid #ccc;
    height: 300px;
    display:inline-block;
    margin: 10px
}
#paginator {
    margin: 10px;
    display: block
}
#paginator span {
    width: 30px;
    padding: 5px;
    margin: 10px;
    background: #1f1f1f;
    color: #fff;
}

JQUERY:
$(function() {
    $('#next').click(function() {
        $('#wrapper').append($('
window 3

window 4
')); // you can add div using other way
        $('#wrapper').animate({
            marginLeft: '-=860px'
        },
        500, 'linear');
    });
    $('#prev').click(function() {
        $('#wrapper').animate({
            marginLeft: '+=860px'
        },
        500, 'linear');
    });
});

A: Not sure I understand your question, but I'll give it a shot...

... is this what you mean to do?


text:
Q: Python Linear Programming I am trying to solve the following equation:
maximize x^{T}Ax   where x is a 3 X 1 vector of the variables to be maximized and A is a 3 X 3 matrix of values.
So basically x^{T} = [a,b,c] which are the unknowns to be maximized and A could be something like
A = [ [29, 29, 79],
      [28, 28, 48],
      [9, 40, 0 ]]
Could someone show me how to represent this in the form of a maximization problem using PuLP or some other linear programming package in python?
Any help would be much appreciated. I am extremely new to this area and have not idea how to get started representing this formulation.
I have so far tried to use CVXPY to model this function.
I have the following code but am seeing an error:
    [1] A = np.array([[29,29,79],[28,28,48],[9,40,0]])
    [2] x=Variable(3)
    [3] objective=Minimize(x.T*A*x)
     Warning: Forming a nonconvex expression (affine)*(affine).
  warnings.warn("Forming a nonconvex expression (affine)*(affine).")
    [4] constraints=[0<=x,x<=1,sum_entries(x)==1] #what I'm trying to say is each entry of x should be between 0 and 1 and all entries should add up to 1.
    [5] prob = Problem(objective, constraints)
    [6] prob.solve()
    DCPError: Problem does not follow DCP rules.

A: I don't believe PuLP supports quadratic programming (QP). Your model is quadratic and PuLP is only for linear programming models (LPs and MIPs). There are quite a few options to express QPs in Python. High performance commercial solvers often provide Python bindings, and otherwise you can look at for example CVXOPT. Notice that only convex QPs are "easy" to solve. If you have a non-convex QP things become much more difficult and you may need to look at a global solver (there not as many of those type of solvers). Non-convex QPs can be reformulated via the KKT conditions as a linear MIP model, although these models may not always perform very well.


text:
Q: How to I prevent widgets in a QGridLayout from overlapping? I have a QGridLayout that has a number of widgets in six rows.  Rows 1, 3 and 5 contain a QLabel, a QLineEdit and a QPushButton that opens up a file selection dialog.  Rows 2, 4, and 6 contain a QLabel that is used to present validation errors to the user.  The errors are hidden in the image below.
When the window is able to take up as much space as it likes, this issue does not appear.  But when I restrict the size of the window at all, the elements in this list look like this:

So my question is, how do I ensure that all qwidgets in the QGridLayout can take up as much space as they need?
EDIT:
Following @Avaris' suggestion, I tried calling setMinimumSize() for each widget in the QGridLayout (all 6 rows), and the visible elements look much better (thanks, @Avaris!).  Yet now when I cause a validation error, the error itself (a red QLabel) is laid over the other widgets.  Can I force the QGridLayout to not overlap?
Here's what it looks like now:

A: While searching around for a solution, I found something in the TrollTech archives that supported @Avaris's idea about setting the minimum size of the widget.  The post suggests setting a minimum size for each widget in the QGridLayout.
My implementation looks like this as I loop through all elements to be added to my QGridLayout:
widget = QtGui.QWidget()
hint = widget.sizeHint()
if hint.isValid():
    widget.setMinimumSize(hint)

The validity of a hint varies on the layout used, but widget sizehints always seem to be valid when I use a QGridLayout.


text:
Q: Issue loading clr assembly into sql server that uses system.text.json Have a clr assembly that references System.Text.Json (.net 4.8 with SQL Server 14), when I try to load it into SQL Server (CREATE ASSEMBLY) I get:

Assembly 'my assembly' references assembly 'system.text.json, version=4.0.1.0, culture=neutral, publickeytoken=cc7b13ffcd2ddd51.', which is not present in the current database. SQL Server attempted to locate and automatically load the referenced assembly from the same location where referring assembly came from, but that operation has failed (reason: 2(The system cannot find the file specified.)). Please load the referenced assembly into the current database and retry your request.

Updated the server with the latest .net, obviously loading the entire .net framework into sql server isn't a good idea :)

A: The error is due to system.text.json not being in the list of Supported .NET Framework Libraries.
You will have to load that DLL manually via CREATE ASSEMBLY (it will load dependent assemblies automatically) as UNSAFE. However, if that assembly is not available in .NET Framework, then I'm not sure you will be able to load it (or, even if it is available in .NET Framework but is a mixed-mode assembly -- i.e. contains unmanaged code).

A: Yep.  I tried loading the assembly but it pulled me into the rabbit hole of .net's version of DLL h*ll where this was dependent on that, which was dependent on that...
One would THINK System.Text.Json is the Microsoft replacement for Newtonsoft, apparently not quite yet.
Thanks for the answers.


text:
Q: Node js when is good time to use Buffer I am learning nodejs and come cross the buffer Class. looks like it's a raw memory allocation outside the V8 heap. Wondering when it's a good situation to use buffer rather than use transitional string or array. is it purely for the sake of performance to use buffer?
http://www.tutorialspoint.com/nodejs/nodejs_buffers.htm

A: More or less, yes. Buffer is very low-level since it abstracts node::Buffer. You use it for reading binary data and can also treat it as typed, which is very efficient. Whereas arrays might coerce. Those things are what JS naturally is quite bad at and therefore v8 doesn't seem to be the best place to do them.
Maybe it's rather Buffer vs. streams:
Buffers API is more straightforward and less verbose. It takes some time to setup streams properly. Also it's control flow is easier when you want to do just sequential stuff for low and mid sized data.


text:
Q: Libxml2 usage -- total novice I am new to using the libxml2, in fact this will be my very first time. I've been looking to find some sample code that could point me in the correct direction but so far I've been absolutely unsuccessful. I am attempting to use the following XPath statement:
"$XTX//DeptName[ . = $Dn ]"
However, I cannot figure out how to produce and evaluate a query with variables ($XTX and $Dn). I cannot figure out how to add the variable substitution to the code. I assume I will need the xmlXPathRegisterVariable API but as I said I simply cannot figure out how to do that. Can anyone either provide me or point me to some sample code that I can use to get this working?
        if ( 0 != iXmlArrDim ) {
        Assert( XMLOID == ARR_ELEMENTS( pXmlDataArr ) );

        deconstruct_array( pXmlDataArr,
                           XMLOID,
                           -1,
                           false,
                           'i',
                           &pXmlData,
                           &pXmlDataNulls,
                           (int32_t*)&iXmlCount );

        /**
         */
        xmltype  *pX    = NULL;
        char     *pData = "<\\>";
        uint32_t  iData = sizeof( "<\\>" ) - 1;

        if ( !pXmlDataNulls[0] ) {
            pX    = DatumGetXmlP( pXmlData[0] );
            pData = VARDATA( pX );
            iData = VARSIZE( pX ) - VARHDRSZ;

            pDoc = xmlCtxtReadMemory( pCtx, pData, iData, NULL, NULL, 0 );

            if ( NULL == pDoc )
                ereport( ERROR,
                         ( errcode( ERRCODE_INVALID_XML_DOCUMENT ),
                           errmsg( "Could not parse the XML document" ) ) );

            pXPathCtx = xmlXPathNewContext( pDoc );

            if ( NULL == pXPathCtx )
                ereport( ERROR,
                         ( errcode( ERRCODE_OUT_OF_MEMORY ),
                           errmsg( "Could not allocate XPath context" ) ) );

            pXPathCtx->node = (xmlNodePtr)pDoc;

            pXPathObj = xmlXPathEval( pXPathStr, pXPathCtx );
            //pXPathObj = xmlXPathEvalExpression( pXPathStr, pXPathCtx );

            /**
             * Add any additional XML items or variables.
             */
            for ( size_t ix = 1; ix < ( iXmlCount >> 1 ); ++ix ) {
                int                rc        = 0;
                xmlXPathObjectPtr  pXPathObj = NULL;
                const char        *pAlias    = NULL;

                pX    = DatumGetXmlP( pXmlData[ix * 2] );
                pData = VARDATA( pX );
                iData = VARSIZE( pX ) - VARHDRSZ;

                /**
                 * Add the alias as a variable if one was specified.
                 */
                if ( !pXmlDataNulls[( ix * 2 ) + 1] ) {
                    pAlias = TextDatumGetCString( pXmlData[ix * 2] );

                    rc = xmlXPathRegisterVariable( pXPathCtx,
                                                   BAD_CAST pAlias,
                                                   xmlXPathObjectCopy( pXPathObj ) );

                    if ( rc == -1 )
                        ereport( WARNING,
                                 ( errcode( ERRCODE_INTERNAL_ERROR ),
                                 errmsg( "Could not create an XPath object" ) ) );
                }
            }
        }
    }

Regards,
Garfield

A: ok, so after a lot of debugging I've figured it out. Basically, the following change to my code now allows me to set the variable as expected:
                    pAlias = TextDatumGetCString( pXmlData[( ix * 2 ) + 1] );
                    pValue = xmlXPathNewString( BAD_CAST pData );
                    rc     = xmlXPathRegisterVariable( pXPathCtx,
                                                       BAD_CAST pAlias,
                                                       pValue );

                    if ( rc == -1 )
                        ereport( WARNING,
                                 ( errcode( ERRCODE_INTERNAL_ERROR ),
                                   errmsg( "Could not create an XPath object" ) ) );

Subsequent to this, the xmlXPathEval is moved below the for loop to register the variables.


text:
Q: Function Literal vs Function Expression in Javascript Are function literals and function expressions the same thing, or is there a difference?

A: As answered on topic Exact meaning of Function literal in JavaScript: "A function literal is just an expression that defines an unnamed function."
Description of "function expression" on MDN about function name says, that it "Can be omitted, in which case the function is anonymous.". (unnamed function === anonymous function)
Another example of anonymous function notation is "arrow function expression" in ES6
var func = (x, y) => { return x + y; };

This does the same thing as:
var func = function (x, y) { return x + y; };

and (almost) the same thing as:
function func(x, y) { return x + y; };

For more in-deph explanation read: Difference between "anonymous function" and "function literal" in JavaScript

TL;DR:
Function Literal is kind of function expression.


text:
Q: mysql return two columns based on same field SELECT
(case when tableA.gender = 'Male' then tableB.X) as Male,
(case when tableA.gender = 'Female' then tableB.X) as Female

...
FROM (MANY TABLES JOINT)
...

GROUP BY tableB.X
ORDER BY count(*) DESC

I'm trying to return two columns based on one field (column_name) by querying whether another column (tableB.X) is 'Male' or 'Female'. How do I do this? I would still need to order in DESC for both columns too. Thank you.
Every row returned as a value and a gender (2 columns). I am trying to split the value into two columns based on the gender and then display in descending order of counts by each splitted column..
i.e. input table:
value     Gender
-----     ------
AAA       Male
BBB       Female
AAA       Male
CCC       Male
AAA       Female
BBB       Female

i.e. output table:
Rank      Male      Female
----      ----      ------
 1        AAA       BBB          (AAA because it has 2 male occurences, BBB has 2 female occurences)
 2        CCC       AAA          (1 occurence each for male and female, ordered descending order)

I also do not know how many different values there are/will be, so SQL would have to do the count for me. I am able to get the results using two queries, by using WHERE gender = male and WHERE gender = female but I'm seeking to know whether I can do it in one query instead.. Thank you!

A: I think something like that is possible with a UNION statement. The following is not tested though:
SELECT
tableB.X as Male,
'' as Female
FROM
...
tableB JOIN tableA
...
WHERE tableA.gender = 'male'

UNION

SELECT
'' as Male,
tableB.X as Female
FROM
...
tableB JOIN tableA
...
WHERE tableA.gender = 'female'

Instead of an empty string '' you might also be able to use NULL.


text:
Q: Harmonic functions are analytic Let $B_1\subset \mathbb{R}^N$ be the unitary ball centered in the origin, and let $u$ be an harmonic function in $B_1$, i.e.
$$
-\Delta u = 0 \,\,\,\,\, \mbox{in}\,\,\, B_1.
$$
How can i prove that $u$ is analytic?
Moreover, how can be proved this results using some estimates on the high order derivative? I know that it must be a classic result, also in several variables, but i cannot find a good reference.

A: A typical approach would be the same as for proving that holomorphic functions are analytic. That is, represent $u$ in terms of its boundary values on some ball contained in the domain of $u$ (the Poisson formula does that). The Poisson kernel is real-analytic, since it is basically $(r^2-|x|^2)/|\zeta-x|^2$ where both numerator and denominator are polynomials of $x$ (the point $\zeta$ is a boundary point, $|\zeta|=r$). The power series converges when $|x|<r$, hence it can be integrated term by term on compact subsets of this ball. This gives a power series representation of $u$.


text:
Q: ASN.1 encodings BER, PER etc. in C# I have been searching on this topic for a while now, without finding any relevant answers. So thought of taking it on 'Stackoverflow' ...
We are trying to encode a string in order to pass it over a TCP/IP connection. Since ASN.1 is the most popular one to do it, so we are trying the various rules BER,DER,PER etc. to find out which one we can use. Our application is a .net based application and I was looking for freely available library which does this.
Strangely i could not find any free libraries.So, i started looking in the .Net framework itself. I found the there is only a 'BERConverter'. So, i did a small example with it. Taking an example string
string str = "The BER format specifies a self-describing and self-delimiting format for encoding ASN.1 data structures. Each data element is encoded as a type identifier, a length description, the actual data elements, and, where necessary, an end-of-content marker. These types of encodings are commonly called type-length-value or TLV encodings. This format allows a receiver to decode the ASN.1 information from an incomplete stream, without requiring any pre-knowledge of the size, content, or semantic meaning of the data"

In UTF-8 or ASCII it show as 512 bytes. I use the following code to encode it using BER
public static byte[] BerConvert(byte[] inputbytes)
    {
        byte[] output = BerConverter.Encode("{o}", inputbytes);
        return output;
    }

I get a byte array with size 522. In some of the other cases I find that the byte size increases compared to the original text. I thought encoding will decrease the size. Why is it happening like this ?
Apart from BER, are there other encoding rules like PER or DER which can be used to reduce the encoding size ? Are there any examples, libraries, or support which will help is implementing the these encoding styles?

A: When looking for ASN.1 Tools (free and commercial), a good place to start is the ITU-T web page http://www.itu.int/en/ITU-T/asn1/Pages/Tools.aspx that lists several.  There are commercial tools listed there that support C#, but I do not see a free C# tool.
As for reduction of size of encodings, this depends significantly on the nature of your ASN.1 specification and the encoding rules used.  If you are primarily sending text strings, BER and DER will not result in a reduction of the size of your message, while PER can significantly reduce the size of the message if you are able to produce a "permitted alphabet" constraint indicating a smaller set of characters permitted in the text you are sending.
You can try various encodings rules and different constraints to see the effects of your changes at the free online ASN.1 encoder decoder at http://asn1-playground.oss.com.

A: If you are beginning work on a new protocol, you may want to reevaluate your needs a bit.
As you probably know by now, ASN.1 comes with a bit of overhead—not just in the messaging, but in the engineering. A typical workflow involves writing a specification that describes the protocol, feeding it into a CASE tool that generates source code for an API, and then integrating the generated components into your application.
That said, some prefer a more ad-hoc approach. Microsoft has a BER converter class that you could try to use with C#: it may be suitable for your needs.
If compression is important, you may want to look into PER, as Paul said. But it's hard to produce valid PER encodings by hand because they rely on the specification to perform compression. (The permitted alphabet constraint is written into the specification and used to enumerate valid characters for shrinking the encoding.)
For more information on ASN.1 there are a number of tutorials online; you can also look at ITU-T standards X.680-X.695, which specify both the syntax notation and various encoding rules.

A: There are a few libraries on CodePlex. Like this one.
https://asn1.codeplex.com/SourceControl/latest#ObjectIdentifier.cs

A: I'll just leave it here Asn1DerParser.NET . And thank to the author for his work!


text:
Q: Swift 3 getting nil value in firebase while retrieving data I am using firebase as my backend i am trying to get the name from firebase of users and trying to display it in UITableView but i am not getting it in UITableView.
My code :-
 func retriveData() {
    ref.observe(.childAdded, with: { (snapshot) in

        if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {

            for snap in snapshot {
                if let userDict = snap.value as? Dictionary<String,AnyObject> {
                    print("user dict - \(String(describing: userDict["name"]))")
                    let username = userDict["name"] as? String
                    self.uname.append(username!)
                }
            }
        }

    })
}

My JSON:-

I have used uname array of strings and used it in UITableView delegate methods.

A: Reload your table view after appending the data to array:
func retriveData() {
    ref.observe(.childAdded, with: { (snapshot) in

        if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {

            for snap in snapshot {
                if let userDict = snap.value as? Dictionary<String,AnyObject> {
                    print("user dict - \(String(describing: userDict["name"]))")
                    let username = userDict["name"] as? String
                    self.uname.append(username!)
                }
            }
                tableView.reloadData()

        }
    })
}


text:
Q: Natbib citation error One of my citations is breaking my document. If I build it with the citation uncalled in the document and a fresh .bbl file, the document builds fine. If I try and call the citation, it breaks the build process and even if I remove the citation, I have to rebuild the .bbl file for a proper build.
Here is the citation, its quite small and simple but something is happening that I can't seem to fix.
@misc{Perez1,
author = {Perez, Hernain David},
booktitle = {CSCMP's Supply Chain Quarterly},
pages = {4},
title = {{Supply Chain Strategies: Which one hits the mark?}},
url = {http://www.supplychainquarterly.com/print/supplychainstrategieswhichonehitsthemark},
year = {2013}
}

I should state that I'm importing my .bib file from Mendeley and haven't had a problem with any other citation. I've move the citation to the first entry on the bib file.
I'm calling the citation with \citet{Perez1} and my master document is using \usepackage[round]{natbib}. The error I'm receiving is an Undefined control sequence.\Generic Error, not exactly helpful.
MWE:
 \usepackage[round]{natbib}
 \begin{document}
 Test citation \citep{Perez1}.
 \bibliographystyle{plainnat}
 \bibliography{Skripsie}
 \end{document}

\@outlinefile=\write3 Package natbib Warning: Citation Perez1' on
  page 1 undefined on input line 15.
  (C:\Users\reece\Documents\Engineering\Skripsie\Test.bbl [1
  {C:/Users/reece/AppData/Local/MiKTeX/2.9/pdftex/config/pdftex.map}] !
  Undefined control sequence. \GenericError ... 4 \errhelp \@err@ ...
  l.12 ...strategieswhichonehitsthemark} . The control sequence at
  the end of the top line of your error message was never \def'ed. If
  you have misspelled it (e.g.,\hobx'), type I' and the correct
  spelling (e.g.,I\hbox'). Otherwise just continue, and I'll forget
  about whatever was undefined.

A: There was a problem with the url field (I suppose direcly copied on the web), which probably had some invisible character in it. I retyped the url, changed the category from @misc to @article since it comes from a journal on line, loaded the url package to break long urls at the end of line.
I also propose to use bblatex with option natbib (it emulates the \citet and citep commands from natbib) and style=authoryear. The advantage, with backend=biber is you can input accented letters directly on the keyboard, since biber understands utf8.
I corrected the url, which wasn't exact, and the author's first name, which precisely has an accented letter.
Code with natbib + bibtex:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[showframe]{geometry}
\usepackage[round]{natbib}
\usepackage{url}

 \begin{document}

\citet{Perez1}.

\bibliographystyle{plainnat}
\bibliography{Skripsie}

.bib file for bibtex
@article{Perez1,
author = {Perez, Hern\'{a}in David},
journal = {CSCMP's Supply Chain Quarterly},
pages = {4},
title = {{Supply Chain Strategies: Which one hits the mark?}},
url = {{http://www.supplychainquarterly.com/print/20130306-supply-chain-strategies-which-one-hits-the-mark/}},
year = {2013},
}

Code with biblatex + biber:*
\documentclass{article}

\usepackage[utf8]{inputenc}
\usepackage[showframe]{geometry}
\usepackage[english = british]{csquotes}
\usepackage[english]{babel}
\usepackage[natbib, style=authoryear, backend=bibtex]{biblatex}
\addbibresource{Skripsie1.bib}

 \begin{document}

 A citation: \citet{Perez1}
\printbibliography

 \end{document}

\end{document}

.bib file for biber;
@article{Perez1,
author = {Perez, Hernán David},
journal = {CSCMP's Supply Chain Quarterly},
pages = {4},
title = {Supply Chain Strategies: Which one hits the mark?},
url = {http://www.supplychainquarterly.com/print/20130306-supply-chain-strategies-which-one-hits-the-mark/},
year = {2013},
}


text:
Q: Update previous merge commit without resolving conflicts twice I have a repo with two branches, main and feature. The output of git log --graph --format='%s %d' --all looks like the following:
* e  (main)
| * d  (HEAD -> feature)
| *   Merge branch 'main' into feature
| |\
| |/
|/|
* | c
| * b
|/
* a

I now want to include the commit e on my main branch in the merge commit on the feature branch, so that I have the latest changes on main, but don't have to force push if commit b on the feature branch is already pushed. I also don't want to have another merge commit in my history. I want my final graph to look like this:
| * d  (HEAD -> feature)
| *   Merge branch 'main' into feature
| |\
| |/
|/|
* | e  (main)
* | c
| * b
|/
* a

I can achieve that with git rebase -i main --onto :/a --rebase-merges and change the instructions for the interactive rebase to:
label onto

reset 9870d06 # a
pick 579c27a b
merge -C d4caa73 main # Merge branch 'main' into feature
pick f672b7f d

The problem with that though is that in the previous merge commit, I had to resolve a conflict between b and c, and with this approach, I would have to resolve this conflict again. Therefore, what I would really like to do is pick up the merge commit where I left off at commit c on main and just continue with merging e into feature on top of b. Is there a way to achieve this? Perhaps there is also a way to introduce another merge commit temporarily and then squash these two merge commits afterwards?

A: Git does include something designed for this kind of work-flow.  There's a hitch: you must turn it on before you do your first merge.
Fortunately, there's a third-party solution to the hitch, called git rerere-train, which is included with Git distributions now (but still not installed directly).  See, e.g., the accepted answer to Smarter rebase avoiding redundant work?
While this question (from eight years ago!) is about rebase, the same concept works with the git merge performed by --rebase-merges.  In fact, the conflicts that occur during rebase are merge conflicts.  You don't need the full training the script can do; you could use this method (from ten years ago!) to teach Git the resolutions you used earlier.
Do note that once you turn on rerere.enabled, Git will keep checking for previous resolutions and re-using them, even if you don't want that to happen (e.g., if you realize you resolved something incorrectly and want to do it over again).  You can turn it off with the same kind of git config operation you used to turn it on, though.  Note also that even with the re-use recoreded resolutions (rerere) option turned on, Git will stop after a conflicted merge that does take these recorded resolutions.  This gives you an opportunity to check the result.


text:
Q: PyDev with Virtualenv: Interpreter not found I am having trouble getting PyDev to work with Virtualenv. I have:

*

*Created a PyDev project. At that point I am forced to specify an interpreter, so I choose the installed system Python 2.7 interpreted. When I add the interpreter the necessary library folders are added as well.

*Issued virtualenv venv in the project directory to create a Virtualenv environment.

*Removed the standard interpreter I added in the first step and tried to add the one located in my venv directory. But I can not seem to get it to work.

In more detail:
All directories in my PythonFlaskTemplate PyDev project:

The result when I try to add the interpreter in my venv directory as well as the necessary libraries there. Did I miss any library directory which I should have picked? Did I pick a directory I should not have picked?

And I still get an error saying that it can not find an interpreter. Even though the interpreter path I picked is correct (I can start it by ./venv/bin/python2.7):

How should I configure PyDev to make it play nicely with Virtualenv?

A: The problem there seems to be that you configured your project not to use the 'default' interpreter, but to use an interpreter which has to be named 'python'.
You can fix that by changing the name of the interpreter in the interpreter preferences (i.e.: preferences > pydev > interpreters > python interpreter > double click it and type 'python')
Or you can set your project to use the default interpreter (i.e.: select project > alt + enter > pydev - interpreter/grammar > interpreter: Default).


text:
Q: TeXnicCenter and Sumatra PDF forward/inverse search off by a few paragraphs I am using TeXnicCenter 2.0 Alpha 4 and MikTex 2.9 with SumatraPDF 2.0.1.
My forward/inverse search is off by 3-4 paragraphs. Forward/inverse search under DVI and YAP works correctly. My setup is shown below. How do I get my SumatraPDF to forward/inverse search properly?


text:
Q: Using existing cookies from outside the browser Ii want to download a file from site that need to be  log-in.
So i think if i use my browser to log-in and store cookie on hdd.
Is it possible to download file with that cookie ?
(its impossible to get cookie with program, anti-bot, etc)

A: everything you can do with your browser you can also do in a program, so if you want a program to download the file, authenticate with the program and let the program receive the cookie.


text:
Q: Start playing sound in background on iOS? I'm trying to do something similar to Tile.app. When it shows a notification, it plays a sound. That seems simple enough-- use UILocalNotification and include the sound file name. But local notifications limit sounds to no more than 30 seconds, and Tile's sound keeps playing for a whole lot longer than that. I expect it's looping, and it continues until I can't stand the noise any more.
The sound also plays even if the phone's mute switch is on, which doesn't happen with local notifications. For these reasons, UILocalNotification appears to be out.
I thought maybe I could post a text-only local notification and have my app play the sound. But using AVAudioPlayer, the play method returns NO and the sound doesn't play.
Other questions have suggested that this is by design, that apps aren't supposed to be able to play sounds from the background-- only continue sound that's already playing. I'd accept that reasoning except that Tile does it, so it's obviously possible. One suggested workaround violates Apple's guidelines in a way that I'm pretty sure Apple checks for now.
Some details that may be relevant:

*

*I have the audio background mode in Info.plist

*I use AVAudioSessionCategoryPlayback on the audio session, and the session should be active (at least, setActive:error: claims to succeed).

*This app uses Bluetooth but does not currently use the bluetooth-central background mode.

A: Actually you can use one of AudioServices... functions

*

*AudioServicesPlaySystemSound

*AudioServicesPlayAlertSound

*AudioServicesPlaySystemSoundWithCompletion
to start playing sound in background.
I'm not sure about length of sound that can be submitted to AudioServicesCreateSystemSoundID because I'm checked only with short looped sound for ringing but this API not tied to notification so possible can overpass 30 second limit.
EDIT:
App still requires audio in UIBackgroundModes to play in background
Cut from my test project appDelegate, iOS 9.3.1
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // test sound in foreground.
    registerAndPlaySound()

    return true
}

func applicationDidEnterBackground(application: UIApplication) {
    var task =  UIBackgroundTaskInvalid
    task = application.beginBackgroundTaskWithName("time for music") {
        application.endBackgroundTask(task)
    }
    // dispatch not required, it's just to simulate "deeper" background
    let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(5 * Double(NSEC_PER_SEC)))

    dispatch_after(delayTime, dispatch_get_main_queue()) {
        self.registerAndPlaySound()
    }
}

func registerAndPlaySound() {
    var soundId: SystemSoundID = 0

    let bundle = NSBundle.mainBundle()
    guard let soundUrl = bundle.URLForResource("InboundCallRing", withExtension: "wav") else {
        return
    }
    AudioServicesCreateSystemSoundID(soundUrl, &soundId)

    AudioServicesPlayAlertSound(soundId)
}

Update
There I used beginBackgroundTask to start sound only as simplest way to execute code in background in another project similar code to registerAndPlaySound was called from PushKit callback without background task.

A: From official Apple documentation:

"Custom sounds must be under 30 seconds when played. If a custom sound
  is over that limit, the default system sound is played instead."

There is no way that you can make UILocalNotication to loop the sound. You can schedule it again with time intervals for 30s, but that one will be a schedulation of another alarm.
To setup your custom notification sound:
notif.soundName = @"sound.caf";

Make sure the sound is actually in your app's bundle, is in the correct format (linear PCM or IMA4—pretty much anywhere that explains how to convert sounds for iOS will tell you how to do that), and is under 30 seconds.


text:
Q: Gracefully cancel a MySQL statement in console while typing it In MySQL's console, how do I gracefully cancel a MySQL statement while in the middle of typing it?
For example, let's say I type SELECT and then hit the ENTER key.  My console now looks like this:
mysql> SELECT
    ->

Now, if I change my mind and no longer want to complete the SELECT statement, how do I cancel it?
If I type Ctrl-C, then this completely exits the MySQL console, which is not what I want.
I can also type a semicolon and prematurely run the statement, but this results in a SQL syntax error.  I would prefer not to pollute MySQL's query log if possible.

A: End the statement with \c:
mysql> select
    -> \c
mysql>


text:
Q: jQuery AJAX Request Error I've done a few AJAX requests using jQuery in my time but for some reason I can't get this one to work.
What my code does is ask the user for their location, geocodes it using the Google Maps API and returns the 5 closest stores to the user.
If I visit the page called by the ajax request in the browser with the URL parameters entered manually then it works fine, e.g. www.domain.com/storelocator/geocode.php?address=xxxxxx
index.php
<form id="storeform">
    <input type="text" id="address" size="50"/>
    <input id="submit" type="image" src="../images/btnsmall.jpg" value="Search" />
</form>

geocode.php
ini_set('display_errors', 1);
error_reporting(E_ALL);

$db_conn = mysql_connect('xxxxxx', 'xxxxxx', 'xxxxx') or die('error');
mysql_select_db('xxxx', $db_conn) or die('error');

$address = $_GET['address'];
$earth_radius = 3959;
$ch = curl_init('http://maps.google.com/maps/api/geocode/json?address='.$address.'&sensor=false');

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$geocode = curl_exec($ch);
curl_close($ch);

$output= json_decode($geocode);

$lat = $output->results[0]->geometry->location->lat;
$lng = $output->results[0]->geometry->location->lng;

$sql = "SELECT *, ( $earth_radius * acos( cos( radians($lat) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians($lng) ) + sin( radians($lat) ) * sin( radians( latitude ) ) ) ) AS distance FROM stores HAVING distance < 25 ORDER BY distance LIMIT 5";
$result = mysql_query($sql);
$stores = '';

if (mysql_num_rows($result) > 0){
    while($row = mysql_fetch_array($result))
    {
        $stores .= $row['town'].' - '.$row['name'];
        $stores .='
';
    }
}
else {
    $stores = 'No results!';
}

echo $stores;

It's hard to see the error in Firebug because it comes and goes so fast but it looks like an internal server error in geocode.php somehow.
Also, when I do submit my form, I get strange x and y parameters in my url, e.g.
http://www.domain.com/store-locator/index.php?x=13&y=11 and I have no idea why.
Any help would be much appreciated.

A: If you use .submit() like this, it will definitely refresh the page (most probably while the request is still running). You should "return false" to prevent this default behavior.
$(document).ready(function() {

$('#storeform').submit(function() {
    var address = $('#address').val();
    var params = $('#storeform').serialize();

    if (address == '') {
    alert('Please enter a location');
    }

    $.ajax({
        url: "geocode.php",
        data: params,
        dataType: 'html',
        type: 'GET',
        success: function(response){
             $('#stores').html(response);
        }
    });

    return false;
});
});


text:
Q: Georeferenced subgraphs / clusters with Graphviz Sometimes I would like to overlay a conceptual graph on top of a map to provide additional context of where elements belong. For example, if I wanted to show social relationships between people in different countries, I might want to have the people located in their appropriate country, but with the layout within those countries being automated.
I've drawn (poorly) a picture to help illustrate what I'm hoping to do.

I found this example, but this appears to be a fake geography with clustering. What I would like is a real map where entities are contained inside their correct region, but where the entities themselves are automagically arranged.

A: I don't think it's possible, either, at least not in a strict sense.
However, you might try to add an invisible node in the middle of each country (use "pos" for placing and "style=plain" with no label to make it invisible), and then link the people who live there with a short edge (use "len" to constrain the length and "weight" to make it more important in the ordering). You might add more than one such node to a country, if it has a funky shape.


text:
Q: How do we conclude that polarized dielectric in electric field reduces overall field? If we have a dielectric inside an electric field, the dipoles in the dielectric will align in the following direction due to the torque on them by the external field.

The conclusion then is that the overall field is reduced since positive charges appear on the bottom plate and negative on the top, opposite to the applied field.
But if we consider the field of the electric dipole itself, we know that it points in the same direction as the dipole moment.
The dipole moments clearly point in the same direction as the applied field. So shouldn't the field due to the polarized dielectric point in the same direction as the applied field, thus strengthening it?

A: You need to at least assume a convention for direction of electric fields. I am using the conventions that is used pretty much everywhere, in this convention the electric field points from positive to negative.

I have marked the external field in blue and field of dipole in green, it is clearly evident that both the fields are opposing and hence cancel each other.
Therefore, the net field magnitude reduces.
Edit/Update (To explain the question raised in comment) :
I think you understand that the field reduces inside the dielectric medium. But pay attention,  if you look at the dielectric material on an atomic scale will you call the dipoles the dielectric material or the spaces between them?
When we look at the dielectric material on atomic scales we need to start looking at the dipoles and not outside them because these dipoles are what make rhe dielectric material.
Moreover for a solid or liquid dielectic material these dipoles are far more than the spaces between them, your picture in this sense is a little misleading. The following picture is a better depiction of what is more likely to be found in dielectrics.

A: Take a piece of Polarised Material with Dipole Moment per Unit Volume $\mathbf{P}$. The associated electrostatic potential is
$$ V(\mathbf{r})=\frac{1}{4\pi\epsilon_0}\int_V\frac{\mathbf{\hat{R}}.\mathbf{P}(\mathbf{r}')}{R^2}dV' $$
where $\mathbf{R}=\mathbf{r}-\mathbf{r}'$. Some clever manipulation, mainly noting that $\nabla'(1/R)=\mathbf{\hat{R}}/R^2$ lets us write this as a volume + surface integral
$$ V= \frac{1}{4\pi\epsilon_0}\int_V\mathbf{P}(\mathbf{r}').\nabla'\left(\frac{1}{R}\right)dV'=\frac{1}{4\pi\epsilon_0}\left[ \int_V\nabla'.\left(\frac{\mathbf{P}(\mathbf{r}')}{R}\right)dV'-\int_V\frac{\nabla'.\mathbf{P}(\mathbf{r}')}{R}dV' \right] $$
$$ V=\frac{1}{4\pi\epsilon_0}\oint_{\partial V}\frac{\mathbf{P}(\mathbf{r}').d\mathbf{S}'}{R}-\frac{1}{4\pi\epsilon_0} \int_V\frac{\nabla'.\mathbf{P}(\mathbf{r}')}{R}dV'$$ which familiarity with electrostatics will tell you is equivalent to the potential had the object had surface charge density $\mathbf{\hat{n}}.\mathbf{P}$ and volume charge density $-\nabla.\mathbf{P}$.
So, the field of a polarised object, dipole moment per unit volume $\mathbf{P}$, will have an induced Electric Field equal to that generated by considering the object to have surface charge $\mathbf{\hat{n}}.\mathbf{P}$ and volume charge $-\nabla.\mathbf{P}$.
Suppose $\mathbf{P}=-P\mathbf{\hat{z}}$ is constant (to roughly match your problem), then immediately $\nabla.\mathbf{P}=0$ so there is no contribution from a volume charge density. On the $+ve$ plate of the example, $\mathbf{\hat{n}}$ (pointing outwards) points vertically upwards i.e. $\mathbf{\hat{n}}=\mathbf{\hat{z}}$ and on the $-ve$ plate we have the opposite $\mathbf{\hat{n}}=-\mathbf{\hat{z}}$. At the $+ve$ plate surface we therefore induce $-P\mathbf{\hat{z}}.\mathbf{\hat{z}}=-P$ (negative charge density), and on the $-ve$ plate surface we induce $-P\mathbf{\hat{z}}.(-\mathbf{\hat{z}})=P$ i.e. positive charge density. The direction of the induced electric field  therefore points from the $-ve$ plate to the $+ve$ plate, acting to reduce the applied field.

A: Due to the external electric field,the molecules (which may be polar or non-polar) becomes a dipole. As a result there is an existence of consecutive dipoles as shown in your figure.
Now these molecules are placed very closely. So in the material the charges can be neglected due to the coexistence of positive and negative charges very closely. But on the surfaces a net layer of charge is formed (this is how molecules with bond charges are polarised). In your figure the upper surface has a negative charge density and downward one has a positive charge density. So there is a creation of an internal field. (Thus what happens inside the dipole does not matter). So field magnitude is reduced.


text:
Q: Can a Toolstrip and Toolstrip Textbox have the same color? I am using a Toolstrip on a Windows Form. On this Toolstrip I placed a Textbox. I am not able to give the Textbox the same color as the Toolstrip and BackColor transparent is not possible.
Toolstrip BackColor = Control and Textbox BackColor = ControlLightLight.

A: I changed from Textbox to Label. Since I am just trying to display some text the label works fine and the BackColor can be set to Transparent.


text:
Q: Load a page with onclick method of an html button with parameters in the url I'm modifying a webpage and I would like to create a button that onclick it loads me a new page in the same window. For example, for a link to a webpage with some parameters it could be:
LINK TO THE WEBSITE

If I do this, the link loads correctly the website. If I modify it to:
LINK TO THE WEBSITE

I'm successful too. However, I would like to implement this on a button. Therefore I have:
<button
   onclick="javascript:window.open('www.mypage.com/page?param1=abc&param2=345', '_self')"
</button>

However, now it loads "www.mypage.com/page", and the parameters are erased, even I can see in the source code of the website they are there. Why? How can I implement this with a button?

A: you could wrap the button into the href link.
for example:
<button>Click me</button>


text:
Q: Linkedin OAuth and Zend retrieving Acces Token returns 'Error in HTTP request' Answer + new question
I found out that the code below works just fine on a LIVE server. LinkedIN blocked all requests from localhost.
That established; Does anybody know how to test an application from localhost with LinkedIN OAuth? Because doing this on a live server sucks!
Old Question
I'm trying to connect with Zend_OAuth to LinkedIN. This code used to work, but now it returns an error in http request while I'm trying to retrieve an access token.
Tried checking the LinkedIN api, but the code still seems valid. Tried several scripts but all with the same result.
The config is setup in the preDispatch of my controller
$this->configLinkedin = array(
        'version' => '1.0',
        'siteUrl' =>  'http://'.$_SERVER['HTTP_HOST'].$this->view->baseUrl(false).'/news/index/connectlinkedin',
        'callbackUrl' => 'http://'.$_SERVER['HTTP_HOST'].$this->view->baseUrl(false).'/news/index/connectlinkedin',
        'requestTokenUrl' => 'https://api.linkedin.com/uas/oauth/requestToken',
        'userAuthorisationUrl' => 'https://api.linkedin.com/uas/oauth/authorize',
        'accessTokenUrl' => 'https://api.linkedin.com/uas/oauth/accessToken',
        'consumerKey' => 'XXX',
        'consumerSecret' => 'XXX'
    );

And the code in the action to connect to linkedIN is
$this->consumer = new Zend_Oauth_Consumer($this->configLinkedin);

    if(!empty($_GET) && isset($_SESSION['LINKEDIN_REQUEST_TOKEN']))
    {
        $token = $this->consumer->getAccessToken($_GET, unserialize($_SESSION['LINKEDIN_REQUEST_TOKEN']));
        // Use HTTP Client with built-in OAuth request handling
        $client = $token->getHttpClient($this->configLinkedin);
        // Set LinkedIn URI
        $client->setUri('https://api.linkedin.com/v1/people/~:(id,first-name,last-name,picture-url)');
        // Set Method (GET, POST or PUT)
        $client->setMethod(Zend_Http_Client::GET);
        // Get Request Response
        $response = $client->request();
        $this->NewsService->TokenSocialMedia(
            $token,
            'linkedin',
            serialize($response->getBody())
        );
        $_SESSION['LINKEDIN_REQUEST_TOKEN'] = null;
        $this->_helper->flashMessenger(array('message' => $this->view->translate('The CMS is successfully connected to your linkedin account'), 'status' => 'success'));
        $this->_helper->redirector('settings#settingSocial', 'index');
    }
    else
    {
        $token = $this->consumer->getRequestToken();
        $_SESSION['LINKEDIN_REQUEST_TOKEN'] = serialize($token);
        $this->consumer->redirect();
    }

What am I missing or doing wrong? I use a similair setup for Twitter and that works fine.
UPDATE 20 September 211
I found out that this rule is returning the error:
 $token = $this->consumer->getRequestToken();

I'm still clueless why, and reading the linkedin api doesn't help a bit. Will keep you posted.

A: I got similar problem and after adding openssl extension it was solved
try adding to php.ini this line:
extension=php_openssl.dll

A: I got the same issue, try to turn off ssl before asking the new consumer :
        $httpConfig = array(
        'adapter' => 'Zend\Http\Client\Adapter\Socket',
        'sslverifypeer' => false
    );

    $httpClient = new HTTPClient(null, $httpConfig);
    OAuth::setHttpClient($httpClient);


text:
Q: Experience of moving to 64 bit JVM Our company is planning to move to 64 bit JVM in order to get away from 2 GB maximum heap size limit. Google gave me very mixed results about 64 bit JVM performance.
Has anyone tried moving to 64 bit java and share your experience

A: In a nutshell: 64-bit JVMs will consume more memory for object references and a few other types (generally not significant), consume more memory per thread (often significant on high-volume sites) and enable you to have larger heaps (generally only important if you have many long-lived objects)
Longer Answers/Comments:

*

*The comment that Java is 32-bit by
design is misleading. Java
memory-addressing is either 32, or
64-bit, but the VM spec ensures that
most fields (e.g. int, long, double,
etc.) are the same regardless.

*Also - the GC tuning comments while
pertinent for number of objects, may
not be relevant, GC can be quick on
JVMs with large heaps (I've worked
with heaps up to 15GB, with very
quick GC) - it depends more on how
you play with the generational
collector schemes, and what your
object usage pattern is. While in the
past people have spent lots of energy
tuning parameters, it's very workload
dependent, and modern (Java 5+) JVMs
are very good at self-tuning - unless
you have lots of data you're more
likely to harm yourself than help
with aggresive JVM tuning.

*As mentioned on x86 architectures,
the 64-bit EMT64 or x64 processors
also include new instructions for
doing things like atomic writes, or
other options which may also impact
high-performance applications.

A: Works fine for us. Why don't you simply try setting it up and run your load test suite under a profiler like jvisualvm?

A: If you need the larger heap, then questions of performance are rather moot, aren't they? Or do you have a plan for horizontal scaling?
The main problem that I've heard with 64-bit apps is that a full garbage collection can take a very long time (because it's based on number of live objects). So you want to carefully tune the GC parameters to avoid full collections (I've heard one anecdote about a company that had 64 Gb of heap, and tuned their GC so that they'd never to a full GC; they'd simply shut down once a week).
Other than that, recognize that Java is 32-bit by design, so you're not likely to see any huge performance increase from moving data 64 bits at a time. And you're still limited to 32-bit array indices.

A: We've written directly to 64bit and I can see no adverse behavior...

A: Naively taking 32 bit JVM workloads and putting them on 64 bit produces a performance and space hit in my experience.
However, Most of the major JVM vendors have now implemented a good technology that essentially compresses some of the heap - it's called compressed references or compressed oops for 64 bit JVMs that aren't "big" (ie: in the 4-30gb range).
This makes a big difference and should make a 32->64 transition much lower impact.
Reference for the IBM JVM:  link text


text:
Q: How to view user stories in TFS? Where is the option in TFS to view user stories?
I can see the task but task is a break down of user story!

A: If you have opened the task, and the task is a child of the user story, then you should be able to access the user story from the "All Links" tab.
Alternatively, select the team project that you want, right click Work Items and select "New Query".  The default query is anything in the project, so change the WI type to User Story, click run and you should get a list of all user stories.