text:
Q: How do I properly set the permgen size? I have this VM with tomcat, java, and grails in it. I've been getting permgen errors so I looked around and found the solution:
set JAVA_OPTS="-Xms256m -Xmx1024m -XX:PermSize=512m -XX:MaxPermSize=512m"

I use SSH to access the vm and type the arguments above. I suppose that would fix the problem. Thing is, I wanted to make sure that I did it correctly. So I searched again on how I could check the current permSize and this is the solution I got:
jinfo -flag MaxPermSize 6444

6444 is the pid, and as a response, I got this.
-XX:MaxPermSize=85983232

Question: Is the value of the maxPermSize in bytes? because, if it is, then that would mean that the java_opts command didn't work. I am expecting to get 512m but 85983232 bytes = 82 mb.. Or am I seeing it wrong..? Can anybody enlighten me on this? D:

A: You have to change the values in the CATALINA_OPTS option defined in the Tomcat Catalina start file. To increase the PermGen memory change the value of the MaxPermSize variable, otherwise change the value of the Xmx  variable.
Linux & Mac OS: Open or create setenv.sh file placed in the "bin" directory. You have to apply the changes to this line:
export CATALINA_OPTS="$CATALINA_OPTS -server -Xms256m -Xmx1024m -XX:PermSize=512m -XX:MaxPermSize=512m"

Windows:
Open or create the setenv.bat file placed in the "bin" directory:
set CATALINA_OPTS=-server -Xms256m -Xmx1024m -XX:PermSize=512m -XX:MaxPermSize=512m

A: Don't put the environment configuration in catalina.bat/catalina.sh. Instead you should create a new file in CATALINA_BASE\bin\setenv.bat to keep your customizations separate of tomcat installation.

A: So you are doing the right thing concerning "-XX:MaxPermSize=512m": it is indeed the correct syntax. You could try to set these options directly to the Catalyna server files so they are used on server start.
Maybe this post will help you!
How to make sure that Tomcat6 reads CATALINA_OPTS on Windows?

A: Completely removed from java 8 +
Partially removed from java 7 (interned Strings for example)
source


text:
Q: Width of page in iframe I have a parent page and inside that parent page, there is an iframe that is around half the size of the parent page.
The JavaScript in the iframed page is supposed to get the size of the iframed page and set the size of a text input, but both JavaScript's document.body.clientWidth and jQuery's $(document).width() are returning the parent page's width.
How do I get the width of the iframed page from scripts inside the iframe (that is, without having to send the iframe width from the parent page to the iframe page with querystrings)? They are cross-domain too.

A: simply use this -
<iframe src="demo_iframe.htm" width="200" height="200"></iframe>

A:
The similar kind of work is done here stackoverflow.com/questions/7808729/… you can refer this if it works –  Manoj Singh

Thank you, this is exactly what I wanted!
EDIT: Sorry, after a bit of testing, this doesn't work too well. In jsfiddle it works, but in my page, it only gives me the height accurately.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Awesomium c++: syntax error : missing ';' before '*' I'm trying to integrate c++ code with awesomium functionalities, but I get many errors.
It seems that VisualStudio doesn't like my definition/declaration of the WebCore element. I copied it from http://wiki.awesomium.com/tutorials/tutorial-1-hello-awesomium.html.
I have simplified the code until this, and I still get the errors.
SimpleClass.cpp:
#include <Awesomium/WebCore.h>
include "SimpleClass.h"
using namespace Awesomium;

CSimpleClass::CSimpleClass(){
    WebCore *web_core = WebCore::Initialize(WebConfig());
}
CSimpleClass::~CSimpleClass(){
}

SimpleClass.h:
class CSimpleClass
{
public:
    CSimpleClass(void);
    ~CSimpleClass(void);
    WebCore *web_core;
};

Thanks!

A: Change your SimpleClass.h header to read:
#pragma once
#ifndef SIMPLECLASS_H
#define SIMPLECLASS_H

// forward declarations
namespace Awesomium{
class WebCore;
}

class CSimpleClass
{
public:
    CSimpleClass(void);
    ~CSimpleClass(void);
    Awesomium::WebCore *web_core;
};

#endif /* SIMPLECLASS_H */

That way you announce to your compiler that there exists a type WebCore in the namespace Awesonium, and then you can use it to declare the member pointer CSimpleClass::web_core.

A: Potential dependency issues aside, the problem is that your header does not know that you want to use the Awesomium namespace.
Either (preferred) be explicit in the header about your definition of *web_core by doing
class CSimpleClass
{
public:
    CSimpleClass(void);
    ~CSimpleClass(void);
    Awesomium::WebCore *web_core; //note the use of Awesomium::
};

or (if you really must) include your header after your using directive
#include <Awesomium/WebCore.h>
using namespace Awesomium;
#include "SimpleClass.h"


text:
Q: What is the word for a guy who is from a village and ignorant because of it? How should I describe a guy who moves to a city or urban area, but does not know much about how things work in those cities, and make an ass of themselves?
The closest word I came up with is unsophisticated, but it is a broad term.

A: To describe a person like that I might say, "country bumpkin".
Using the word unsophisticated in this context would be accurate, and not too broad. It it a rather sophisticated way of saying it. "Country bumpkin" is much more casual English.

A: There are a few choices, depending on how formal the word is that you are looking for.
The word you mentioned: unsophisticated fits well, and is pretty high on the formal list
Others include:

*

*countrified

*artless

*provincial

*rustic

*hick

*hillbilly

*redneck

*backwoodsman

*yokel

Hillbilly, hick and redneck would probably be at the bottom in terms of formality. In line with the bit about '... making an ass of themselves' these phrases all have some degree of negative connotation, depending on context of course (as shown by the recent EL&U question on Redneck pride).
Look for synonyms of any of these words to find more.  There are quite a few.


text:
Q: Python find number of student assessments by using pd.groupby and insert the score of each assessment I got a dataset that looks like this :
Dataset
I am trying to accumulate extra columns based on the number of assessments the student has completed.
For example, the first student has completed 5 assignments so we need to accumulate a table like this :
acummulated_columns
The id_assessment column is converted into A[i], based on number of len(id_assessments) of id_student and then each score is inserted to the relevant assignment.
What is the best approach tackling this ?


text:
Q: inverse image of sets prove or disprove
If $f : X → Y$ is a injective function and $f(X) = Y$, then $f^{−1}(f(\{u\})) = \{u\}\quad\forall u∈ X$.
After I worked in this statement I find it is true statement since $f(x)$ is one to one but I am not sure since I find that is difficult to prove it .

A: For all $x\in X$ we have $$x\in f^{-1}(f(\{u\}))\iff f(x)\in f(\{u\})\iff$$ $$\iff f(x)\in \{f(u)\}\iff f(x)=f(u)\iff $$ $$\iff x=u.$$ The last equivalence  holds because $f$ is injective.

A: You have stated that f is injective and $f(X)=Y $ hence it is bijective. Hence, $\exists f^{-1}: Y \to X$ Satisfying, $f^{-1} \circ f= f \circ f^{-1} = Id$. Thus, you can conclude $\forall x \in X$, $f^{-1} \circ f(x) =x$ and $\forall y \in Y$, $f \circ f^{-1}(y) =y$.

A: This is true even without assuming $f$ is onto!
$f : X \rightarrow Y$ is injective if and only if $f : X \rightarrow f(X)$ is invertible .Therfore for all $x \in X$ we have $\{y\}=f(\{x\}) \subseteq f(X)$ equivalently $f^{-1}(\{y\}) = \{x\}$ which means $f^{-1}(f(\{x\}))=\{x\}$


text:
Q: Strange behaviour formatting a long string Something must explain this, but for me this makes currently no sense :)
If you have this three variables:
(setf l '((( "NAME" "HASH-TABLE" )) ("&BODY") ("BODY")))
(setf fs "WITH-HASH-TABLE-ITERATOR")
(setf doc "V0lUSC1IQVNILVRBQkxFLUlURVJBVE9SICgobmFtZSBoYXNoLXRhYmxlKSAmYm9keSBib2R5KQoKUHJvdmlkZXMgYSBtZXRob2Qgb2YgbWFudWFsbHkgbG9vcGluZyBvdmVyIHRoZSBlbGVtZW50cyBvZiBhIGhhc2gtdGFibGUuIE5BTUUKaXMgYm91bmQgdG8gYSBnZW5lcmF0b3ItbWFjcm8gdGhhdCwgd2l0aGluIHRoZSBzY29wZSBvZiB0aGUgaW52b2NhdGlvbiwKcmV0dXJucyBvbmUgb3IgdGhyZWUgdmFsdWVzLiBUaGUgZmlyc3QgdmFsdWUgdGVsbHMgd2hldGhlciBhbnkgb2JqZWN0cyByZW1haW4KaW4gdGhlIGhhc2ggdGFibGUuIFdoZW4gdGhlIGZpcnN0IHZhbHVlIGlzIG5vbi1OSUwsIHRoZSBzZWNvbmQgYW5kIHRoaXJkCnZhbHVlcyBhcmUgdGhlIGtleSBhbmQgdGhlIHZhbHVlIG9mIHRoZSBuZXh0IG9iamVjdC4KCkNvbnNlcXVlbmNlcyBhcmUgdW5kZWZpbmVkIGlmIEhBU0gtVEFCTEUgaXMgbXV0YXRlZCBkdXJpbmcgZXhlY3V0aW9uIG9mIEJPRFksCmV4Y2VwdCBmb3IgY2hhbmdpbmcgb3IgcmVtb3ZpbmcgZWxlbWVudHMgY29ycmVzcG9uZGluZyB0byB0aGUgY3VycmVudCBrZXkuIFRoZQphcHBsaWVzIHRvIGFsbCB0aHJlYWRzLCBub3QganVzdCB0aGUgY3VycmVudCBvbmUgLS0gZXZlbiBmb3Igc3luY2hyb25pemVkCmhhc2gtdGFibGVzLiBJZiB0aGUgdGFibGUgbWF5IGJlIG11dGF0ZWQgYnkgYW5vdGhlciB0aHJlYWQgZHVyaW5nIGl0ZXJhdGlvbiwKdXNlIGVnLiBTQi1FWFQ6V0lUSC1MT0NLRUQtSEFTSC1UQUJMRSB0byBwcm90ZWN0IHRoZSBXSVRILUhBU0gtVEFCTEUtSVRFUkFUT1IKZm9yLg==")

format it with this directive:
(format NIL "~a ~a ~a" fs doc l)

I get the output:
"WITH-HASH-TABLE-ITERATOR V0lUSC1IQVNILVRBQkxFLUlURVJBVE9SICgobmFtZSBoYXNoLXRhYmxlKSAmYm9keSBib2R5KQoKUHJvdmlkZXMgYSBtZXRob2Qgb2YgbWFudWFsbHkgbG9vcGluZyBvdmVyIHRoZSBlbGVtZW50cyBvZiBhIGhhc2gtdGFibGUuIE5BTUUKaXMgYm91bmQgdG8gYSBnZW5lcmF0b3ItbWFjcm8gdGhhdCwgd2l0aGluIHRoZSBzY29wZSBvZiB0aGUgaW52b2NhdGlvbiwKcmV0dXJucyBvbmUgb3IgdGhyZWUgdmFsdWVzLiBUaGUgZmlyc3QgdmFsdWUgdGVsbHMgd2hldGhlciBhbnkgb2JqZWN0cyByZW1haW4KaW4gdGhlIGhhc2ggdGFibGUuIFdoZW4gdGhlIGZpcnN0IHZhbHVlIGlzIG5vbi1OSUwsIHRoZSBzZWNvbmQgYW5kIHRoaXJkCnZhbHVlcyBhcmUgdGhlIGtleSBhbmQgdGhlIHZhbHVlIG9mIHRoZSBuZXh0IG9iamVjdC4KCkNvbnNlcXVlbmNlcyBhcmUgdW5kZWZpbmVkIGlmIEhBU0gtVEFCTEUgaXMgbXV0YXRlZCBkdXJpbmcgZXhlY3V0aW9uIG9mIEJPRFksCmV4Y2VwdCBmb3IgY2hhbmdpbmcgb3IgcmVtb3ZpbmcgZWxlbWVudHMgY29ycmVzcG9uZGluZyB0byB0aGUgY3VycmVudCBrZXkuIFRoZQphcHBsaWVzIHRvIGFsbCB0aHJlYWRzLCBub3QganVzdCB0aGUgY3VycmVudCBvbmUgLS0gZXZlbiBmb3Igc3luY2hyb25pemVkCmhhc2gtdGFibGVzLiBJZiB0aGUgdGFibGUgbWF5IGJlIG11dGF0ZWQgYnkgYW5vdGhlciB0aHJlYWQgZHVyaW5nIGl0ZXJhdGlvbiwKdXNlIGVnLiBTQi1FWFQ6V0lUSC1MT0NLRUQtSEFTSC1UQUJM (((NAME
                                                                                HASH-TABLE))
                                                                                (&BODY)
                                                                                (BODY))"

Note the line breaks at the end of the printed list. I expected one straight line without any line breaks. This must be coming from SBCL and is not some command line behaviour with long strings, since (format NIL ...) gives me a similar output in a string. The behaviour is also new in SBCL > 2.0.
Is there some control variable I'm missing, like *print-level*?
Sorry for the long outputs, but it happens only with long outputs.

A: This is due to *PRINT-PRETTY* being set. This causes the printer to wrap lines and try to line up list elements.
Fix it with
(setq *print-pretty* nil)


text:
Q: Unexpected error even before login prompt I have a web application with 8 site collections, each with their own database.  I'm getting a strange error when trying to open 3 of them, but only when trying to go directly to them in a new browser window.  (Meaning, if I log into one of the other sites and link back to one of the 3, there is no problem.)
I get the old "An unexpected error has occurred" window even before the login prompt appears.  If I click "Go back to site", the login prompt appears and I can log in normally.
Looking through the logs, this is what's happening for each of the sites:
A few category General, level Verbose entries about looking up the site, ending with Found typical site /the/site in web application ...etc.
A General/Verbose entry Application error when access /the/site/default.aspx, Error=Operation is not valid due to the current state of the object.
A Runtime/Unexpected entry:
System.InvalidOperationException: Operation is not valid due to the current state of the object.
 at Microsoft.SharePoint.WebControls.SPControl.EnsureSPWebRequest(SPWeb web)
 at Microsoft.SharePoint.WebControls.SPControl.SPWebEnsureSPControl(HttpContext context)
 at Microsoft.SharePoint.ApplicationRuntime.SPRequestModule.GetContextWeb(HttpContext context)
 at Microsoft.SharePoint.ApplicationRuntime.SPRequestModule.PostResolveRequestCacheHandler(Object oSender, EventArgs ea)
 at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
 at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

A General/Verbose entry PermissionMask check failed. asking for 0x00010000, have 0x00000000
A General/Medium entry Unknown SPRequest error occurred. More information: 0x80070005
And then releasing the SPRequest.
Because of the PermissionMask entry, I would think to look for something about permissions, but remember this is happening before I even have a chance to enter credentials.
What else can go wrong at that early stage?  My gut feeling is that without having authenticated, it's not trying to serve up any content yet.  The log entries mentioned looking up the site in the Config database, and I checked the database upgrade status.  There were a few non-content databases that needed to be upgraded, so I ran PSConfig.exe -cmd upgrade -inplace b2b -force -cmd applicationcontent -install -cmd installfeatures, and now everything looks fine there, but the problem is still happening.
I just don't know where else to look, or even what to look for.  Anyone have any ideas about this?
EDIT:
This apparently has to do with how SharePoint deals with different requests.  Contrary to what I thought, it is not happening just on 3 sites, it's happening on all sites, and it happens when the request specifies a page.
http://server/my/site/default.aspx will produce the error.
http://server/my/site will not.
At first I thought it might be because we have a warning dialog that pops up initially, and the dialog is getting it's text from a list.  Which would explain the PermissionMask error -- before authenticating, the request is anonymous (0x00000000), but meanwhile to get the text for the dialog, the code opens the web (0x00010000) where the list is.  But I changed it to impersonate the system account in order to open the web and get the text (verified that this is working correctly through logging), and the error is still happening.

A: Apparently this was a VM issue, and not a SharePoint problem after all.  This morning, the VM hosting this SharePoint server appeared to be down.  The virtual environment admins did some behind-the-scenes voodoo, brought the server back online, and now the error is not happening anymore.  Don't really know what was wrong, or what they did to fix it, but things are back to normal.


text:
Q: C# Console.Writeline Placeholders for function name Are there any placeholders for the current function's name when using Console.Writeline()?

A: In Reflection, you have MethodBase.GetCurrentMethod() as an option.

A: I believe this is what you're looking for:
using System.Diagnostics;

StackTrace stackTrace = new StackTrace();
Console.WriteLine(stackTrace.GetFrame(1).GetMethod().Name);

A: See http://www.codeproject.com/Articles/7964/Logging-method-name-in-NET
Another (better) option for logging is AOP, using a framework such as PostSharp

A: Not unless you want to use reflection. However, C# 5 will include a new feature called "Caller Info Attributes" which will insert the information at compile time. See http://bartwullems.blogspot.com/2012/02/c-5-caller-info-attributes.html


text:
Q: Confusión para integrar React y Redux He estado mirando vídeos y leyendo documentos sobre React Redux, pero todos varían en algo y no concreto aplicarlo en un proyecto personal que tengo. Así que voy a tratar de enumerar los puntos necesarios para realizar un proyecto con React Redux.
Estructura de directorios

*

*proyecto

*

*src

*

*components

*User

*

*index.js (Componente contenedor)

*page.js (Componente presentacional)

*actions

*

*users.js

*index.js (exporta la combinación de actionCreators)

*reducers

*

*users.js

*index.js (exporta la combinación de reducers con combineReducers

*constants

*

*actionTypes.js

*services

*

*users.js

*index.js

*store.js

*public

*

*index.html

Configuración de Redux

*

*Se crean las constantes en proyecto/src/constants/actionTypes.js:

export const CREATE_USER = 'CREATE_USER';
export const DELETE_USER = 'DELETE_USER';
export const UPDATE_USER = 'UPDATE_USER';

*Se crean los actionCreators en proyecto/src/actions/users.js y luego se combinan en proyecto/src/actions/index.js:

*

*users.js

import { CREATE_USER } from '../constants/actionTypes';

export default function createUser(user) {
    type: CREATE_USER,
    user
}

*

*index.js

import { createUser } from './users';

export default {
    createUser
}

*Se crean los reducers en proyecto/src/reducers/users.js y se combinan en proyecto/src/reducers/index.js utilizando combineReducers():

*

*users.js

import { CREATE_USER, UPDATE_USER, DELETE_USER } from '../constants/actionTypes';
import { createUser } from '../services/users';

const initialState = {
    name: '',
    password: '',
    email: ''
}

export default function users(state = initialState, action) {
    switch (action.type) {
        case CREATE_USER:
            state = createUser(action.user);
            return state;
    }
}

*

*index.js

import users from './users';

export default combineReducers({
    users
})

*Se crea el store en proyecto/src/store.js:
import { createStore } from 'redux';
import reducers from './reducers';

export const store = createStore(reducers);

Configuración de React Redux

*Se envuelve a la aplicación en el componente <Provider> en proyecto/src/index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { store } from './store';

const Root = () => (
    `
        <Provider store={store}>
            <App />
        </Provider>
    `
)

ReactDOM.render(Root, document.getElementById('root');

*Se convierte el estado de los componentes a propiedades con mapStateToProps en proyecto/src/components/User/index.js:
import React, { Component } from 'react';
import { createUser } from '../../actions/users';
import Page from './page';

class User extends Component {
    render() {
        return <Page users={this.props.users} />
    }
}

const mapStateToProps = state => ({
    users: this.props.users
});

const mapDispatchToProops = dispatch => ({
    // ¿y acá?
});

export default connect(mapStateToProps, mapDispatchToProps)(User);

Entonces: La pregunta sería, ¿más o menos está bien éste ciclo? ¿Qué está mal?

Ejemplifiqué con un componente pero la aplicación es lógicamente más grande.

A: El primer error que noto es que en actions/users estás haciendo un export default y en el index lo requieres como: import { createUser } f... cuando lo ideal es que si al requerirlo va a ser de esa forma, entonces al exportarlo solo hagas: export function createUser () {...
Del resto para mí, luce bien lo que estás haciendo, sin embargo, no añadiste el contenido de lo que tiene tu archivo de services/users el cual por lo que veo tiene una función llamada createUser (verifica que no se esté exportando de la misma forma que el otro, o posiblemente tendrás un error al ejecutar). Debes tener en cuenta que si esta función es una función asíncrona entonces redux no funcionará. Una filosofía de redux es intentar manejar las funciones lo más simples posibles, si lees esto tendrás mucha más idea de qué te hablo, por lo que lo ideal para realizar esas acciones asíncronas es usar algo como redux-thunk.
Por otro lado, ten en cuenta que tus actions son los encargados de dar los datos para el nuevo state, y los reducers son la lógica para ubicar esos actions en el state. Por lo tanto, en ese orden de ideas, lo normal es que llames a createUser dentro del action y no dentro del reducer.
Haces una pregunta con respecto al mapStateToProps y el mapDispatchToProps, la diferencia básicamente de cada uno es lo que reciben. mapStateToProps recibe como parámetro de la función el state y todo lo que devuelvas en el objeto se lo asignará al componente por medio de la función connect, y mapDispatchToProps recibe como parámetros el dispatch el cual es el encargado de hacer correr tus actions, sabiendo eso, podrías hacer algo así:
const mapDispatchToProps = (dispatch) => ({
  createUser: (payload) => {
    // ejecutamos la acción
    return dispatch(createUser(payload));
  }
});

Y ahora en cualquier método de tu componente puedes llamarla y usarla así (esto varía de acuerdo a lo que realice tu función createUser, es solo un ejemplo)
crearUsuario() {
  this.props.createUser({ name: 'Foo', lastName: 'Bar' });
}

Como última anotación, veo que tu componente Root renderiza algo como esto:
`
    <Provider store={store}>
        <App />
    </Provider>
`

No necesitas de esas comillas, puedes hacerlo directamente gracias a JSX.
Ahora si, espero haberte ayudado a resolver algunas dudas, de igual forma puedes comentar la respuesta y te ayudaría en alguna otra inquietud que tengas, del resto, vas por buen camino y has entendio bastante bien el concepto de redux

A: Comparto la recomendación de agregar un middleware como redux-thunks otra recomendación puede ser que utilices el patron Redux Ducks https://medium.com/react-redux/estructura-de-archivos-ducks-para-redux-js-36bb56a70cb3 lo cual haría mucho mas sencilla la creación de actions y reducers
Otra herramienta muy útil para todo desarrollador React-Redux es Redux Dev Tools
https://github.com/zalmoxisus/redux-devtools-extension

A: Existen muchas implementaciones de Redux.
En tu "mapDispatchToProops" van los actions que haran cambios en tus reducers, .en tu caso sería createUser
Otra cosa que debes tomar en cuenta es que para poder hacer actions asincronos necesitaras un middleware, te recomiendo redux-thunks (Igual que en el comentario de arriba)


text:
Q: How to convert a string IP address to Decimal using Split and Aggregate in C#? I'm trying to convert one IP from string to Decimal using split and aggregate. Specifically I made this question about Split and Aggregate not other solutions like IpAddress or similar.
For the "192.168.0.1" ip, the number must be 3232235521
var decimalIP = "192.168.0.1".Split(".").Aggregate(0, (numIP, segment) => {
    numIP = numIP<< 8;
    return numIP + Decimal.Parse(segment);
});

This method does not work:
Decimal number = "192.168.0.1".Aggregate(0m, (numIP, segment) => {
    numIP = (long)numIP << 8;
    return (Decimal)(numIP + Decimal.Parse(segment));
});

I was also trying
var segments = "192.168.0.1".Select(segment => Decimal.Parse(segment));
var reverse = segments.Reverse();

Decimal reverseSumm = reverse.Aggregate(0m, (numIP, segment) => {
    numIP = (long)numIP << 8;
    return (Decimal)(numIP + segment);
});

Decimal directSumm = segments.Aggregate(0m, (numIP, segment) => {
    numIP = (long)numIP << 8;
    return (Decimal)(numIP + segment);
});

The number
How to do it?

A: There are multiple issues here.

*

*Your question is constantly changing

*Bit shift operations are not allowed for decimals as they are floating point numbers

*Your aggregate function needs to have the same return value type as its input value type

*You can't add a string to a numeric type without parsing it to a numeric type first.

*You can't use an int type as it uses 32 bit to represent a range including negative numbers, but uint is suited to represent a 32 bit positive number - which an IP address basically is.

This would work:
Decimal directSum = "192.168.0.1".Split(".").Aggregate(0m, (numIP, segment) => {
    numIP = (uint)numIP << 8;
    return numIP + Decimal.Parse(segment);
});

But what this is basically doing is casting inside a loop, which is not the most elegant way to do things. I'ld recommend operating with uint and doing the cast once you are finished:
            Decimal directSum = "192.168.0.1".Split(".").Aggregate(0u, (numIP, segment) => {
                numIP = numIP << 8;
                return numIP + uint.Parse(segment);
            });

Or if you want to keep using var:
            var directSum = (decimal) "192.168.0.1".Split(".").Aggregate(0u, (numIP, segment) => {
                numIP = numIP << 8;
                return numIP + uint.Parse(segment);
            });

I`d also propose to use uint and not decimal for your result, if it's not a hard requirement to use decimal:
            var directSum = "192.168.0.1".Split(".").Aggregate(0u, (numIP, segment) => {
                numIP = numIP << 8;
                return numIP + uint.Parse(segment);
            });


text:
Q: Prevent elements clipping when using 3D CSS transforms I am having trouble preventing two elements clipping when using 3D CSS transforms. Has anyone come across this before and found a solution?
I have attached a screenshot from the latest version of iOS to illustrate the issue - It also occurs on the desktop version of Safari, but not Chrome on OS X.
I understand why this happens, and even that this is the correct behaviour in some circumstances, but it is inconsistent across different browsers.
Thanks for any help :)

A: This is caused by rendering both elements within the same 3d layer. The solution is to render them each in their own layer.
This is a simplified version of the code which caused the issue:
CSS:
.wrapper {
    transform-style: preserve-3d;
    perspective: 1000;
}

.rotate {
    width: 100px;
    height: 100px;
    background: grey;
    transform: rotateX(45deg);
}

.clipped-element {
    width: 30px;
    height: 30px;
    background: blue;
}

HTML:

By using transform-style and perspective I've created a rendering layer. As the .clipped-element is part of this layer it exists in the same 3d space.
By moving the clipped element into it's own layer it exists in it's own 3d space and the clipping issue is avoided.
CSS:
.wrapper {
    width: 200px;
    height: 200px;
}

.rotate__wrapper {
    width: 100%;
    height: 100%;
    transform-style: preserve-3d;
    perspective: 1000;
}

.rotate {
    width: 100px;
    height: 100px;
    background: grey;
    transform: rotateX(45deg);
}

.clipped-element {
    width: 30px;
    height: 30px;
    background: blue;
}

HTML:

I've created an example on CodePen.


text:
Q: Using dot memory API to take multiple snapshot on same .dmv file I am trying to profile my specific code using dot memory api. When I call the dump() method my expectation is to take snapshot and save it to dir.
I am trying to take two snapshot here one before executing my code and after executing my code by calling dump() method.
Is it possible to create the both snapshot in the same output file as we option to do it from Stand alone dot memory?
Appreciate your suggestion. following is the code snippet
SelfAttach.Attach(new SaveSnapshotProfilingConfig
{
   ProfilingControlKind = ProfilingControlKind.Api,
   SaveDir = "D:\\SelfProfiling",
   RedistDir = "D:\\Softwares\\JetBrains.Profiler.SelfSdk.2017.2.2",
   ProfilingType = ProfilingType.Memory,
   ListFile = "D:\\snapshot_list.xml"
});

while (SelfAttach.State != SelfApiState.Active)
{
     Thread.Sleep(250);  // wait until API starts
}

if (MemoryProfiler.IsActive)
{
   MemoryProfiler.Dump();
   MyMethodTobeProfiled();
   MemoryProfiler.Dump();
}

if (MemoryProfiler.CanDetach)
   MemoryProfiler.Detach();

A: I guess you can use dotMemory Command Line Profiler instead of "Self profiling" API to reach your needs.
Launch dotMemory command line profiler.
Determine that profiler is already attached to your app, for that you need to analyze dotMemory CLT process output.
So, pseudo code to get what you need
dotMemory.exe attach --service-output --use-api "your_app_PID"

// then the message will be printed to output
// ##dotMemory["connected",{"pid":your_app_PID,"name":"your_app_NAME.exe"}]
wait for this message

// the rest of your code remains the same
// and you need only JetBrains.Profiler.Windows.Api.dll
// no more need JetBrains.Profiler.Windows.SelfApi.dll
if (MemoryProfiler.IsActive)
{
    MemoryProfiler.Dump();
    MyMethodTobeProfiled();
    MemoryProfiler.Dump();
}

if (MemoryProfiler.CanDetach)
   MemoryProfiler.Detach();

Read more about dotMemory command line profiler here

A:
Is it possible to create the both snapshot in the same output file as we option to do it from Stand alone dot memory?

A snapshot is normally a bunch of files. .dmw is an archive of a snapshot. This is the design now. The reason is to ability to start sending a snapshot immediately to a remote host. This is the R# requirement.


text:
Q: `pydot` failed to call GraphViz.Please install GraphViz and ensure that its executables are in the $PATH My jupyter server is running in a gcp deep learning vm.
I'm trying to print the model in a Jupyter notebook cell.
import os, sys
from utils.models.alexnet import alexnet
from keras.utils.vis_utils import plot_model
from keras.optimizers import SGD

model = alexnet(len(class_names))
model.summary()
plot_model(model, to_file="alexnet_model.png", show_shapes=True)

I get this error
`pydot` failed to call GraphViz.Please install GraphViz ([https://www.graphviz.org/](https://www.graphviz.org/)) and ensure that its executables are in the $PATH.

I have correctly installed Graphviz in my machine with
apt-get install graphviz
stat /usr/bin/dot
  File: /usr/bin/dot
  Size: 10568       Blocks: 24         IO Block: 4096   regular file
Device: 801h/2049d  Inode: 142872      Links: 1
Access: (0755/-rwxr-xr-x)  Uid: (    0/    root)   Gid: (    0/    root)
Access: 2020-02-10 11:48:19.416617639 +0000
Modify: 2017-02-19 10:32:17.000000000 +0000
Change: 2019-12-13 01:47:41.084977709 +0000

The python packages pydot, pydot-ng, pydotplus are also installed.
This is my path variable
echo $PATH
/usr/local/cuda/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games

/user/bin is included here.
EDIT
When executed in a jupyter notebook shell.
print(os.environ["PATH"])

/usr/local/cuda/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games
Another wierd thing
I have a simple image dataset with 3 classes and altogether around 2000 images. In my jupyter notebook I first process and load the images into memory. Creating the model and printing it comes next. With the simple dataset it works without error. This happens when I work with large datasets.

A: I was also getting the same thing so i install conda install python-graphviz
after conda install pydot

A: I have the same problem, I solved it by following the Answer of Prerna Verma. By the way, there are three steps for using graphviz in Linux Envs:

*

*sudo apt-get install graphviz (download and install graphviz, if you are a Windows User)

*conda install pydot

*conda install python-graphviz
then, you can use it!

A: conda installs only binary files of graphviz, but you need to install Python dependencies also. So install both of them with:
conda install graphviz

conda install python-graphviz

A: This solved the issue for me :
sudo apt install python-pydot python-pydot-ng graphviz

refer issue in : https://github.com/WillKoehrsen/Data-Analysis/issues/36


text:
Q: Matlab subplot linkaxes is not lining up the axes as expected I can't seem to get linkaxes to work (code is below). I am trying to get the subplots to line up, such that visually the x-axis is has the same range and width for both subplots. The misalignment is in both the pop-up figure window and the saved JPG. Using Matlab R2018a.
Here is my code, and below is what the figure looks like:
x1 = [27247 26973 27265 28924 27182 27430 26534 26839 7876 26484 29787 26934 27218 25777 27801 8250 34820 7980 26927 34639];
y1 = [-2350 -3334 -2948 -2336 -2778 -2813 -3383 -3635 -31 -3334 -4216 -3284 -2271 -2477 -2058 375 -821 351 -3441 -1108];

ax1 = subplot(2,1,1);
scatter(x1, y1)
box on
grid on
axis equal
xlims = get(gca, 'XLim')
ax = gca;
ax.XRuler.Exponent = 0;
ax.YRuler.Exponent = 0;
xlims = get(gca, 'XLim')
ax2 = subplot(2,1,2);
scatter(x1, y1)
xlim(xlims)
box on
grid on
ax = gca;
ax.XRuler.Exponent = 0;
linkaxes([ax1,ax2],'x')

I've also tried this (below), but it doesn't change the plot.
% adding this to the first subplot:
xlims = get(gca, 'XLim')
positioning = get(gca,'position');
% adding this to the second subplot:
xlim(xlims)
set(gca, 'position', [positioning(1) positioning(2)/5 positioning(3) positioning(4)]) %x y width height

And here is what the figure looks like:

A: This was solved on the Matlab forums, and here is a summary/application of the solution:
x1 = [27247 26973 27265 28924 27182 27430 26534 26839 7876 26484 29787 26934 27218 25777 27801 8250 34820 7980 26927 34639];
y1 = [-2350 -3334 -2948 -2336 -2778 -2813 -3383 -3635 -31 -3334 -4216 -3284 -2271 -2477 -2058 375 -821 351 -3441 -1108];

ax1 = subplot(2,1,1);
scatter(x1, y1)
box on
grid on
axis equal
xlims = get(gca, 'XLim')
ax = gca;
ax.XRuler.Exponent = 0;
ax.YRuler.Exponent = 0;
xlims = get(gca, 'XLim')
ax2 = subplot(2,1,2);
scatter(x1, y1)
xlim(xlims)
box on
grid on
ax = gca;
ax.XRuler.Exponent = 0;
set(gcf,'Resize','off') %%%%%%%% this line fixes it for some reason!
linkaxes([ax1,ax2],'x') % want to link x-axis only

%figOut = 'test';
%print(figOut, '-r300', '-djpeg')


text:
Q: Word for displaying the percentage of works hours logged by employee In a project we need to display percentage of work done by the employee. For example in a week of 40 hrs, employee only logged in 20 hrs of work. Then we need to display 50%. That percentage can be either due to employee not completing the task or no task assigned. Can you please suggest a suitable word for this.

A: *

*"On-task hours" - The employee's time may be spent outside the system.

*"Work hours" - As far as the system is concerned, it is work hours.

*simply: "Hours" - Best not to quibble over details when it comes to systems, let the person analysing the stats do that!

A: The employee was unutilized. It means not used or not used effectively.
Or
The employee was mismanaged. It means to manage badly or wrongly.
The first word doesn't assign blame but the second reeks of the fact that someone was responsible for this bad management.

A: I work in an Agile Lifecycle Management of a Project. We define every individual's man-hours as their CAPACITY. If an employee can give 50% of his time and is on a leave for one day,

we say his capacity is 50% of (40 - 8) = 16 hours

So I believe the word you are looking for is CAPACITY


text:
Q: Why do I not get an out of range error here? I'm learning python and I was trying to write a function that checks whether the number 6 is within the first 4 items of a given list.
I was surprised that this code works:
def first3(list):
    for item in list[0:3]:
        if item == 6:
            return True
    return False

print(first3([1, 2, 6, 3, 4])) # True
print(first3([1, 2, 3, 4, 6])) # False
print(first3([1, 2, 3, 4, 5])) # False
print(first3([1,2,6,3,0,0])) # True
print(first3([1,2,3,3,0,6])) # False
print(first3([6])) # True
print(first3([])) # False

I expected an out of range error for lists with less than 4 items. (EDIT: I was mistaken - has nothing to do with inside or outside the function)I tried around and found out, that outside of a function definition, there will be an out of range error.
This must be a super basic question but I didn't mange to get the google query right for an answer. Can anyone shed some light on how this is handled?
I'm using Python 3.9.2 if that matters.
Thanks a lot!


text:
Q: fetching JSON data by spark-SQL When i try to fetch the nested JSON data by using Spark-SQL query:
SparkContext sc = new SparkContext(new SparkConf().setAppName("sql").setMaster("local"));
SQLContext  sqlContext = new SQLContext(sc);
DataFrame df = sqlContext.read().json("path_to_s3_bucket").cache();
df.registerTempTable("table_name");
DataFrame d=sqlContext.sql("Select address.state as state from table_name");

I am getting th following exception
Exception in thread "main" org.apache.spark.sql.AnalysisException: Can't extract value from address

My Json data is like:-
"address":{"city":"xyz","state":"abc","country":"pqr"}

Please help in resolving the issue.

A: Your json is invalid. It should be:
                                                                                {"address":{"city":"xyz","state":"abc","country":"pqr"}}


text:
Q: spring boot scanning and injecting external non-spring beans What does it take, or is it even possible for Spring to scan and inject non-spring annotated classes? For example.
resource.jar
com.project.resource.ResourceInterface
com.project.resource.StandardResource <-- concrete implementation

@Singleton <--- Standard CDI annotation
public class StandardResource implements ResourceInterface{
    @Override
    public void something(){}
}

Now let's say I have a spring boot application which depends on resource.jar.
com.project.resource.SpringApp
@SpringBootApplication(scanBasePackages = {"com.project"})
@EnableAutoConfiguration
public class SpringApp{
    ... initializer
    @Inject
    private ResourceInterface resourceService; <--- this is not found
}

Is this supposed to work out of the box? Is this even possible? I'm using spring boot 2.0.0.RELEASE. I'm getting the following error:
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'MainController': Unsatisfied dependency expressed through field 'resourceService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.project.resource.ResourceInterface' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@javax.inject.Inject()}

Thanks

A: For Spring framework @Singleton has no meaning, as such even if class is picked up by component scanning it's going to be ignored. In order for Spring to recognize your class you can:

*

*Create a configuration class in com.project.resource with @Bean of
ResourceInterface and instantiate it as StandardResource.

*Since you are using Spring Boot you can create Auto-configuration (which will be similar to the first option) in resource.jar. You can follow examples
from creating autoconfiguration. With this approach no changes needed in com.project.resource

After that your spring boot app will run normally


text:
Q: Rollback transaction after commit in rails Can I rollback record after successfully saved?
Lets I have a user model with attribute name,email and so on.
For ex.
u=User.new
u.name="test_name"
u.email="test@email.com"
u.save

Now record will be successfully saved in database after that I want to rollback my transaction (not destroy or delete). Have any idea?

A: You can do this with transactions, see http://markdaggett.com/blog/2011/12/01/transactions-in-rails/
Example:
User.transaction do
  User.create(:username => 'Nemu')
  raise ActiveRecord::Rollback
end

A: You can run console in sandbox mode
$> rails c --sandbox

*

*On exit all changes rollback to the point of enter.

A: There's also a gem called PaperTrail that we've been using with great success.  It might do a little more than you want.

PaperTrail lets you track changes to your models' data. It's good for
  auditing or versioning. You can see how a model looked at any stage in
  its lifecycle, revert it to any version, and even undelete it after
  it's been destroyed.

https://github.com/airblade/paper_trail
No affiliation.


text:
Q: how to set chip select for ds3234 We are writing an spi driver. How can I set the "chip select pin" for linux ds3234 driver? Name of the functions or the header file that can help would be appreciated.

A: The chip select pin gets set in the board file that probes the driver, not the driver code itself. For example, if you were writing this SPI driver for the Beagleboard you would edit the board-omap3beagle.c file which is located in /arch/arm/mach-omap2. The edit should include a new struct that contains the modalias of the driver, the bus number and the chip select number. For example:
static struct spi_board_info mcspi_board_info[] = {
    // spi 3.0
    {
        .modalias   = "driver1",
        .max_speed_hz   = 5000000, // 5 Mbps
        .bus_num    = 3,
        .chip_select    = 0,
        .mode = SPI_MODE_0,
    },

    // spi 3.1
    {
        .modalias   = "driver2",
        .max_speed_hz   = 5000000, //  Mbps
        .bus_num    = 3,
        .chip_select    = 1,
        .mode = SPI_MODE_3,
    },
};

And then in the __init function register the driver as follows:
spi_register_board_info(mcspi_board_info,ARRAY_SIZE(mcspi_board_info));

When you call this register function, the probe function of the driver is called. Check out the doc in /Documentation/spi. If you want to just write a userspace implementation you can use the spidev interface. This is documented in /Documentation/spi also.


text:
Q: C++ namespace function definition only has static keyword I understand that a static namespace function may be declared static, and the static keyword omitted from the definition of the function. What I have is the opposite, e.g.:
// in foo.h
namespace Foo
{
    void bar();
}

// in foo.cpp
static void Foo::bar()
{
}

Does the static keyword have any effect here, or is it simply ignored? It compiles either way, and the functions are available to other translation units.

A: The given program is ill-formed as can be seen from dcl.stc which states:

The linkages implied by successive declarations for a given entity shall agree. That is, within a given scope, each declaration declaring the same variable name or the same overloading of a function name shall imply the same linkage.

(end quote)
Now, lets apply this to your example.
// in foo.h
namespace Foo
{
    void bar(); //#1 external linkage
}

// in foo.cpp
static void Foo::bar()  //#2 tries to give Foo::bar internal linkage
{
}

In the above code, the first declaration #1 of bar gives it external linkage while when implementing it in the source file(foo.cpp) in #2, you're trying to give it internal linkage. And so according to the above quoted statement, the given example is not valid.


text:
Q: got error while fetching an image I have faced this error:

Thread 1: signal SIGABRT error I got in 3rd override function in cell declaration
Could not cast value of type 'UICollectionViewCell' (0x10d27aa18) to 'collection.viewcell' (0x10a431130).

extension PhotoCollectionViewController {

    override func numberOfSections(in collectionView: UICollectionView) -> Int {

        return searches.count
    }

    //2
    override func collectionView(_ collectionView: UICollectionView,
                                 numberOfItemsInSection section: Int) -> Int {
        return searches[section].searchResults.count
    }

    //3
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! viewcell
        //2
        let flickrPhoto = photoForIndexPath(indexPath: indexPath)
        print(flickrPhoto)
        cell.backgroundColor = UIColor.white
        //3
        //cell.imageview.image = flickrPhoto.thumbnail
        return cell
    }
}

A: Change the viewcell to UICollectionViewCell
 let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! UICollectionViewCell

If you want to use custom cell the first register and use.
Make sure registerClass and dequeueReusableCell are the same class to solve the problem.
self.registerClass(viewcell.self, forCellWithReuseIdentifier: reuseIdentifier)

let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! viewcell

This will help.


text:
Q: problem with forward message method in telegram bot I am trying to forward a message in telegram bot API in python . It shows "Bad Request: chat_id is empty" despite using same chat_id in sendMessage and works perfectly fine.
https://api.telegram.org/bot{BOT_TOKEN}/forwardMessage?chat_id={CHAT_ID}&from_chat_id={ID}&message_id={MID}

my problem is what is the message id and how can i find it?
for example chat id is like this number 123456789.
what does message id look like ?

A: You are a bot. So, people interact with you (directly or in a group). When a message is sent to your bot, you would receive a callback that includes the message details (including the chat_id, the sender chat id, the message id, and all other details). Something like this (see message->message_id and message->from_id):
{
   "update_id":1111,
   "message":{
      "message_id":111,
      "from":{
         "id":1111,
         "is_bot":false,
         "first_name":"...",
         "last_name":"...",
         "username":"...",
      },
      "chat":{
         "id":1111,
         "first_name":"...",
         "last_name":"...",
         "username":"...",
         "type":"private"
      },
      "date": 1111,
      "text":"...."
   }
}

So, you can store those details and use them to forward that message to another chat. In each chat (unique chat id), each message has a chat id (which is usually an incremental number) and by these two identifier, you can uniquely select which message from which chat should be forwarded.

A: Depends on where you want to access a chat_id, you can use different ways.
if you want to send a specific message to a user or bot that you don't know his chat_id, you can print a message from that user and access chat_id. Or simply forward a message from that user to @ShowChatIdBot and it returns you the related chat_id.
In fact this bot extract data from your forwarded message and gives back chat_id in that message to you.


text:
Q: Using Exceptions in Transformer Monad I have a question regarding use of Exceptions with a transformer stack.
I am a trying to develop some networking software, specifically implement
the GTP control protocol on S5 interface.
I am finding it difficult to get Exceptions work the transformer stack.
import Control.Monad (unless)
import Control.Exception
....
import Control.Monad.Trans.State.Strict
import Control.Monad.Trans.Except
...
data GtpcModSt = GtpcModSt { sock             :: Socket
                       , rcvdBytes        :: BS.ByteString
                       , s5cTeidKey     :: Word32
                       ---- ....
                       } --deriving (Show)

type EvalGtpC a = (StateT GtpcModSt (ExceptT GtpcExceptions IO )) a
                  -- deriving (Functor, Applicative, Monad)

gtpcProcess = loop
       where loop = do
             rcvAndProcessGtpc   `catch` (\e -> do
                                      print "Exception handler"
                                      print (e :: SomeException))
            loop

 rcvAndProcessGtpc ::  EvalGtpC ()
 rcvAndProcessGtpc = do
                    sock <- gets sock
                    (msg, addr) <- liftIO $ recvFrom sock 1000
                    modify (\x -> x {rcvdBytes = msg, sndrAddr = addr})
                    processMsg
processMsg :: EvalGtpC ()
 processMsg = do
            --  validateSrc
           -----
          --....
            msg <- gets gtpMsg
            processGtpc $ msgType msg

 -- createSessionRequest
  processGtpc :: Word8 -> EvalGtpC ()
  processGtpc 32 = do
         myState@GtpcModSt {..} <- get
         .....

         sessParams <- return $ foldl ieInfo (SessionParams { imsi = Nothing
                              , mei = Nothing
                              , msisdn = Nothing
                              , senderFteidKey = Nothing
                              , senderIpV4Addr = Nothing
                              , senderIpV6Addr = Nothing
                              , pgwFteidKey      = Nothing
                              , pgwIpV4Addr   = Nothing
                              , pgwIpV6Addr   = Nothing
                              , apn           = Nothing
                              , paaPdnType    = Nothing
                              , pco           = Nothing
                              , bearerContext = []
                              , unDecodedIe   = []
                              , unSupportedIe = []
                              }) $ msgIeList gtpMsg

        ueApn <-return $ fromMaybe (throwE BadIe) (apn sessParams)
        apnCfg <- return $ fromMaybe (throw BadIe) $ Map.lookup ueApn apnProfile
        thisSndrFteidKey <-return $  fromMaybe (throw BadIe) (senderFteidKey sessParams)

I think that I should use throwE/catchE from Control.Monad.Trans.Except. However, throwE does not even compile when used with my transformer monad, as shown here:
apnCfg <- return $ fromMaybe (throw UnknownApn) $ Map.lookup ueApn apnProfile

Using throw from Control.Exception gets past the compilation stage but I am not sure it will work.
 Should I not be using Exception in a transformer monad that has IO as its base?

A:
I think that I should use throwE/catchE from Control.Monad.Trans.Except. However, throwE does not even compile when used with my transformer monad, as shown here:
apnCfg <- return $ fromMaybe (throw UnknownApn) $ Map.lookup ueApn apnProfile

Using throw from Control.Exception gets past the compilation stage but I am not sure it will work.

This can be solved by following the types. In your do-block, we have:
-- I won't use the synonym here, for the sake of explicitness:
return :: a -> StateT GtpcModSt (ExceptT GtpcExceptions IO) a

The type of throwE is:
throwE :: Monad m => e -> ExceptT e m a

That being so, what you want is:
apnCfg <- maybe (lift $ throwE UnknownApn) return $ Map.lookup ueApn apnProfile

Firstly, you only need return if you aren't throwing (maybe is more convenient than fromMaybe for expressing that). Secondly, throwE produces an ExceptT computation that you need to lift to the outer, StateT layer. You can make the lift implicit by using mtl instead of transformers directly. To do that, change your imports from...
import Control.Monad.Trans.State.Strict
import Control.Monad.Trans.Except

... to:
import Control.Monad.State.Strict
import Control.Monad.Except

Then you can simply write (using the throwError method from MonadError):
apnCfg <- maybe (throwError UnknownApn) return $ Map.lookup ueApn apnProfile


text:
Q: nsExtendOutput1Line Fails with SNMPD on Debian Wheezy I've been trying to set up a a few SNMP extensions. Here's a sample entry from /etc/snmp/snmpd.conf on my target host:
extend php_pids /var/skotos/cacti/check-proc lsphp5

The program works fine:
#  /var/skotos/cacti/check-proc lsphp5
There are 26 lsphp5 processes.

However, when I go to my cacti server, I get errors:
snmpwalk -c <community> <site> 'NET-SNMP-EXTEND-MIB::nsExtendOutput1Line."php_pids"'

NET-SNMP-EXTEND-MIB::nsExtendOutput1Line."php_pids": Unknown Object Identifier

(I get timeouts from Cacti, but I figured snmpwalk would take out the middle man.)
Everything else works fine for Cacti on the server and for SNMP on the target, but for some reason I can't get nsExtendOutput1Line to work at all.
This is a very fresh Debian Wheezy 7.4 isntallation.

A: Due to licencing issues MIB database was removed from the libsnmp-base sometime ago, so currently your client cannot translate the names to OIDs. You can query the snmpd server using the object identifier directly, by: (asking for first line of the output)
snmpwalk -c <community> <site> 1.3.6.1.4.1.8072.1.3.2.3.1.1

Alternatively you can install the package snmp-mibs-downloader which is in the non-free repository.
apt-get install snmp-mibs-downloader

It should download the database automatically, but if for some reason it doesn't just run the "download-mibs" script. After the database is properly downloaded the command:
snmpwalk -c <community> <site> 'NET-SNMP-EXTEND-MIB::nsExtendOutput1Line."php_pids"'

should just work.


text:
Q: Spectrum of rotation matrices Given an $n$-tuple $(e^{i\theta_j})_{j=1}^n$ of $n$ points on the unit circle in $\mathbb{C}$, what are the necessary and sufficient conditions that guarantee the existence of a rotation matrix $R\in SO(n)$ such that the spectrum of $R$ is $\{e^{i\theta_1},\ldots,e^{i\theta_n}\}$?
I realize that $\sum_{j=1}^n\theta_j=0$ because of the constraint $\det R=1$. Is it also sufficient? Here is where I get stuck. In particular, if I form the spectral decomposition $Q=U\Lambda U^*$, where $\Lambda=diag(e^{i\theta_j})_{j=1}^n$ and U is some unitary matrix, how can I know that there always exists a $U$ such that $Q$ is real?

A: The complex (non-real) eigenvalues of a real matrix must come in conjugate pairs. Hence, a matrix $R \in \operatorname{SO}(n)$ must have a spectrum of the form
$$ z_1, \overline{z_1}, \dots, z_k, \overline{z_k}, x_1, \dots, x_{n-2k} $$
where $0 \leq 2k \leq n$, $|z_i| \in S^1 \setminus \{ \pm 1 \}$, $x_i \in \{ \pm 1 \}$ and $\prod_{i=1}^{n-2k} x_i = 1$. Conversely, given a list satisfying the conditions above, one can always build a matrix $R$ is precisely that list by taking the block diagonal matrix
$$ R = \operatorname{diag}(R(z_1), \dots, R(z_k), x_1, \dots, x_{n-2k}) $$
where each $R(z_i) \in \operatorname{SO}(2)$ is the $2 \times 2$ rotation matrix given by
$$ R(z_i) = \begin{pmatrix} \Re(z_i) & -\Im(z_i) \\ \Im(z_i) & \Re(z_i) \end{pmatrix}. $$

A: A diagonalizable complex matrix is similar to some matrix with real entries if and only if its eigenvalues come in conjugate pairs.
In your notation, you must be able to partition your $\theta$'s into pairs of the form $\pm \theta$, except in the case where $\theta = 0$.
If we were looking for elements of $O(n)$, we could also have an odd number of $\theta$s equal to $\pi$.


text:
Q: Besides web, which tool I can browse files from git? I am coming from Perforce. It allows me to browse the files stored in the server by using p4v. I am wondering if there is similar GUI tool for git.

A: With git, there's really no need for such a tool. Just fetch changes from the server and browse locally.

A: If you just want to see files instead of checking them out, you can use git show ${revision}:path/to/file, where ${revision} could be a commit id, a branch name, a tag name...
You can install and use tig, too, which is a curses client for git. Typing t you can browse the tree a commit refers.
Finally, you can just checkout a file/directory from a given revision, but that would of course make your working directory to differ from the index. You can do this via git checkout ${revision} -- path/to/file.

A: In general you should just check out the revision you want to look at, by using git checkout %revision%. If that is too slow you are probably doing something wrong ;).
To look at a specific file in a given revision, use git show %revision%:filename. This also works for looking at directories, e.g. git show head^:./
If you want a gui for doing this, use the included git gui. Repository > Browse Branch files is what you're looking for.


text:
Q: Print control identifiers for Network and Sharing Center I am looking for a way how to change the IP address of a network adapter by a script. I am trying pywinauto.
I managed to open the Network and Sharing Center from Windows Control panels. Now I am looking for a way to click on the Change adapter settings link to get the list of my network adapters:

So I tried to print the control identifiers of this window by .print_control_identifiers()
import pywinauto

network_cpl = pywinauto.Application(backend="uia").start('control /name Microsoft.NetworkAndSharingCenter')
dlg = network_cpl["Network and Sharing Center"]
dlg.print_control_identifiers()

I have checked in the live debugging console that dlg is actually the dialogue of network_cpl:
network_cpl
<pywinauto.application.Application object at 0x000000000476FDD8>
actions:<pywinauto.actionlogger._StandardLogger object at 0x0000000003BCE630>
backend:<pywinauto.backend.BackEnd object at 0x000000000539B208>
match_history:[]
process:7888
use_history:False
xmlpath:''

dlg
<pywinauto.application.WindowSpecification object at 0x0000000003C0C828>
WAIT_CRITERIA_MAP:{'active': ('is_active',), 'enabled': ('is_enabled',), 'exists': ('exists',), 'ready': ('is_visible', 'is_enabled'), 'visible': ('is_visible',)}
actions:<pywinauto.actionlogger._StandardLogger object at 0x0000000003BCE828>
backend:<pywinauto.backend.BackEnd object at 0x000000000539B208>
criteria:[{'backend': 'uia', 'best_match': 'Network and Sharing Center', 'process': 7888}]

I see that the process ID of the dlg WindowsSpecification object is the same as the process ID of the network_cpl Application object. Yet when I execute dlg.print_control_identifiers() I get this:
Exception has occurred: pywinauto.findwindows.ElementNotFoundError
{'best_match': 'Network and Sharing Center', 'backend': 'uia', 'process': 7888}

A: This is typical problem when launcher process spawns a child one. Automatic detection of spawning processes is planned in the future.Currently you may use
network_cpl.connect(title="Network and Sharing Center")

after starting an app. Or access it through Desktop object:
>>> from pywinauto import Desktop, Application

>>> network_cpl = Application(backend="uia").start('control /name Microsoft.NetworkAndSharingCenter')
>>> network_cpl.process
9652
>>> dlg_desktop = Desktop(backend="uia")["Network and Sharing Center"]
>>> found_dlg = dlg_desktop.wrapper_object()
>>> found_dlg.process_id()
15520


text:
Q: JQuery not acting as it should I am trying to make a "drop down" menu where you click a div and the sibling below it will become visible or disappear. It should be extremely simple, but it is giving me trouble for some reason.
$(".dropDownClick").click(function(){
    alert($(self));
    $(self).next().css("display",(node.css("display")=="inline")?"none":"inline");
});

This code returns [object Object] and then doesn't change the display css of the next sibling. After a bit of testing I found that $(self).next(); will actually break the code (if I try to do something like alert($(self).next()); the code will not execute). I am assuming this is because there is no next sibling? But my HTML would suggest otherwise:

Drop

1

2

Shouldn't the div with the class "dropDown" be selected when I call .next()?

A: it should be this not self, also you can use .toggle() instead of manually applying the display value
$(".dropDownClick").click(function () {
    $(this).next().toggle();
});

this is a special variable, which is always available - but self/node are custom variables which has to be declared before using else it will throw a reference error
Demo: Fiddle


text:
Q: Cutting out a mask from a image with ImageMagick I'm trying to cut out a shape from an image based on a mask I have. I tried a number of ways but I'm really struggling to get the result I need.
I'm using ImageMagick 7.1.0-51 Q16-HDRI on Windows.
The "base" image:
https://imgur.com/a/j1kioWu
The mask i'm using:
https://imgur.com/a/OcArICa
Expected result(photoshoped):
https://imgur.com/a/GjRoxyS
Edit: Reuploaded direct on imgur to maintain transparent background

A: In Imagemagick, you want to invert (negate) the polarity of black and white, then do a -compose difference -composite, then invert again.
Hair:

Face:

magick hair.png face.png -alpha off -colorspace gray -negate -compose difference -composite -negate result.png

Result:

If you want pure white in the face area, threshold the two images after the conversion to grayscale
magick hair.png face.png -alpha off -colorspace gray -auto-threshold otsu -negate -compose difference -composite -negate result2.png
Result 2:

ADDITION
If your input images have transparent backgrounds, then you have to extract the alpha channels, combine them to do the difference and then put that alpha channel back on the input.
Unix Syntax:
magick hair.webp \
\( +clone face_mask.webp -alpha extract -compose difference -composite \) \
-alpha off -compose copy_opacity -composite result.png

For Windows,remove the \ in front of the parentheses and change the end of line \ to ^.


text:
Q: Loading Hibernate properties outside context isn't working I'm facing some strange problem here and right now I'm stuck. I've read some other posts on this regards and some of then helped me to configure my enviroment, but for some reason that I couldn't find out why it is not working.
I need to place the hibernate.connection.url, hibernate.connection.username and hibernate.connection.password properties outside my WAR file to make easier to configure theese parameters when the system is deployed on different servers. So after digging over the Google I find this solution:
applicationContext.xml:
...
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

<bean id="sessionFactory" class="br.myapp.DataBaseConfig"/>

And the class DataBaseConfig
public class DataBaseConfig extends AnnotationSessionFactoryBean {
    private final BaseConfig baseConfig = new BaseConfig();

    public DataBaseConfig() {
        super();
    }

    @Override
    protected SessionFactory buildSessionFactory() throws Exception {
        Properties dbConfig = new Properties();
        dbConfig = baseConfig.getPropertiesFile("myPropertiesFile");

        Configuration config = new Configuration();
        Enumeration<Object> props = dbConfig.keys();

        while ( props.hasMoreElements() ){
            String key = (String)props.nextElement();
            config.setProperty( key , dbConfig.getProperty(key) );
        }
        config.addResource("hibernate.cfg.xml");

        SessionFactory sessionFactory = config.buildSessionFactory();
        return sessionFactory;
    }
}

And my hibernate.cfg.xml file looks like:
<hibernate-configuration>
    <session-factory>
        <mapping class="br.myapp.model.SomeClass1" />
        <mapping class="br.myapp.model.SomeClass2" />
        <mapping class="br.myapp.model.SomeClass3" />
    </session-factory>
</hibernate-configuration>

My myPropertiesFile is:
hibernate.connection.driver_class=oracle.jdbc.driver.OracleDriver
hibernate.connection.url=jdbc:oracle:thin:@localhost:1524:MyDB
hibernate.connection.username=user
hibernate.connection.password=passpass
hibernate.default_schema=myschema
hibernate.connection.oracle.jdbc.V8Compatible=true
hibernate.show_sql=true
hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
#I'm usign c3p0 to pool connections
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.timeout=300
hibernate.c3p0.max_statements=50
hibernate.c3p0.idle_test_period=3000
hibernate.cache.use_second_level_cache=true
hibernate.cache.use_query_cache=true
hibernate.cache.region.factory_class=net.sf.ehcache.hibernate.EhCacheRegionFactory

With this enviroment when I'm trying to get something from the database without success on this way:
final SomeClass1 sm = repository.find(SomeClass1.class)
            .where( Restrictions.eq( "someField" , varFromWebForm ) )
            .uniqueResult();

But sm always returns null, and on the console there is no query printed even with hibernate.show_sql=true setted.
The strange thing is that when I change the configurations on my applicationContext.xml file like this
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="configLocation">
        <value>classpath:/hibernate.cfg.xml</value>
    </property>
</bean>

And the hibernate.cfg.xml file to this
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1524:MyDB</property>
        <property name="hibernate.connection.username">user</property>
        <property name="hibernate.connection.password">passpass</property>
        <property name="hibernate.default_schema">myschema</property>
        <property name="hibernate.connection.oracle.jdbc.V8Compatible">true</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
        <property name="hibernate.c3p0.min_size">5</property>
        <property name="hibernate.c3p0.max_size">20</property>
        <property name="hibernate.c3p0.timeout">300</property>
        <property name="hibernate.c3p0.max_statements">50</property>
        <property name="hibernate.c3p0.idle_test_period">3000</property>
        <property name="hibernate.cache.use_second_level_cache">true</property>
        <property name="hibernate.cache.use_query_cache">true</property>
        <property name="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.EhCacheRegionFactory</property>
        <mapping class="br.myapp.model.SomeClass1" />
        <mapping class="br.myapp.model.SomeClass2" />
        <mapping class="br.myapp.model.SomeClass3" />
    </session-factory>
</hibernate-configuration>

All works fine. So it is like the code that read the properties and inject it on the Configuration to Hibernate (DataBaseConfig) is not working properly.
Can someone point me out what am I doing wrong?
UPDATE:
There is no exceptions on the console. it just doesn't work.
UPDATE 2
This is the log from the apache server. I'm using VRaptor as controllerManager and the only things that appear when I call my method to do the query is the requisition to the controller nothing else, therefore I think that it is not important to put it here.
I've try to put the log here but the SO doesn't let me because it extrapolate the characters limit for a question so, here is a link to pastebin: http://pastebin.com/cASD7EPu
Thanks.

A: When you say (DataBaseConfig) is not working properly : Do you have somes Exceptions and a StackTrace returned by the Spring Container. Try To launch your app in debug/trace mode to see what happen exactly.

A: I've managed to solve my own question by changing the way I read the configurations. The waqy I was doing does not work and I couldn't find out why. Which is like this:
@Override
protected SessionFactory buildSessionFactory() throws Exception {
    Properties dbConfig = new Properties();
    dbConfig = baseConfig.getPropertiesFile("myPropertiesFile");

    Configuration config = new Configuration();
    Enumeration<Object> props = dbConfig.keys();

    while ( props.hasMoreElements() ){
        String key = (String)props.nextElement();
        config.setProperty( key , dbConfig.getProperty(key) );
    }
    config.addResource("hibernate.cfg.xml");

    SessionFactory sessionFactory = config.buildSessionFactory();
    return sessionFactory;
}

So I was reading the Hibernate#Configuration docs and find the method configure(File file). Then I took the hibernate.cfg.xml out of my context and put it on my configs directory (which I get from a Util class of my project) and it work fine. The final method is like:
@Override
protected SessionFactory buildSessionFactory() throws Exception {
    Configuration config = new Configuration();
    config.configure(
             new File( BaseConfig.CONFIG_BASE
                        + File.separator
                        + "hibernate.cfg.xml" )
    );
    SessionFactory sessionFactory = config.buildSessionFactory();
    return sessionFactory;
}

And now it is working fine. I would like to find out why the previous configuration did not work to understand. This is not the best solution but solved my problem.
I've a friend here that always says: "It isn't an ugly solution until someone else show a better one!". So for now I will stick with this one.
Thanks to the ones who came here and tryied to help me.
I will not mark this answer as the right one for some time to see if someone else can show me a better solution :)


text:
Q: Nested Group BY Sql Query I have following three tables in my sql server db
1 ->    GroupList
GroupID || GroupName

2 ->    MachineList
MachineID   || GroupID  || MachineName

3 ->    CaptureLogs
LogID   || MachineID    || VoilationWord

I need a query to get the following report
GroupName   || MachineCountInGroup  || TotalLogCountByMachinesInGroup

Guys, Please help me out.

A: You can
  select GroupName ,
    (select count(1) from  MachineList where GroupID = grp.GroupID ) as
     MachineCountInGroup   ,
   (select count(1) from  MachineList
   inner join  CaptureLogs
   on  CaptureLogs.MachineID=MachineList .MachineID
   where GroupID  = grp.GroupID ) as TotalLogCountByMachinesInGroup
   from  GroupList grp

I am sure that there is better way but this will work.

A: Without data it's difficult to say for sure, but I would guesstimate that something like this might be what you're after?
SELECT
  DISTINCT gl.groupid ,
  gl.groupname,
  COUNT(ml.MachineId) OVER (PARTITION BY gl.groupid) AS MachineCountInGroup,
  COUNT(cl.LogId) OVER (PARTITION BY cl.MachineId) AS TotalLogCOuntBYMachinesInGroup
FROM dbo.GroupList AS gl
JOIN dbo.MachineList AS ml ON ml.groupid = gl.groupid
JOIN dbo.CaptureLogs AS cl ON cl.machineid = ml.MachineId

This will give some data that appears like:

groupname, machinecountingroup, totallogcount...
    A       3                       1
    A       3                       2
    B       2                       2

if you only want one row for A, you'll need to adjust the
COUNT(cl.LogId) OVER (PARTITION BY cl.MachineId) AS TotalLogCOuntBYMachinesInGroup
line to something like
COUNT(cl.logid) OVER (PARTITION BY gl.groupid) AS TotalLogCOuntBYMachinesInGroup
That will give you only one row for A and one for B.

A   3   3
B   2   2

So seeing as I don't know exactly what you're after, this is the best I can do (again - test data would be nice)

A: I have prepared the complete script and then the best solution for the requirement.
Script to create tables
create table GroupList
(GroupId int primary key, GroupName varchar(50) not null);

create table MachineList
(MachineId int primary key,
 GroupId int not null,
 MachineName varchar(50) not null
);

Alter table MachineList
Add foreign key(GroupId)
references GroupList(GroupId)

Create table CaptureLogs
(LogId int identity(1,1) primary key,
 MachineId int not null,
 VoilationWord varchar(50) not null
);

Alter table CaptureLogs
Add foreign key(MachineId)
references MachineList(MachineId);

Now script to insert some sample data in tables:
Insert into GroupList Values(1,'Group 1'),(2,'Group 2');

Insert into MachineList
values(1,1,'Machine 1'),(2,1,'Machine 2 of 1'),(3,2,'Machine 3 of 2'),(4,2,'Machine 4 of 2'),(5,2,'Machine 5 of 2');

Insert into CaptureLogs
    (MachineId, VoilationWord)
select MachineId, 'First Word from ' + MachineName from MachineList
union all
select MachineId, 'Second Word from ' + MachineName from MachineList
    where MachineId > 1
union all
select MachineId, 'Third Word from ' + MachineName from MachineList
    where MachineId > 2
union all
select MachineId, 'Fourth Word from ' + MachineName from MachineList
    where MachineId > 3
union all
select MachineId, 'Fifth Word from ' + MachineName from MachineList
    where MachineId > 4;

Now to get your required data, you need to run the simple code. I think it is the best for this requirement.
Select gl.GroupName, count(distinct ml.MachineId) MachineCountInGroup,
        count(LogId) TotalLogCountByMachinesInGroup from GroupList gl
        inner join MachineList ml on gl.GroupId = ml.GroupId
        inner join CaptureLogs cl on ml.MachineId = cl.MachineId
        group by gl.GroupName;

I hope it helps.

A: This will work:
SELECT
  g.GroupName,
  COUNT(DISTINCT l.MachineID) AS MachineCountInGroup,
  COUNT(*)                    AS TotalLogCountByMachinesInGroup
FROM CaptureLogs l
JOIN MachineList m ON m.MachineID=l.MachineID
JOIN GroupList   g ON g.GroupID=m.GroupID
GROUP BY g.GroupName
As an aside, I expect that counting l.MachineID provides the engine with better opportunities to optimize the access than counting m.MachineID. The 2 are identical anyway, since there is an INNER JOIN.
Tested on SQLFiddle, as I have no SQL Server installation of my own.


text:
Q: How to set environmental variable from Scala? I need to set environmental variable (PATH) from Scala.
I tried this:
val cmd = Seq("export", "PATH='bla'")
cmd.lines

but I got error:
java.io.IOException: Cannot run program "export": error=2, No such file or directory
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1041)
at scala.sys.process.ProcessBuilderImpl$Simple.run(ProcessBuilderImpl.scala:68)
at scala.sys.process.ProcessBuilderImpl$AbstractBuilder.lines(ProcessBuilderImpl.scala:140)
at scala.sys.process.ProcessBuilderImpl$AbstractBuilder.lines(ProcessBuilderImpl.scala:106)
at .<init>(<console>:12)
at .<clinit>(<console>)
at .<init>(<console>:11)
at .<clinit>(<console>)
at $print(<console>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at scala.tools.nsc.interpreter.IMain$ReadEvalPrint.call(IMain.scala:704)
at scala.tools.nsc.interpreter.IMain$Request.loadAndRun(IMain.scala:914)
at scala.tools.nsc.interpreter.IMain.loadAndRunReq$1(IMain.scala:546)
at scala.tools.nsc.interpreter.IMain.interpret(IMain.scala:577)
at scala.tools.nsc.interpreter.IMain.interpret(IMain.scala:543)
at scala.tools.nsc.interpreter.ILoop.reallyInterpret$1(ILoop.scala:694)
at scala.tools.nsc.interpreter.ILoop.interpretStartingWith(ILoop.scala:745)
at scala.tools.nsc.interpreter.ILoop.command(ILoop.scala:651)
at scala.tools.nsc.interpreter.ILoop.processLine$1(ILoop.scala:542)
at scala.tools.nsc.interpreter.ILoop.loop(ILoop.scala:550)
at scala.tools.nsc.interpreter.ILoop.process(ILoop.scala:822)
at scala.tools.nsc.interpreter.ILoop.main(ILoop.scala:851)
at xsbt.ConsoleInterface.run(ConsoleInterface.scala:57)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at sbt.compiler.AnalyzingCompiler.call(AnalyzingCompiler.scala:73)
at sbt.compiler.AnalyzingCompiler.console(AnalyzingCompiler.scala:64)
at sbt.Console.console0$1(Console.scala:23)
at sbt.Console$$anonfun$apply$2$$anonfun$apply$1.apply$mcV$sp(Console.scala:24)
at sbt.TrapExit$.executeMain$1(TrapExit.scala:33)
at sbt.TrapExit$$anon$1.run(TrapExit.scala:42)
Caused by: java.io.IOException: error=2, No such file or directory
    at java.lang.UNIXProcess.forkAndExec(Native Method)
    at java.lang.UNIXProcess.<init>(UNIXProcess.java:135)
    at java.lang.ProcessImpl.start(ProcessImpl.java:130)
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1022)
    ... 35 more

Is there some other way to do that?

A: 'export' isn't an executable, it's a shell built-in command.  If you're trying to set the path in the parent shell, well, you can't.  You can set it for a new shell that you execute.  This is really more of a unix FAQ.

A: Example from doc for sys.process.Process:
apply("java", new java.ioFile("/opt/app"), "CLASSPATH" -> "library.jar")

Edit for more helpful verbiage:
That is, you specify the env when you spawn a child process.
The environment of the current process is read-only; see System.getenv, or compare the abstractions sys.props and sys.env.
The fact that a shell augments the environment it bestows on subshells with exported variables is a shell convention.  See 3.7.4 in the bash reference, for example:

On invocation, the shell scans its own environment and creates a
  parameter for each name found, automatically marking it for export to
  child processes. Executed commands inherit the environment. The export
  and 'declare -x' commands allow parameters and functions to be added
  to and deleted from the environment. If the value of a parameter in
  the environment is modified, the new value becomes part of the
  environment, replacing the old. The environment inherited by any
  executed command consists of the shell's initial environment, whose
  values may be modified in the shell, less any pairs removed by the
  unset and 'export -n' commands, plus any additions via the export and
  'declare -x' commands.

This is the first time my answer was longer than the Daniel Sobral answer it duplicates.


text:
Q: How to determine variables that make certain cluster different from others? Say clustering was performed. My concern is to understand what characterizes certain cluster. Which variables differ most for a certain cluster? Are there any methods for performing such kind of analysis?
For example, say I have 50 variables and 10 clusters. The desired result would sound like: for a cluster 1 variables 5, 16, 23, 42 and 49 contribute to the biggest difference from other clusters.

A: You can always assume that the clusters are classes and train a classifier on that.
A decision tree classifier comes to my mind, as it will often produce a "human readable" classification tree.

A: An interesting topic to look into is Fuzzy clustering.
The idea behind fuzzy clustering is that a cluster can have elements that are more "typical" than others and therefore have a higher membership within that cluster than other members which are less "typical".
For example, a Robin would have a high value (say 0.9) for its membership in the Birds cluster, while a Penguin would have a low value (say 0.4) for its membership in the Birds cluster.
With 50 data items (and 10 clusters!) to cluster a good inference might be difficult to obtain.
A good book to read on Fuzzy Clustering and Fuzzy Logic is the following Fuzzy Sets and Fuzzy Logic: Theory and Applications by Bo and Klir, although it is a bit dated.


text:
Q: cakephp 3 unable to sort by deeply associated data We are not able to sort our transactions by deeply associated data. Mostly belongsTo and hasOne associations. Any information needed/not founded here will be posted immediately. Tables:
BcTransactions:
$this->belongsTo('Seller', [
    'className' => 'BcAccessCards',
    'foreignKey' => 'seller',
    'propertyName' => 'BcAccessCards',
]);
$this->belongsTo('Buyer', [
    'className' => 'BcUsers',
    'foreignKey' => 'buyer',
    'propertyName' => 'BcUsers',
]);

BcAccessCards:
$this->belongsTo('BcUsers', [
    'className' => 'BcUsers',
    'foreignKey' => 'user',
    'propertyName' => 'BcUsers'
]);

BcUsers:
$this->hasOne('BcUserInfos', [
    'className' => 'BcUserInfos',
    'foreignKey' => 'user_id',
    'dependent' => true,
    'propertyName' => 'BcUserInfos'
]);

We are able to retrieve all the associated data for each transaction:
$query = $bcTransactions->find('all', [
    'conditions' => ['BcTransactions.company =' => $id],
    'contain' => ['Seller', 'Seller.BcUsers', 'Seller.BcUsers.BcUserInfos', 'Buyer', 'Buyer.BcUserInfos'],
]);

Query returns perfect data set, but when it comes to sorting:
$this->paginate = [
    'contain' => ['Seller', 'Seller.BcUsers', 'Seller.BcUsers.BcUserInfos', 'Buyer', 'Buyer.BcUserInfos'],
    'sortWhitelist' => [
        'id',
        'Buyer.BcUserInfos.firstname',
        'Seller.BcUsers.BcUserInfos.firstname',
    ]
];
$this->paginate($query);

We get following URL: ?sort=Seller.BcUsers.BcUserInfos.firstname&direction=asc for example and we fail with an error: Column not found: 1054 Unknown column 'Seller.BcUsers' in 'order clause' We understand what the error means, but dont know how to fix it, how to sort by deeply associated data.

A: Sorting works via identifiers
You seem to confuse this with how for example containments or filtering by associations works, where the "path" is required in order to retrieve association information at PHP level.
Sorting doesn't work that way, it happens purely on SQL level where the associated tables are joined in via their respective aliases. It eats identifiers, which consist of just an alias and a fieldname, so you'd just refer to fields of associations as for example BcUserInfos.firstname instead of Seller.BcUsers.BcUserInfos.firstname.
Aliases must be unique when joined into a single query
Another problem you have there is that there are duplicate aliases, ie BcUserInfos is included twice, which won't work for 1:1 associations, as they are all being included in the same SQL query.
That will most likely cause problems as the query builder doesn't have a name conflict resolution that would include both associations, instead the one that was contained first will win, the following ones will simply not be included.
You'll probably have to rename them, add additional ones, or maybe even join the tables in manually.


text:
Q: GDM don't show available users list and don't switch layout Good night!
I can't login through GDM but can via terminal.
Also I can't change layout but successfully do it via terminal.
This is example of /var/log/messages endline:

gdm-simple-greeter[...]: Couldn't enumerate devices
...the permission of the setuid helper is not correct...

And this "permission of the setuid" is everywhere in GDM logs. What the problem is?

A: Apologies for just posting links but I cannot reproduce the problem myself. I hope this is useful none the less.
There is a thread on this problem on ubuntuforums.org
The solution there was

*

*log in tty1 console as root

*stop gdm

*startx

*Now if you are able to see the desktop, connect to the internet and reinstall dbus related stuff from synaptic.

Another thread suggests the following command may also work
sudo apt-get install --reinstall gnome


text:
Q: Analysing data in pandas where some values are lists of dicts I was given a stupid csv with like 20,000 rows of data pertaining to only ~300 cases, so I wanted to try and group things in a way that made more sense, so I now have a text file with 300 cases, a sample of two of them are below:
[{"Treatment": [""], "Year": "2004", "Reason": "Intentional/Suspected Suicide", "CaseNumber": "9999", "OutCome": "Minor effect", "Symptoms": ["Drowsy/lethargy / Related"], "case_drugs": [{"Substance": "RIVOTRIL", "Poisindex_Desc": "BENZODIAZEPINE", "SubstanceFormula_20c": "LIQUID", "SubstanceProductCode": "999", "RouteExp": "INGEST", "SubstanceGeneric_AAPCC_Code": "999"}, {"Substance": "HYDROMORPHONE X 15 SYRINGES 6 MG EA", "Poisindex_Desc": "HYDROMORPHONE", "SubstanceFormula_20c": "LIQUID", "SubstanceProductCode": "9999", "RouteExp": "INGEST", "SubstanceGeneric_AAPCC_Code": "9999"}], "Acuity": "Acute", "AgeGroup": "90-99 yrs", "SEX": "zoidberg"},
{"Treatment": ["Single Dose Activated Charcoal", "IV Fluids"], "Year": "2006", "Reason": "Unintentional/General", "CaseNumber": "8888", "OutCome": "Minimal clinical effects possible", "Symptoms": [""], "case_drugs": [{"Substance": "LOPERAMIDE 2MG X 1/2", "Poisindex_Desc": "LOPERAMIDE", "SubstanceFormula_20c": "SOLID (TABLETS/CAPSULES/CAPLETS)", "SubstanceProductCode": "88", "RouteExp": "INGEST", "SubstanceGeneric_AAPCC_Code": "88"}], "Acuity": "Acute", "AgeGroup": "L5 yrs", "SEX": "F"}]
Something like "Year" only has 1 value for each case. "Symptoms" has a list of values, and "case_drugs" has a list of dicts. This format makes a lot of sense to me since 1 person can have multiple drugs, and each drug has multiple attributes associated with it. I don't really want to flatten the data because something like the drug variable doesn't really have a maximum number of entries, so it's possible that if I have like "drug1, drug2, drug3" then next time I get data I'll have to add a "drug4".
Currently, I can load the file in pandas and analyze most of it. For the list values, I've come across another stack exchange post that suggested I could use this:

df['Symptoms'].apply(lambda x: pd.Series(x).value_counts()).sum()

That works perfectly. I'm sure I can figure out how to do other analysis with a similar method. I still am unsure how I will go about analyzing the case_drugs variable. I can make my own functions to loop through and read the data, but I was wondering if there is existing functionality in pandas that will be able to do this. For example, what if I wanted to count the number of times 'RIVOTRIL' showed up in the "substance" value of "case_drugs" variable?
Or if you think I'd be better off storing the data in a different way, that would be an acceptable answer too!
Thanks

A: For the case_drugs variable, one way to do it is to create another dataframe for it.
df_case_drugs = pd.DataFrame(df['case_drugs'].values[0])
df_case_drugs['Substance'].value_counts()
>>>
RIVOTRIL                               1
HYDROMORPHONE X 15 SYRINGES 6 MG EA    1

Update:
Creating a dataframe that includes all the entries in case_drugs.
I would first split (explode) the list of dicts in case_drugs to its own row and use CaseNumber as the index.
df_case_drugs = pd.DataFrame(df['case_drugs'].tolist(), index=df['CaseNumber']).stack()
df_case_drugs = df_case_drugs.reset_index()

This gives you a dataframe with one dict per row in the column named 0. (You can rename the column, but we are not keeping this column anyway so it doesn't really matter.)
Then convert the dicts into a dataframe.
df_case_drugs = pd.concat([df_case_drugs['CaseNumber'],
    pd.DataFrame(df_case_drugs[0].tolist())], axis=1)

Count values:
df_case_drugs['Substance'].value_counts()
>>>
RIVOTRIL                               1
LOPERAMIDE 2MG X 1/2                   1
HYDROMORPHONE X 15 SYRINGES 6 MG EA    1


text:
Q: C# Поставить в соответствие элементу Button определенный элемент массива Есть двумерный массив arr[5,5]  и на форме 25 кнопок расположенных 5 на 5
Как сопоставить элемент этого массива определенной кнопке,то есть чтобы при нажатии на какую-то кнопку менялось значение элемента в массиве(или в соседних элементах)?
Другими словами я хочу как-то проиндексировать элемент button, чтобы можно было засунуть его в цикл


text:
Q: S3 presigned upload url error I am trying to perform a document upload using an S3 pre-signed PUT url. I generated the url using java AWS SDK (GeneratePresignedUrlRequest.java). This url generation code sits in a lambda function behind AWS API gateway.
However I am getting the following error when I copy the generated url in Postman & try to perform an upload.
<Error>
AccessDenied
<Message>
There were headers present in the request which were not signed
</Message>
<HeadersNotSigned>host</HeadersNotSigned>
<RequestId>6E624EC66091A099</RequestId>
<HostId>
9HnUUZpa9zUWfyzuNrZtRkoN2CYxH8V6rqx5QgsMFC6foTZKuG5qmZL5ThnUXooYPk2reFzKKUg=
</HostId>
</Error>

The generated url is "https://<bucket>.s3.amazonaws.com/<key>?X-Amz-Security-Token=<value>&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20180718T013339Z&X-Amz-SignedHeaders=content-type%253Bhost&X-Amz-Expires=1799&X-Amz-Credential=<value>&X-Amz-Signature=<value>
Any suggestions as to what needs to be corrected here in the generation of url ?

A: The error was indeed related to a 'missing header', but not 'host' which was misleading. The value 'content-type' that comes before 'host' in X-Amz-SignedHeaders=content-type%253Bhost , needs to be explicitly provided as a request header when a http client uses the pre-signed url to upload a file to S3.
I had generated the pre-signed url in java as
GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName,objectKey).withMethod(HttpMethod.PUT).withContentType("application/pdf").withExpiration(expiration);
So S3 expects content-type with value 'application/pdf' to be part of the pre-signed url request as a header for a signature match as I understand.


text:
Q: Strong security precautions for an Android app to prevent it from being cracked Can you suggest me any good anti-crack approaches (other than a code obfuscation), considering that the paid apps on the Market are easily cracked, and the same goes for a basic server check after a PayPal transaction?
My idea is to have one (very important for the app) Java object saved on the server, and passed to the app each time when it starts. Do you think that this sounds good ?
Note that it is more like of a theoretical question, as I am not going to implement it in an app, I am more like seeking the knowledge for this rather than a concrete solution to a problem.
Any ideas would be appreciated, even ones that you are not very sure if they are good or not. Remember, the question is for Android apps. Thanks.
EDIT: I know that there can't be an unbreakable client side application, I am asking for a good option to prevent it other than a obfuscation

A: No.  Code stored on the server and provided for execution on the device can be grabbed and stored elsewhere such as locally.  (And that's probably going to be as hard for you to implement as it will be for the attacker to patch around)
Ultimately, you have to face the fact that preventing run authorization just isn't possible on a general purpose computing platform.
Unless you move actual functionality to execution on a server requiring an individually authorized account, all you can hope for with regard to code running on the user owned device is to achieve a higher than average shade of difficulty.


text:
Q: extracting facebook second degree friends IOS objective-c I'm trying to extract the profile of my friends, friends.
me --> Andy --> Dona
I'm friends with Andy so I can get his data as well as see that Dona is his friend but how do I get all the information (name, gender, location etc) of dona when all I have it's her FB userID?
I've tried calling the following, replacing @"me" with dona id as well as profile/<id> but both failed
[[[FBSDKGraphRequest alloc] initWithGraphPath:@"me"
                                       parameters:@{ @"fields": @"name,picture,email,friendlists",}]//picture.type(large)
     startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error)
     {
 }];


text:
Q: How to retrive select value of dynamic dropdown inside placeholder controls in C# I want to get a selected value of Dynamic Control which is inside placeholder
The below code is how i have created dynamic dropdown controls
string strQuery = "select distinct(TXT_BRANCH_NAME) from TBL_BRANCH_MASTER;";

DataTable dt_data = new DataTable();

dt_data = objdBConnection.getDataTableQuery(strQuery);

DropDownList ddlBranchList = new DropDownList();

if (dt_data.Rows.Count > 0)
{

int rowCount = dt_data.Rows.Count;

string[] assetList = new string[rowCount];

ddlBranchList.ID = "ddlBranchList";

ddlBranchList.Items.Add(new ListItem("Select", ""));

ddlBranchList.CssClass = "form-control form-control-line";

for (int j = 0; j < rowCount; j++)
{

ddlBranchList.Items.Add(new ListItem(dt_data.Rows[j]["TXT_BRANCH_NAME"].ToString(), dt_data.Rows[j]
["TXT_BRANCH_NAME"].ToString()));
}
ddlBranchList.DataBind();
}

What I have tried:
Here Below i m fetching selected value of dropdown
string ddlBranch = "";

DropDownList ddlist = ((DropDownList)plcBranchddl.FindControl("ddlBranchList"));

ddlBranch = ddlist.SelectedValue.ToString();

but at last i m getting a null in ddllist dropdown references


text:
Q: Matlab: ode45 output incorrect for forced spring mass damper Here is my Matlab code to solve the second order ODE for a mass-spring-dashpot system:
function Spring

clear all;
close all;
options=odeset('RelTol',1e-6);
p0 = [1 0]; %initial position and velocity
[t,p] = ode45(@SpringFunction, [0 20], p0, options);

plot(t,p(:,1)) %plot the first column (x) vs. time

return

function pdot = SpringFunction(t,p)

c = 5; w = 2;
g = sin(t); % forcing function
pdot = zeros(size(p));
pdot(1) = p(2);
pdot(2) = g-c*p(2)-(w^2)*p(1);

return

I believe the output I am getting is wrong because for this case I think a plot of displacement vs. time should look like a sinusoid with decreasing amplitude. Instead, it looks like this:

This seems incorrect to me, but please correct me if I'm wrong. I cannot see what is incorrect in the code.

A: You're sinusoidally forcing a damped system so you should expect the steady state to be a sinusoid. Here's a nice vibrations tutorial (PDF) – see pp. 448–450 on damped sinusoidal forcing. Try removing the forcing or greatly reducing its amplitude. Also, it looks like you have a lot of damping. Your damping ratio, ζ (zeta), appears to be c/(2*w) = 5/4. This implies that the unforced form of your system is over-damped – with no forcing you won't see oscillation.
Also, be careful using ode45 with oscillatory systems. If your system happens to be too stiff, you may either need to adjust the tolerances or use a stiff solver such as ode15s to get accurate results. You can always try using tighter tolerances to check that they yield qualitatively similar results (same period, amplitude, rate of growth/decay, etc.).


text:
Q: How do I download KPPP-debs from within Windows? How do I download KPPP even if I can only connect to the internet via dial-up connection?
In other words: is there a way to get KPPP while Windows is running and install it later on Ubuntu?

A: You can find the package at http://packages.ubuntu.com
For 13.04 for instance http://packages.ubuntu.com/raring/kppp
You'd need to make sure that you have the dependencies installed.
Once you've downloaded the file(s) externally you can install them on the target machine.


text:
Q: connect is not a function when connecting to mongodb Error occurs when trying to run the function from the mongodb website that connects code to db.
const MongoClient = require('mongodb')

const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
  const collection = client.db("test").collection("devices");
  // perform actions on the collection object
  client.close();
});

Error is:
client.connect(err => {
  ^

    TypeError: client.connect is not a function

I have mongodb installed via npm and uri defined as the string they gave. Do I need anything else?

A: The reason is that you should import the MongoClient class:
const MongoClient = require("mongodb").MongoClient;

Instead of the following line in your code: const MongoClient = require("mongodb");

A: Try connecting this way:
const { MongoClient } = require("mongodb");

const uri = "yourUri...";
const databaseName = "yourDBName";

MongoClient.connect(uri, { useNewUrlParser: true }, (error, client) => {
  if (error) {
    return console.log("Connection failed for some reason");
  }
  console.log("Connection established - All well");
  const db = client.db(databaseName);
});

A: If you are using older version of MongoClient then try to install mongo client 2.2.33.
npm uninstall mongodb
npm install mongodb@2.2.33

If you are using the newer version (3.0 and above) of mongo client then modify the code as shown below.
let MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017', function(err, client){
  if(err) throw err;
  let db = client.db('test');
  db.collection('devices').find().toArray(function(err, result){
    if(err) throw err;
    console.log(result);
    client.close();
    });
 });

A: For that problem, the standard solution is to import clientPromise because versions higher than 3.9/4.0 do not have import {Mongoclient} command.
Then also, if you want to use MongoClient then,

*

*Stop the current running server

*Type npm i mongodb@3.5.9 in terminal

*Restart your server by npm/yarn run dev
Now it will work

A: const mongodb = require('mongodb').MongoClient();