text:
Q: Computing the largest eigenvalue of a very large sparse matrix I am trying to compute the asymptotic growth-rate in a specific combinatorial problem depending on a parameter $w$, using the Transfer-Matrix method. This amounts to computing the largest eigenvalue of the corresponding matrix.
For small values of $w$, the corresponding matrix is small and I can use the so-called power method — start with some vector, and multiply it by the matrix over and over, and under certain conditions you'll get the eigenvector corresponding to the largest eigenvalue. However, for the values of $w$ I am interested in, the matrix becomes too large, and thus the vector becomes too large, say, $n > 10^7$ entries or so, and it can't be contained in the computer's memory anymore and I need extra programming tricks or a very powerful computer.
As for the matrix itself, I don't need to store it in memory — I can access it as a black box, i.e., given $i, j$ I can return $A_{ij}$ via a simple computation. Also, the matrix has only $0$ and $1$ entries, and I believe it to be sparse (i.e., only around $\log n$ of the entries are $1$'s, $n$ being the number of rows/columns). However, the matrix is not symmetric.
Is there some method more space-effective for computation of eigenvalues for a case like this?

A: You could use the Arnoldi Iteration algorithm. This algorithm only requires the matrix A for matrix-vector multiplication. I'm expecting that you will be able to black-box the function v→Av. What you generate is an upper Hessenberg matrix H whose eigenvalues whose can be computed cheaply (by a direct method or Rayleigh quotient iteration) and which approximate the eigenvalues of A. Arnoldi Iteration will give the best approximation to the dominant eigenvalue so I suspect you won't have to do many iterations before you have a good estimate.
An excellent introduction to this is: "Numerical Linear Algebra" by Trefethen and Bau. (p250)
The basic algorithm can be found here: http://en.wikipedia.org/wiki/Arnoldi_iteration
Now the only thing that is required to make this a fully functional algorithm is a termination condition. Since you don't seem to need the dominant eigenvalue to a high degree of accuracy I would not worry and just stop when the dominant eigenvalue estimate doesn't change too much.
If you have Matlab you can always use the built in function eigs(Afun,n,...) where Afun is the black-box function handle that computes Av.

A: . nonzeroindices = set([])
. for i in range(n):
.. for j in range(n):
... if A(i,j) == 1:
.... nonzeroindices.union(set([i]))
. nonzeroindex = sorted(nonzeroindices)
. newmatrix = []
. for i in range(n):
.. newmatrix.append([])
.. for j in range(n):
... newmatrix[i].append(A(nonzeroindex[i],nonzeroindex[j]))
Then compute the eigenvalues of the around 2*log(n)-by-2*log(n) newmatrix.


text:
Q: I want to make an if statement that each image would be full screen when the user is tap here is the code that I check if they images are tapped but only the 3 image is apply full screen. As you can see I set the image is tapped to statusImageView to call the function of zoomImage So I want fixed for all images.
func imageTapped() {
  let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageZoom(tapGestureRecognizer:)))

    if detailsImage[0].tag == 0 {
        detailsImage[0].isUserInteractionEnabled = true
        detailsImage[0].addGestureRecognizer(tapGestureRecognizer)
        self.statusImageView = detailsImage[0]
    }
    let tapGestureRecognizer1 = UITapGestureRecognizer(target: self, action: #selector(imageZoom(tapGestureRecognizer:)))
        detailsImage[1].isUserInteractionEnabled = true
        detailsImage[1].addGestureRecognizer(tapGestureRecognizer1)
        self.statusImageView = detailsImage[1]

    let tapGestureRecognizer2 = UITapGestureRecognizer(target: self, action: #selector(imageZoom(tapGestureRecognizer:)))
        detailsImage[2].isUserInteractionEnabled = true
        detailsImage[2].addGestureRecognizer(tapGestureRecognizer2)
        self.statusImageView = detailsImage[2]

}

let blackBackgroundColor = UIView()
let tappedImage = UIImageView()
var statusImageView: UIImageView?
let navigationBarView = UIView()

@objc func imageZoom(tapGestureRecognizer: UITapGestureRecognizer) {
    annimationImage(detailsImage: statusImageView!)
}

And then I call the annihilationImage function which is takes the statusImageView as input
    func annimationImage(detailsImage: UIImageView) {

    if let startingFrame = statusImageView?.superview?.convert(statusImageView!.frame, to: nil) {

        statusImageView!.alpha =  0

    blackBackgroundColor.frame = self.view.frame
    blackBackgroundColor.backgroundColor = UIColor.black
    blackBackgroundColor.alpha = 0
    view.addSubview(blackBackgroundColor)

        navigationBarView.frame = CGRect(x: 0, y: 0, width: 1000, height: 100)
        navigationBarView.backgroundColor = UIColor.black
        navigationBarView.alpha = 0

        if let keyWindow = UIApplication.shared.keyWindow {
            keyWindow.addSubview(navigationBarView)
        }

    let tappedImage = UIImageView()
    tappedImage.backgroundColor = .gray
    tappedImage.frame = startingFrame
    tappedImage.contentMode = .scaleToFill
    tappedImage.isUserInteractionEnabled = true
    tappedImage.image = statusImageView?.image
    tappedImage.clipsToBounds = true
    view.addSubview(tappedImage)

    UIView.animate(withDuration: 0.75, animations: {
        tappedImage.frame = CGRect(x: 0, y: y, width: self.view.frame.size.width, height: 300)

        })
    }
}

I want to make an if statement that while check which image is tapped

A: You can use tapGestureRecognizer.view for getting a view that is assigned a tap gesture. And by this, you can also get the view tag (your view is corresponding to the image view in your code)
@objc func imageZoom(tapGestureRecognizer: UITapGestureRecognizer) {
    let senderView = tapGestureRecognizer.view // Here you get a view that is associated with the gesture
    let tag = senderView?.tag // Here you get a tag that is assigned to all image

// Add your condition here by tag

 annimationImage(detailsImage: statusImageView!)
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: SQL Server - TIMESTAMP caused exception I am syncing from PostgreSql to MSSQL using SymmetricDS. Some tables of the source database have timestamp field set too '0001-01-01 00:00:00.0' and it could not be able to insert to destination(SQL Server) database.
Is there anyway to work around this ?
AcknowledgeService - The outgoing batch 001-987 failed: Parameter arg '0001-01-01 00:00:00.0' type: TIMESTAMP caused exception: Only dates between January 1, 1753 and December 31, 9999 are accepted.

A: Instead of using the (old) datetime datatype in SQL Server, you can use the (newer and better) datetime2. Among other things, it accepts earlier dates, back to year 1.
A tip is to specify how many digits you was for the second fractions. If you don't do it, you get 7 (as in 12:23:45.2314534). If you can get by with less, then specify for instance datetime2(0) and you get zero decimals. Or whatever you want/need.

A: Pseudocode:
set destinationValue = case when sourceValue = '0001-01-01 00:00:00.0' then null else sourceValue end

In English:
Can you check the value during the export/import? If so, then test for the case where the value is '0001-01-01 00:00:00.0' and in that case, set the destination value as null instead. When the above is not the case, then migrate the data as before.
If you want to be pedantic, make your test case when sourceValue < '1753-01-01'
If your destination does not accept nulls, then you need to decide how you want to represent those dates. One option is to set them to the value '1753-01-01 00:00:00' instead of null. Whether that works depends on how your applications are configured to consume the data in the destination.


text:
Q: Phalcon fire event from controller I am using the Phalcon micro application as my REST web service. I want to add an event to the application and fire this event from different places like controllers.
For example; if a user registers, the controller should fire a userRegistered event, and userRegistered should do some stuff.
How can I implement this?
interface IUsers
{
    function onUserRegistered();
}

Event class
class UsersActivities implements IUsers
{
    function onUserRegistered()
    {
        // TODO: Implement onUserRegistered() method.
    }
}

A: Just check docs. It's pretty simple, create manager, creat listener(UsersActivities in your case i guess) and fire events in manager.
https://docs.phalconphp.com/pl/latest/reference/events.html


text:
Q: Como checar mudança em tempo real no banco de dados com websocket php? Quero atualizar uma div somente quando houver mudança em um determinado campo no banco de dados, atualmente estou usando polling, mas quero mudar para websocket por questões de desempenho, mas só achei exemplos de chats, e não é o que eu preciso.Alguém tem uma dica de como checar mudanças no bd com websocket?

A: Você tem várias maneiras.

*

*MySQL: Usando sys_exec().
Ele pode ser usado como um Trigger, sempre que o dado é adicionado ele é acionado e portanto pode acionar um arquivo, como por exemplo um PHP, este PHP envia a informação via websocket.
Maleficio: O PHP tende a ser lento e somado com o tempo de conexão você terá um query muito mais lenta, uma vez que ela somente irá terminar após o websocket ser concluído, ou você terá que fazer alguma gambiarra para executar silenciosamente, de qualquer uma das formas isto não estará mencionado no EXPLAIN, você pode não conseguir saber a razão do banco da dados está lento.

Encontrei esta publicação do PubNub, uma empresa que oferece websockets, que utiliza curl diretamente usando o sys_eval(), porém com uma "advertência" que isto não é recomendado.

*MySQL: Cheque os logs.
Você sabe como as replicas do MySQL são sincronizadas (um master + X slaves)? Uma das formas é sincronizando os logs do master, nele contem tudo que foi mudado e você pode utilizar os isto para ver o que mudou e enviar informações baseada nela. Essa solução talvez seja a mais complexa (e menos clara) na minha opinião, você também pode usar algo como inotifywait para acionar quando o arquivo for atualizado.

*PHP: Envie depois do commit.
Imagine que você tem um website que possua um saldo, transferível entre usuários, você quer notifica-los quando cada um receber e enviar, por exemplo:

mysqli_begin_transaction($con);
mysqli_autocommit($con, false);

$detalhe = mysqli_query($con, '
   INSERT INTO `pagamento_detalhe`(`QuemPagou`, `QuemRecebeu`, `Valor`)
     VALUES ("'.$idPagou.'", "'.$idRecebeu.'", "'.$Valor.'")
');
$detalhe = mysqli_affected_rows($con) === 1;

$atualizaSaldo = mysqli_query($con, '
   UPDATE usuario as Pagou, usuario as Recebeu
    SET Pagou.Saldo = Pagou.Saldo - '.$Valor.', Recebeu.Saldo = Recebeu.Saldo + '.$Valor.'
     WHERE Pagou.id = "'.$idPagou.'" AND Recebeu.id = "'.$idRecebeu.'"
');
$atualizaSaldo = mysqli_affected_rows($con) === 2;

if($atualizaSaldo && $detalhe){
    mysqli_commit($con);
}else{
    mysqli_rollback($con);
}

Seria mais fácil adicionar algo deste tipo:
//...
if($atualizaSaldo && $detalhe){
    mysqli_commit($con);
    enviar_websocket($idPagou, 'Você enviou '.$Valor);
    enviar_websocket($idRecebeu, 'Você recebeu '.$Valor);
}else{
    mysqli_rollback($con);
}

Criando uma função enviar_websocket irá enviar o websocket para o id correspondente com uma mensagem que você define, POR EXEMPLO. Isso será enviado sempre que ocorrer uma atualização dos dados, porém ainda no lado do PHP e não do MySQL.

A: Você precisa identificar quem faz o update, delete ou insert no seu banco, provavelmente um arquivo .php deve fazer isso, considerando isto, alguma máquina client solicitou esse arquivo, correto?
Considerando que vc já tenha um servidor websocket funcionando é só mandar um send()"javascript" para o socketID da maquina client que deseja receber essa alteração.
Para detalhe sobre como montar servidor websocket, tenho um totalmente em php e posso te ajudar, não é difícil, existem vários tutos que ensina a montar um como chat, é só adaptar ao seu uso. veja esse link
 http://gustavobeavis.github.io/blog/2014/09/11/web-socket-php/
Me baseei nele para montar um chat interno para empresa onde trabalho...


text:
Q: Access custom service class in servicelocator in liferay velocity template I have a scenario where I have a class and some methods in it which i need to access in liferay velocity template in my theme.
I tried accessing the class as a service in my vm file using
#set ($myService = $serviceLocator.findService('my-dummy-portlet', 'com.mycompany.dummy.DummyABC'))

For the following class -
final class DummyABC {
    public String method1() {}
    public String method2() {}
    public String method3() {}
}

But I am getting the following exception -
07:17:22,303 ERROR [PortletBeanLocatorUtil:38] BeanLocator is null
07:17:22,304 ERROR [ServiceLocator:56] com.liferay.portal.kernel.bean.BeanLocatorException: BeanLocator has not been set
com.liferay.portal.kernel.bean.BeanLocatorException: BeanLocator has not been set
    at com.liferay.portal.kernel.bean.PortletBeanLocatorUtil.locate(PortletBeanLocatorUtil.java:40)
    at com.liferay.portal.velocity.ServiceLocator.findService(ServiceLocator.java:52)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.velocity.util.introspection.UberspectImpl$VelMethodImpl.doInvoke(UberspectImpl.java:389)
    at org.apache.velocity.util.introspection.UberspectImpl$VelMethodImpl.invoke(UberspectImpl.java:378)
    at org.apache.velocity.runtime.parser.node.ASTMethod.execute(ASTMethod.java:270)
    at org.apache.velocity.runtime.parser.node.ASTReference.execute(ASTReference.java:262)
    at org.apache.velocity.runtime.parser.node.ASTReference.value(ASTReference.java:507)
    at org.apache.velocity.runtime.parser.node.ASTExpression.value(ASTExpression.java:71)
    at org.apache.velocity.runtime.parser.node.ASTSetDirective.render(ASTSetDirective.java:142)
    at org.apache.velocity.runtime.parser.node.SimpleNode.render(SimpleNode.java:336)
    at org.apache.velocity.runtime.directive.Parse.render(Parse.java:260)
    at org.apache.velocity.runtime.parser.node.ASTDirective.render(ASTDirective.java:175)
    at org.apache.velocity.runtime.parser.node.ASTBlock.render(ASTBlock.java:72)
    at org.apache.velocity.runtime.parser.node.ASTIfStatement.render(ASTIfStatement.java:87)
    at org.apache.velocity.runtime.parser.node.ASTBlock.render(ASTBlock.java:72)
    at org.apache.velocity.runtime.parser.node.ASTIfStatement.render(ASTIfStatement.java:87)
    at org.apache.velocity.runtime.parser.node.SimpleNode.render(SimpleNode.java:336)
    at org.apache.velocity.Template.merge(Template.java:328)
    at org.apache.velocity.Template.merge(Template.java:235)
    at org.apache.velocity.app.VelocityEngine.mergeTemplate(VelocityEngine.java:381)
    at com.liferay.portal.velocity.VelocityEngineImpl.mergeTemplate(VelocityEngineImpl.java:155)
    at com.liferay.portal.velocity.VelocityEngineImpl.mergeTemplate(VelocityEngineImpl.java:165)
    at com.liferay.portal.kernel.velocity.VelocityEngineUtil.mergeTemplate(VelocityEngineUtil.java:71)
    at com.liferay.taglib.util.ThemeUtil.includeVM(ThemeUtil.java:330)
    at com.liferay.taglib.util.ThemeUtil.include(ThemeUtil.java:76)
    at com.liferay.taglib.theme.IncludeTag.include(IncludeTag.java:38)
    at com.liferay.taglib.util.IncludeTag._doInclude(IncludeTag.java:223)
    at com.liferay.taglib.util.IncludeTag.doEndTag(IncludeTag.java:58)
    at org.apache.jsp.html.common.themes.portal_jsp._jspx_meth_liferay_002dtheme_005finclude_005f1(Unknown Source)
    at org.apache.jsp.html.common.themes.portal_jsp._jspx_meth_c_005fotherwise_005f0(Unknown Source)
    at org.apache.jsp.html.common.themes.portal_jsp._jspService(Unknown Source)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:377)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:646)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:436)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:374)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:302)
    at com.liferay.portal.struts.StrutsUtil.forward(StrutsUtil.java:79)
    at com.liferay.portal.struts.PortalRequestProcessor.doForward(PortalRequestProcessor.java:258)
    at org.apache.struts.tiles.TilesRequestProcessor.processTilesDefinition(TilesRequestProcessor.java:239)
    at org.apache.struts.tiles.TilesRequestProcessor.internalModuleRelativeForward(TilesRequestProcessor.java:341)
    at org.apache.struts.action.RequestProcessor.processForward(RequestProcessor.java:572)
    at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:221)
    at com.liferay.portal.struts.PortalRequestProcessor.process(PortalRequestProcessor.java:153)
    at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196)
    at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:414)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
    at com.liferay.portal.servlet.MainServlet.callParentService(MainServlet.java:508)
    at com.liferay.portal.servlet.MainServlet.service(MainServlet.java:485)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:196)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:126)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:196)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:126)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:196)
    at com.liferay.portal.servlet.filters.strip.StripFilter.processFilter(StripFilter.java:261)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:123)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:196)
    at com.liferay.portal.servlet.filters.themepreview.ThemePreviewFilter.processFilter(ThemePreviewFilter.java:88)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:123)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:196)
    at com.liferay.portal.servlet.filters.gzip.GZipFilter.processFilter(GZipFilter.java:110)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:123)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:196)
    at com.liferay.portal.servlet.filters.secure.SecureFilter.processFilter(SecureFilter.java:182)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:123)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:646)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:436)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:374)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:302)
    at com.liferay.portal.util.PortalImpl.sendError(PortalImpl.java:3912)
    at com.liferay.portal.util.PortalUtil.sendError(PortalUtil.java:1221)
    at com.liferay.portal.servlet.ImageServlet.service(ImageServlet.java:124)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:196)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:126)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:196)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:126)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:196)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:126)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:196)
    at com.liferay.portal.servlet.filters.sso.ntlm.NtlmPostFilter.processFilter(NtlmPostFilter.java:81)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:123)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:196)
    at com.liferay.portal.sharepoint.SharepointFilter.processFilter(SharepointFilter.java:179)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:123)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:196)
    at com.liferay.portal.servlet.filters.virtualhost.VirtualHostFilter.processFilter(VirtualHostFilter.java:240)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:123)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:196)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:126)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:196)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:126)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:738)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:196)
    at com.liferay.portal.servlet.filters.threadlocal.ThreadLocalFilter.processFilter(ThreadLocalFilter.java:35)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:123)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:470)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:619)

Let me know if I am going wrong somewhere.

A: Create a ext-spring.xml in the /WEB-INF/classes/META-INF/ folder of your plugin project which would other xml files for spring and hibernate generated through the service-builder. And then specify your class as a spring-bean inside of ext-spring.xml. The serviceLocator just locates spring beans defined by your portlet and not other classes.
If you open your service.properties file you would see an entry as ext-spring.xml for the property spring.configs=, this is what loads the ext-spring.xml, you don't need an EXT-plugin for it. ext- prefix just means that you are extending their spring configuration.


text:
Q: Angular (or something else) isn't saving JSESSIONID cookie I'm setting up a simple authentication service for my angular website using Spring for my backend and I have a following problem.
When I send a cross domain get request with credentials (REST controller on backend), I get authorized by Spring Security, I get a JSESSION cookie and all is fine. What's not fine is that the cookie isn't saved and I can't access it in any way I could think of to save it manually.
Am I missing something here? If you need additional information, I'd be glad to provide it.
@Edit
I have Set-Cookie header in my response:
(...)
Server
WildFly/8
Set-Cookie
JSESSIONID=CODE; path=/PATH
(...)


text:
Q: checking whether data is null Is it best practice to check whether a value is null coming from a database even though there are constraints on the column which disallow nulls.
Thanks in advance

A: What you're talking about is defensive programming.  I like to think it's good to practice it when you don't trust your input.  You might think you can trust your DB now, but what if in the future you decide that column should have a NULL value somewhere?  Then you need to change your code everywhere you assumed it wasn't?
If you don't ever think you'll change it (like it's a primary key or something) then I don't think you need to.  It's more future proofing in case you one day decide to change your schema.  If that column will never have a case where NULL makes sense, then you probably don't need to check.  In the event you get a NULL, like commenters have said, you have a bigger problem in that your DB is probably hosed.

A: I'd say go ahead and add checking for Nulls on your business logic. It would be particularly useful too during unit testing. Maybe not now but in the future.

A: It depends on a lot of factors.
In many of my projects I strive to enable unit-testing, which would decouple the code that processed data from the code that retrieved the data (ie. by talking to the database.)
That way I could also potentially reuse the code that processed the data by feeding it data from other sources. I would absolutely safeguard input values to the logic layer in this case.
Also, applications evolve over time, so even if it is impossible for you to get null values right now, at some point it might be implemented, and a lot of old code would then suddenly get things it wasn't written to handle. I would personally want them to fail fast rather than in some cases silently process wrongly.


text:
Q: Hillegass: Cocoa Prog 3rd Ed: Ch. 33 on OpenGL: Where's the torus? In the opengl section of Hillegass' otherwise fine book, we're given sample code for drawing a 3d object on a view.  Two people at the book's discussion forum at http://techstra.bignerdranch.com/ have reported that the drawing code runs, but fails to draw the object.  I'm getting the same result, and the only discussion I've found resolves to a solution for a fix to the Ubuntu port of OpenGL, not much help to us trying to get this working on the mac.
Seeing how the code successfully changes the bg color, everything's apparently wired up. Maybe the object is written out of the viewport.  Has anyone else tried this code and gotten it to work?

A: I just tried it. Works fine. You can download my project here.


text:
Q: aws emr can't change default pyspark python on bootstrap I am using aws with emr, and trying to change to bootstrap script in order to set the default python in pyspark to be python 3, I am following this tutorial
this is changing the /usr/lib/spark/conf/spark-env.sh file, but does not change the python version in pyspark, I am still getting jobs done with python 2.7. this is only working when I ssh to the machine and specifically use
$source /usr/lib/spark/conf/spark-env.ssh

When I try to add this line to the bootstrap script I am getting bootstrap error that the file is not found.

/bin/bash: /usr/lib/spark/conf/spark-env.sh: No such file or directory

I assume that the file does not exist in this stage. How can I set the pyspark python to be python 3 in the bootstrap script?

A: Add the following code to software configuration (create emr -> step1: software and steps -> edit software configuration -> enter configuration)
[
  {
     "Classification": "spark-env",
     "Configurations": [
       {
         "Classification": "export",
         "Properties": {
            "PYSPARK_PYTHON": "/usr/bin/python3"
          }
       }
    ]
  }
]


text:
Q: Can't get weight samples using anchored query I'm working on a watchOS App as my first Swift/iOS project ever. I want to fetch the latest body weight sample and use it for some calculation. The result is presented to the user. As soon as a new sample is added, I want to update my UI as well. It works in a completely fresh simulator installation. As soon as I add a sample in the iOS simulator, the app updates its UI in the watchOS simulator. However, it doesn't work on my real device or after resetting the watchOS simulator. And I just don't know why. The HKAnchoredObjectQuery just returns 0 samples but I definitely have some samples stored in health. I can even see them under Settings > Health on my watch. I can't imagine this is related to my code, but here it is:
class WeightProvider: ObservableObject {
    private static let weightSampleType = HKSampleType.quantityType(forIdentifier: .bodyMass)!
    private static let healthStore: HKHealthStore = .init()

    private var previousAnchor: HKQueryAnchor?
    private var runningQuery: HKAnchoredObjectQuery?

    @Published var bodyWeight: Measurement<UnitMass>?

    func getBodyWeight(longRunning: Bool = false) {
        let query = HKAnchoredObjectQuery(type: Self.weightSampleType, predicate: nil, anchor: previousAnchor, limit: longRunning ? HKObjectQueryNoLimit : 1, resultsHandler: processQueryResult)

        if longRunning {
            query.updateHandler = processQueryResult
            runningQuery = query
        }

        Self.healthStore.execute(query)
    }

    func stopLongRunningQuery() {
        if let runningQuery = runningQuery {
            Self.healthStore.stop(runningQuery)
            self.runningQuery = nil
        }
    }

    private func processQueryResult(_: HKAnchoredObjectQuery, samples: [HKSample]?, _: [HKDeletedObject]?, newAnchor: HKQueryAnchor?, error: Error?) {
        guard let samples = samples as? [HKQuantitySample], error == nil else {
            fatalError(error?.localizedDescription ?? "Failed to cast [HKSample] to [HKQuantitySample]")
        }

        previousAnchor = newAnchor

        guard let sample = samples.last else {
            return
        }

        DispatchQueue.main.async {
            if Locale.current.usesMetricSystem {
                let weight = sample.quantity.doubleValue(for: .gramUnit(with: .kilo))
                self.bodyWeight = .init(value: weight, unit: UnitMass.kilograms)
            } else {
                let weight = sample.quantity.doubleValue(for: .pound())
                self.bodyWeight = .init(value: weight, unit: UnitMass.pounds)
            }
        }
    }
}

// MARK: - HealthKit Authorization

extension WeightProvider {
    private static let typesToRead: Set<HKObjectType> = [
        weightSampleType,
    ]

    func authorize(completion: @escaping (Bool, Error?) -> Swift.Void) {
        Self.healthStore.requestAuthorization(toShare: nil, read: Self.typesToRead) { success, error in
            completion(success, error)
        }
    }
}

In my Views onAppear I call this function:
private func authorizeHealthKit() {
    guard firstRun else {
        return
    }
    firstRun = false

    weightProvider.authorize { success, error in
        guard success, error == nil else {
            return
        }

        weightProvider.getBodyWeight(longRunning: true)
    }
}

HealthKit is properly authorized as I can see in the Settings of my Watch. Any ideas? Any tips for my code in general?

A: Wow, after all this time I found the issue: The line previousAnchor = newAnchor needs to be after the guard statement. That's it.


text:
Q: Minkowski spacetime vs Euclidian space Two questions marked in bold:
What is the magnitude of a Minkowski spacetime four velocity? I'm deducing that it is c for all observers, but I'd like it confirmed.
In Euclidian space, a velocity vector integrates over time to an absolute position.
Does a four velocity integrate over time to a four dimensional displacement, and is it used in physics?
Eventually; why not?

A: It sounds as if by four vector you are actually thinking of the four velocity. The norm of the four velocity is indeed always $c$, and it does integrate to give a displacement along a world line.
The term four vector refers to anything that transforms as a vector, and as Ben notes in his comment this could refer to lots of different physical quantities that are unrelated to velocity.


text:
Q: Processing of the data from a big number of input files My AWK script processes each log file from the folder "${results}, from which it looks for a pattern (a number occurred on the first line of ranking table) and then print it in one line together with the filename of the log:
awk '$1=="1"{sub(/.*\//,"",FILENAME); sub(/\.log/,"",FILENAME); printf("%s: %s\n", FILENAME, $2)}' "${results}"/*_rep"${i}".log

Here is the format of each log file, from which the number

-9.14

should be taken
AutoDock Vina v1.2.3
#################################################################
# If you used AutoDock Vina in your work, please cite:          #
#                                                               #
# J. Eberhardt, D. Santos-Martins, A. F. Tillack, and S. Forli  #
# AutoDock Vina 1.2.0: New Docking Methods, Expanded Force      #
# Field, and Python Bindings, J. Chem. Inf. Model. (2021)       #
# DOI 10.1021/acs.jcim.1c00203                                  #
#                                                               #
# O. Trott, A. J. Olson,                                        #
# AutoDock Vina: improving the speed and accuracy of docking    #
# with a new scoring function, efficient optimization and       #
# multithreading, J. Comp. Chem. (2010)                         #
# DOI 10.1002/jcc.21334                                         #
#                                                               #
# Please see https://github.com/ccsb-scripps/AutoDock-Vina for  #
# more information.                                             #
#################################################################

Scoring function : vina
Rigid receptor: /home/gleb/Desktop/dolce_vita/temp/nsp5holoHIE.pdbqt
Ligand: /home/gleb/Desktop/dolce_vita/temp/active2322.pdbqt
Grid center: X 11.106 Y 0.659 Z 18.363
Grid size  : X 18 Y 18 Z 18
Grid space : 0.375
Exhaustiveness: 48
CPU: 48
Verbosity: 1

Computing Vina grid ... done.
Performing docking (random seed: -1717804037) ...
0%   10   20   30   40   50   60   70   80   90   100%
|----|----|----|----|----|----|----|----|----|----|
***************************************************

mode |   affinity | dist from best mode
     | (kcal/mol) | rmsd l.b.| rmsd u.b.
-----+------------+----------+----------
   1        -9.14          0          0
   2       -9.109      2.002       2.79
   3       -9.006      1.772      2.315
   4       -8.925          2      2.744
   5       -8.882      3.592      8.189
   6       -8.803      1.564      2.092
   7       -8.507      4.014      7.308
   8        -8.36      2.489      8.193
   9       -8.356      2.529      8.104
  10        -8.33      1.408      3.841

It works OK for a moderate number of input log files (tested for up to 50k logs), but does not work for the case of big number of the input logs (e.g. with 130k logs), producing the following error:
./dolche_finito.sh: line 124: /usr/bin/awk: Argument list too long

How could I adapt the AWK script to be able processing any number of input logs?

A: If you get a /usr/bin/awk: Argument list too long then you'll have to control the number of "files" that you supply to awk; the standard way to do that efficiently is:
results=. # ???
i=00001   # ???
output=   # ???

find "$results" -type f -name "*_rep$i.log" -exec awk '
    FNR == 1 {
        filename = FILENAME
        sub(/.*\//,"",filename)
        sub(/\.[^.]*$/,"",filename)
    }
    $1 == 1 { printf "%s: %s\n", filename, $2 }
' {} + |
LC_ALL=C sort -t':' -k2,2g > "$results"/ranking_"$output"_rep"$i".csv

edit: appended the rest of the chain as asked in comment
note: you might need to specify other predicates to the find command if you don't want it to search the sub-folders of $results recursively

A: Note that your error message:
./dolche_finito.sh: line 124: /usr/bin/awk: Argument list too long

is from your shell interpreting line 124 in your shell script, not from awk - you just happen to be calling awk at that line but it could be any other tool and you'd get the same error. Google ARG_MAX for more information on it.
Assuming printf is a builtin on your system:
printf '%s\0' "${results}"/*_rep"${i}".log |
xargs -0 awk '...'

or if you need awk to process all input files in one call for some reason and your file names don't contain newlines:
printf '%s' "${results}"/*_rep"${i}".log |
awk '
    NR==FNR {
        ARGV[ARGC++] = $0
        next
    }
    ...
'

If you're using GNU awk or some other awk that can process NUL characters as the RS and your input file names might contain newlines then you could do:
printf '%s\0' "${results}"/*_rep"${i}".log |
awk '
    NR==FNR {
        ARGV[ARGC++] = $0
        next
    }
    ...
' RS='\0' - RS='\n'

A: When using GNU AWK you might alter ARGC and ARGV to command GNU AWK to read additional files, consider following simple example, let filelist.txt content be
file1.txt
file2.txt
file3.txt

and content of these files to be respectively uno, dos, tres then
awk 'FNR==NR{ARGV[NR+1]=$0;ARGC+=1;next}{print FILENAME,$0}' filelist.txt

gives output
file1.txt uno
file2.txt dos
file3.txt tres

Explanation: when reading first file i.e. where number of row in file (FNR) is equal number of row globally (NR) I add to ARGV line as value under key being number of row plus one, as ARGV[1] is already filelist.txt and I increase ARGC by 1, I instruct GNU AWK to then go to next line so no other action is undertaken. For other files I print filename followed by whole line.
(tested in GNU Awk 5.0.1)


text:
Q: join 2 variables, each one pointing to something different I want to do a 'for' loop where two variables would be joined. Here is the situation
Initial set of variables, each one pointing to a file :
weather_sunny=/home/me/foo
weather_rainy/home/me/bar
weather_cloudy=/home/me/sth

2nd set of variables :
sunny
rainy
cloudy

Now, I want to do something like this...
for today in sunny rainy cloudy ; do
    cat ${weather_$today}
done

But I don't succeed getting the content of the initial variables. How can I achieve this ?

A: You can get the names of the variables easily enough:
for today in ${!weather_*}; do
    echo cat "${!today}"
done
cat /home/me/foo
cat /home/me/bar
cat /home/me/sth

But if you're using bash 4+, you can use an associative array for this. In bash 4,
$ declare -A weather
$ weather['sunny']=/home/me/sth
$ weather['humid']=/home/me/oth
$ for today in "${!weather[@]}"; do echo "${weather[$today]}"; done
/home/me/sth
/home/me/oth

A: for today in sunny rainy cloudy ; do
  eval e="\$weather_$today"
  cat $e
done

A: Inroduce temporary variable and then use indirect expansion(introduced by ! character).
for today in sunny rainy cloudy ; do
  tmp="weather_$today"
  cat ${!tmp}
done

I don't know how to stay within one line though.


text:
Q: Premature end of script headers: media ( Issue related to :rails app deployment+passenger+ubuntu+apache) i just setup a linode server and deploy my rails 3 app on it.its up and running.The problem is that some images are not showing up in the production.locally they are perfectly working.i double checked the log file(production.log) but nothing found.then i check server error.log file that says.
[Sat Dec 29 22:54:14 2012] [error] [client 182.177.228.157] Premature end of script headers: media, referer: http://50.116.57.152/app?v=11&o=33

Check out http://50.116.57.152/app?v=11&o=33  for live demo.

Thanking in advance.

A: i figured it out.ImageMagick gem was not installed on my linode server and i used dragonfly for images that's why error was coming i just installed it and bingooooo every thing is now working perfectly...........So guys be aware if you are facing the seme problem double check all the required gems installed.
Secondly, if you have installed ruby 1.9.3p360 remember it has bugs due to that request rendering does not complete. So the solution is down the ruby version from p360 to let say p327 and if you are using passenger as a web server then reinstall it. Copy 3 lines that passenger gives after installation in you apache2.cong file. restart server and this error should not occur again.
thanks.


text:
Q: RxSwift, How to draw tableView without using RxDataSourced? I can't figure out how to do your dataSource.
I watched lessons on RxSwift and RxCocoa and realized that for complex tables you need to use your datasource. Found a library RxDataSourced but we're not allowed to use it. Decided to write your own dataSource but nothing happened. If you don't mind can you show examples of writing dataSourse found nothing on the Internet.
class RXSpecificationsDataSource: NSObject, RxTableViewDataSourceType, UITableViewDataSource {
    typealias Element = MaterialEntityRootGroupProperty

    var _sectionModels: [MaterialEntityRootGroupProperty] = []

     public typealias ConfigureCell = (RXSpecificationsDataSource, UITableView, IndexPath) -> UITableViewCell

    func tableView(_ tableView: UITableView, observedEvent: Event<RXSpecificationsDataSource.Element>) { }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        guard _sectionModels.count > section else { return 0 }
       return _sectionModels[section].properties.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        precondition(indexPath.item < _sectionModels[indexPath.section].properties.count)  return ConfigureCell(self, tableView, indexPath, self[indexPath])

    }

    func numberOfSections(in tableView: UITableView) -> Int {
       return _sectionModels.count
    }
}

final class MaterialDetailSpecificationsView: UserInterface {

    private var specificationTableView: UITableView!
    private let disposeBag = DisposeBag()

    func setupView(items: Variable<[MaterialEntityRootGroupProperty]>) {
        setNabigationParms()
        drawTableViewSpecifications()

        let dataSource = RXSpecificationsDataSource ()

        dataSource.configureCell = { (dataSource, tv, indexPath, element) in
            let cell = tv.dequeueReusableCell(withIdentifier: "Cell")!
            cell.textLabel?.text = "\(element) @ row \(indexPath.row)"
            return cell
        }

        items.asObservable()
            .bind(to: specificationTableView.rx.items(dataSource: dataSource))
            .disposed(by: disposeBag)

    }

A: You do not need RxDataSources just to bind a stream to a table. There are already built-in bindings for UITableView and UICollectionView inside RxCocoa, you can see some more information here:
There's actually an example of how to do this without RxDataSources, inside the RxDataSources repo ;-)
let data = Observable<[String]>.just(["first element", "second element", "third element"])

data.bind(to: tableView.rx.items(cellIdentifier: "Cell")) { index, model, cell in
  cell.textLabel?.text = model
}
.disposed(by: disposeBag)

https://github.com/RxSwiftCommunity/RxDataSources#why


text:
Q: Problem importing a library I created for Angular from NPM I am trying to make a generic component that uses primeng inside, I would like to publish it on npm to make it available, I tried but once I import it with "npm install" it gives me error:
Cannot read property 'ecmp' of undefined in angular

Instead if I try to import via .tar file or dist folder it works, the project can be viewed here: https://github.com/hetsrl/my-prime-table
Thanks for the help


text:
Q: R: parallelize linear regression I'm running linear regression on COVID-19 data over all 3000+ US counties and the code is running pretty slow. Are there options to parallelize this?
I've tried furrr::future_map() but it doesn't really speed up the process that much. CPU usage is around 26% with and without furrr:future_map and only one process is running.
Example code:
library(furrr)
future::plan(multisession, workers = 6)
# also tried multisession workers = 6, (runtime 8.5 min)
# also tried multicore workers = 6, (runtime 3.5 min)
# also tried multicore w/ default workers, (runtime 5.5 min)

# the other called regression functions look very similar
casesmodel <- function(tbl) {
        lm(casesper100k ~ time, data = tbl)
}

uscases_twoweeks <-
    casesdeaths %>%
        filter(date >= twoweeksago) %>%
        filter(!is.na(population)) %>%
        filter(population > min_country_population) %>%
        mutate(countyid = paste(county, state, sep = ", ")) %>%
        arrange(countyid, date) %>%
        group_by(countyid) %>%
        nest() %>%
        mutate(deathmodel = future_map(data, deathsmodel),
               casemodel = future_map(data, casesmodel),
               absdeathmodel = future_map(data, absdeathsmodel),
               abscasemodel = future_map(data, abscasesmodel),
               )


text:
Q: Is it OK to unregister 'dynamic' BroadcastReceiver from receiver's own onReceive() method? That is,  I have this BroadcastReceiver I create on the fly to listen for one broadast, after which I want it to unregister itself.
I haven't found any sample code that does it this way, but neither have I found any rule in the android online docs that forbids this. But I cannot let it hang around for as long as the activity, and it is in an anonymous class anyway, so the containing class does not even know the variable name.
That is, the code looks something like this:
myInfoReceiver = new BroadcastReceiver() {
onReceive(Context ctx, Intent intt) {
    // do some Notification when I get here
    nm.notify("I got here") // obvious pseudo code
    ctx.unregisterReceiver(myInfoReceiver);
} // end onReceive
ctx.registerReceiver),uInfoReceiver, new IntentFilter(...));
}; // end BroadcastReceiver

But when I run this, Android complains when it calls unregister, insisting that the receiver is not there to unregister (I forget the exact wording, but it threw IllegalArgumentException).
I also tried modifying the code to check that the action in 'intt' is the same as expected -- but then it still executest onReceive but silently fails to unregister.

A: The answer to your question is "yes". However...
...you need to call unregisterReceiver() on the same Context that you called registerReceiver() on. In the code you posted you are calling unregisterReceiver() on the Context passed in as an argument to onReceive(). This is not the same Context which is why you are getting the exception.

A: I would simply say YES, no problem at all.
I use it for a one-time location fix for example, and can be used in other logics too without me seeing any problem to it.
Plus I've seen it around many times.

A: I have tried various solutions, finally I am doing it that way:
Registering:
MyApplication.getInstance().getApplicationContext().registerReceiver(sentReceiver, new IntentFilter(SENT));

SentReceiver:
public class SentReceiver extends BroadcastReceiver  {
    public void onReceive(Context context, Intent arg1) {
        switch (getResultCode()) {
            case Activity.RESULT_OK:
                Toast.makeText(context,
                        context.getString(R.string.sms_envoye), Toast.LENGTH_SHORT)
                        .show();
                break;
            case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                Toast.makeText(context,
                        context.getString(R.string.sms_defaillance_generique),
                        Toast.LENGTH_SHORT).show();
                break;
            case SmsManager.RESULT_ERROR_NO_SERVICE:
                Toast.makeText(context,
                        context.getString(R.string.sms_pas_de_service),
                        Toast.LENGTH_SHORT).show();
                break;
            case SmsManager.RESULT_ERROR_NULL_PDU:
                Toast.makeText(context,
                        context.getString(R.string.sms_pas_de_pdu),
                        Toast.LENGTH_SHORT).show();
                break;
            case SmsManager.RESULT_ERROR_RADIO_OFF:
                Toast.makeText(context,
                        context.getString(R.string.sms_radio_desactivee),
                        Toast.LENGTH_SHORT).show();
                break;
        }
        MyApplication.getInstance().getApplicationContext().unregisterReceiver(this);
    }

With MyApplication:
public class MyApplication extends Application {
    private static MyApplication mInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized MyApplication getInstance() {
        return mInstance;
    }
}


text:
Q: How to create image with 2 images ffmpeg I want create with 2 or more images a unique image combining all images that i pass as parameter. I start proving with 2 parameters.
    firstpart = "/home/princebot/mazos/cartas/CannonCard.png"
    secondpart = "/home/princebot/mazos/cartas/FireballCard.png"
    a = subprocess.Popen(["ffmpeg","-i", firstpart, "-filter_complex", "scale=120:-1,","-i", secondpart, "-filter_complex","hstack" , "output.png"],stdout=subprocess.PIPE)
    a.communicate()[0].decode('utf-8')

and the combine image dont create.

A: Assuming your scale will output the appropriate size use:
a = subprocess.Popen(["ffmpeg","-i", firstpart, "-i", secondpart, "-filter_complex","[0]scale=120:-1[s];[s][1]hstack" , "output.png"],stdout=subprocess.PIPE)


text:
Q: OpenCV face detection with Haar model gets stuck I am trying to use the opencv's CascadeClassifier for face detection.
Below is a simplified code from tutorial on opencv docs, which I am running.
The problem I have is that the call to CascadeClassifier::detectMultiScale() won't return (at least not after 20mins on the first frame). What could possibly cause this behaviour and how to fix it?
When I run the same code with the pre-trained LBP model, the classifier runs fast, without any problems. When I however uncomment the equalizeHist() call, as it is used in the tutorial, the LBP model gets stuck, similarly to the Haar model.
In answers to a similar questions, I have read that the classifier can take awfully long, when there is no face present.
With the equalized histogram my face on cam became somewhat overexposed, due to dark background. Maybe this could be part of the problem?
#include <opencv2/objdetect/objdetect.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <vector>

using namespace cv;

int main(int argc, const char* argv[])
{
    CascadeClassifier face_cascade;
    if(!face_cascade.load("haarcascade_frontalface_alt.xml"))
        return -1;

    VideoCapture capture(0);
    if (!capture.isOpened())
        return -1;

    UMat frame, frame_gray;

    for (;;) {
        capture >> frame;
        if (!frame.empty()) {
            cvtColor(frame, frame_gray, CV_BGR2GRAY);
            //equalizeHist(frame_gray, frame_gray);    // uncomment and LBP gets stuck too

            std::vector<Rect> faces;
            face_cascade.detectMultiScale(frame_gray, faces, 1.1, 2, 0|CV_HAAR_SCALE_IMAGE, Size(30, 30));

            for(size_t i = 0; i < faces.size(); ++i) {
                Point center(faces[i].x + faces[i].width*0.5, faces[i].y + faces[i].height*0.5);
                ellipse(frame, center, Size( faces[i].width*0.5, faces[i].height*0.5), 0, 0, 360, Scalar( 255, 0, 255 ), 4, 8, 0);
            }
        }

        imshow("Face detection", frame);

        if(waitKey(10) > 0)
            break;
    }

    return 0;
}


text:
Q: Add statistical information to the bottom of a graph I am try to add statistical information (min, max, quartile values, mean, median etc) regarding a given distribution to the bottom a graph (histogram, time series plot) in R.
I know the stats can be generated using the summary() function. However, does any know how to place such information at the bottom of a graph?
Its seems like it should be easy to do but I just can't find anything online regarding how  to do it. Is it even possible using R?
Any help would be gratefully appreciated!

A: Here is one way. For some dummy data
set.seed(2)
dat <- rnorm(100, mean = 3, sd = 3)

compute the summary
sdat <- summary(dat)

We can then paste together the names of the summary statistics and their values using paste(), and collapse this to a single string
summStr <- paste(names(sdat), format(sdat, digits = 2), collapse = "; ")

Note that I format the values of the statistics to have just two significant digits using format(). This can be added to the plot say as a subtitle use the title() function
op <- par(mar = c(7,4,4,2) + 0.1)
hist(dat)
title(sub = summStr, line = 5.5)
par(op)

I push the subtitle down the plot a little bit via argument line.


text:
Q: What is the overhead of having many projects in solution Scenario:
Let's say I have a project, that I would like to split to 3 subdomains and each to 3 layers.
That's 9 project instead of one, but the overall amount of code does not change.
Question
Can you quantify how build time, solution opening time, etc. grows when adding new projects to solution?


text:
Q: How to clean dirty data of dataframe (imported from csv file), filter nums and transfer into the float type There's a csv file, contains numbers, "***", "(X)" and NAN.
Then I use pd.read_csv() to import this into dataframe.
see: import data
but all values in df are "str" type. see: desc data
I want to filter the num and transfer them into float type and for the others to NAN.
Please help me. Thanks!

A: Try using the NaN filter of pd.read_csv(). For each column you can specify different values that should be considered NaN. In your case this should work:
df = pd.read_csv('your_file.csv', na_values={'HC04_VC03': '(X)', 'HC04_VC04': '***'})

Pandas will then automatically choose a fitting dtype for your data. In this case you get the desired float columns. You can also specify the data type as you read in the csv file using the parameter dtype = {'GEO.id2': np.int64, 'HC04_VC04': np.float64, 'HC02_VC05': np.float64} or any other valid dtypes of your choice. Use this option with care since setting the dtype will throw an error if the data cannot be converted to the desired type, e.g. if you don't get rid of all '***' strings first.
Alternatively, you could read in the csv file without specifying data types, and then convert the columns after using pd.to_numeric. For example,
df['GEO.id2'] = pd.to_numeric(df['GEO.id2'], errors = 'ignore') # values that can't be converted to integer types will be left alone

In the documentation, there are other methods for handling data that can't be converted.


text:
Q: Implement maintenance logic - how to restrict further API calls in angular we are working in angular 9 application where we have multiple components. some components are connected with parent-child relation and other components are independent. we are making one initial API call that will return the flag value true/false, based upon the value we need to execute further. i.e. if it is "true" we need to make further calls or else stop the execution.
homecomponent.html :

<div>
//header is child component
<app-header>

       </app-header>
.......
......
</div>

homecomponent.ts:

export class HomeComponent implements OnInit {

ngOnInit(): void {
this.getPageConent();
}

getPageConent() {
// below service will make the http call

    this.dataService.GetPovertyPageStaticContent('home').subscribe((result: any) => {
// based upon the flag execute further or stop execution
 });
  }
}

headercomponent.ts:

export class HeaderComponent implements OnInit {

ngOnInit(): void {
 this.getContents();
}
 getContents() {
  // Another API call to get page data
    this.dataService.GetPovertyPageStaticContent('pageheader').subscribe((result: any) => {

     //do some operation
    });
  }
}

Like that, we have multiple components are connected with one another. We want to restrict the other API calls in the application based upon the initial API call value.

A: Would that be enough ?
this.dataService
  .GetPovertyPageStaticContent('home')
  .pipe(filter(v => !!v))
  .subscribe(...)

If the result is false, this will prevent the subscribe from executing.

A: Following your explanation on my other answer, what you are looking for is called an interceptor.
You can find the documentation here
You will have to create a service that holds your condition at all times (so make it a singleton). When the condition is met, the interceptor can process the requests to the API. If the condition is not met, then the interceptor can simply return an EMPTY observable (an observable that completes without ever emitting).
Although, I would say that the best option is to do this logic on your API rather than your client app, I think this approach is the best solution to your question.


text:
Q: Creating Mulitlanguage Chrome extension What would be the best practice to write a chrome extension in multiple languages?
I know about the chrome.i18n infrastructure to provide language-specific resources WITHIN the extension.
But in the chrome store I can only offer ONE description. Now I want to offer my plugin in two languages: german/english
Should I just upload two versions with the same name and different language settings? Is that even possible?
Does the store automaticly only display one of those two extensions corresponding to the users language?

A: Unfortunately there doesnt appear to be a way to provide store descriptions in multiple languages, I had the same problem recently. The problem with publishing two is that stars and total users will be independent for each. Usually helps to show a large number of users to convince people to install it.


text:
Q: Expanded Widget got exception(Each child must be laid out exactly once)? I have implemented app to read captured image text using Firebase ML kit,In my screen I have display the captured image and place a button bellow the image to read the image and display extract text below the button, but when I have click the button I got following exception,
"Each child must be laid out exactly once",
I have used Huawei GR5 Mini to test the app,
My code is,
 Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(
        title: Text(
          'Read PDF',
          style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: Colors.lightBlue),
        ),
        elevation: 0.0,
        backgroundColor: Colors.transparent,
        iconTheme: IconThemeData(color: Colors.blue),
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          Flexible(
            child: Container(
              height: 300,
              child: SingleChildScrollView(
                child: Padding(
                  padding: const EdgeInsets.only(
                      top: 20.0, left: 40.0, right: 40.0, bottom: 20.0),
                  child: Image.file(File(widget.imageRoute), fit: BoxFit.cover),
                ),
              ),
            ),
          ),
          SizedBox(
            height: 10,
          ),
          Center(
            child: FlatButton(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(18.0),
                  side: BorderSide(color: Colors.blue)),
              color: Colors.blue,
              textColor: Colors.white,
              padding: EdgeInsets.all(10.0),
              onPressed: () async {
                pickImage();
              },
              child: Text(
                "Read".toUpperCase(),
                style: TextStyle(fontSize: 12.0, fontWeight: FontWeight.bold),
              ),
            ),
          ),
          SizedBox(
            height: 10,
          ),
          Center(
            child: text == ''
                ? Text('Text will display here')
                : Expanded(
                    child: SingleChildScrollView(
                      child: Padding(
                        padding: const EdgeInsets.all(10.0),
                        child: SelectableText(
                          text,
                        ),
                      ),
                    ),
                  ),
          ),
        ],
      ),
    );
  }

A: You use expended in center widget. You can use like this:
Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(
        title: Text(
          'Read PDF',
          style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: Colors.lightBlue),
        ),
        elevation: 0.0,
        backgroundColor: Colors.transparent,
        iconTheme: IconThemeData(color: Colors.blue),
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Container(
            height: 300,
            child: SingleChildScrollView(
              child: Padding(
                padding: const EdgeInsets.only(
                    top: 20.0, left: 40.0, right: 40.0, bottom: 20.0),
                child: Image.network("https://i1.wp.com/www.muratoner.net/wp-content/uploads/2019/01/flutterlogo.png?fit=800%2C800&ssl=1", fit: BoxFit.cover),
              ),
            ),
          ),
          SizedBox(
            height: 10,
          ),
          Center(
            child: FlatButton(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(18.0),
                  side: BorderSide(color: Colors.blue)),
              color: Colors.blue,
              textColor: Colors.white,
              padding: EdgeInsets.all(10.0),
              onPressed: () async {
                text = "Response text";
                setState(() {

                });
//                pickImage();
              },
              child: Text(
                "Read".toUpperCase(),
                style: TextStyle(fontSize: 12.0, fontWeight: FontWeight.bold),
              ),
            ),
          ),
          SizedBox(
            height: 10,
          ),
          text == ''
              ? Text('Text will display here',textAlign: TextAlign.center,)
              : Expanded(
            child: SingleChildScrollView(
              child: Padding(
                padding: const EdgeInsets.all(10.0),
                child: SelectableText(
                  text,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

A: I solve the same issue, although the above solution is correct but it seems to fail sometimes.
try this command in terminal in android studio.
1.   flutter clean
2.   flutter run


text:
Q: Verify a matrix value on MATLAB 2
*

*I am using MATLAB. I have a question about how i can verify that the values of a matrix are being repeating, like this:

A=[ 2 3 2 3 2 3 2 3]
with the answer AUX=1
If the matrix A repeat at least the first two values for all columns after, i want a AUX = 1. but if not, only AUX= 0.
or
A=[ 2 3 3 2 2 3 3 2]
with the answer AUX=1
If the matrix A repeat like before, i want a AUX = 1. but if not, only AUX= 0.

*

*The matrix A can also have zeros numbers after the numbers. (example, A = [ 1 2 1 2 1 0 0 0], A = [ 2 3 3 2 2 3 3 2 0 0 0 ].)

A: I think you are looking for this, finding whether the same two numbers are used in each non overlapping window of 2 values:
% Cutting off the tail
x = [1 2 2 1 1 2 1 2 0 0];
x = x(1:find(x,1,'last'));
x = x(1:2*fix(numel(x)/2));

% Checking for allowed values (the first 2 values, each one once)
M=sort(reshape(x,2,[]));
AUX = size(unique(M','rows'),1)==1

Note that this cuts of trailing zeros, so you may need an extra step if the number of remaining elements is not always odd but that should be easy.

A: % A
A = [1 2 3 4 4 5; 1 3 4 5 6 5; 6 7 4 1 3 3];
% make A a column vector
A_col = A(:);
% calculate histogram of A with max(A_col) bins
n = hist(A_col, max(A_col));
AUX = sum(n > 1) > 0


text:
Q: How to enable responsive design for Fabric.js Is there a way to make a Fabric.js canvas resize with the browser to enable the same result on any device? I'm talking about responsive design.
Has anyone a code example?

A: I know it's been a while but i found an easier way to do it using the zoom feature.
This code is triggered when the window resize is completed. It allows me to determine based on the new dimension, the zoom factor needed to resize everything in the canvas.

function rescale_canvas_if_needed()
{
 var optimal_dimensions = get_optimal_canvas_dimensions();
 var scaleFactor=optimal_dimensions[0]/wpd.canvas_w;
 if(scaleFactor != 1) {
  wpd_editor.canvas.setWidth(optimal_dimensions[0]);
  wpd_editor.canvas.setHeight(optimal_dimensions[1]);
  wpd_editor.canvas.setZoom(scaleFactor);
  wpd_editor.canvas.calcOffset();
  wpd_editor.canvas.renderAll();
  }
}

$( window ).resize(function() {
 clearTimeout(resizeId);
 resizeId = setTimeout(handle_resize, 500);
 });

 function handle_resize()
 {
 $(".canvas-container").hide();
 rescale_canvas_if_needed();
 $(".canvas-container").show();

 }

A: i thought this one was the answer I needed https://stackoverflow.com/a/29445765/1815624
it seemed so close but after some adjustments I got what I wanted it down scales when needed and maxes out at a scale of 1.
The canvas size you desire should be set as width/height var optimal_dimensions = [1000,1000];
this needs some more changes to handle height as well so when a user rotates there phone to landscape it may become to big to see it all on the screen
the new edited code will be at 1000 pixels in width and height for this demo
update: added detection for height and width to scale to window...

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas id="canvas" width="1000" height="1000"></canvas>

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.0.0/fabric.min.js"></script>
   <script>
  var canvas = new fabric.Canvas('canvas');
  canvas.add(new fabric.Circle({ radius: 30, fill: '#f55', top: 100, left: 100 }));

  canvas.item(0).set({
    borderColor: 'gray',
    cornerColor: 'black',
    cornerSize: 12,
    transparentCorners: true
  });
  canvas.setActiveObject(canvas.item(0));
  canvas.renderAll();

function rescale_canvas_if_needed(){
    var optimal_dimensions = [400,400];
    var scaleFactorX=window.innerWidth/optimal_dimensions[0];
    var scaleFactorY=window.innerHeight/optimal_dimensions[1];
    if(scaleFactorX <  scaleFactorY && scaleFactorX < 1) {
        canvas.setWidth(optimal_dimensions[0] *scaleFactorX);
        canvas.setHeight(optimal_dimensions[1] *scaleFactorX);
        canvas.setZoom(scaleFactorX);
    } else if(scaleFactorX >  scaleFactorY && scaleFactorY < 1){
        canvas.setWidth(optimal_dimensions[0] *scaleFactorY);
        canvas.setHeight(optimal_dimensions[1] *scaleFactorY);
        canvas.setZoom(scaleFactorY);
    }else {
        canvas.setWidth(optimal_dimensions[0] );
        canvas.setHeight(optimal_dimensions[1] );
        canvas.setZoom(1);
    }

    canvas.calcOffset();
    canvas.renderAll();
}

function handle_resize(){
    $(".canvas-container").hide();
    rescale_canvas_if_needed();
    $(".canvas-container").show();

}
var resizeId = null;
$(function() {
    $(window).resize(function() {
        if(resizeId != null)
        clearTimeout(resizeId);
        resizeId = setTimeout(handle_resize, 500);
     });
    console.log( "ready!" );
    /* auto size it right away... */
    resizeId = setTimeout(handle_resize, 500);
});
    </script>

hope this helps someone...good day.

A: This jsFiddle is a working solution. It is inspired by this github issue.
These are the required things:
A div that surrounds the canvas that is controlled by fabric.
<div class="fabric-canvas-wrapper">
    <canvas id="theCanvas"></canvas>
</div>

And a window resize handler that triggers the calculation and setting of the new canvas dimension and the zoom.
window.onresize = resizeCanvas() {
    const outerCanvasContainer = document.getElementById('fabric-canvas-wrapper');

    const ratio          = canvas.getWidth() / canvas.getHeight();
    const containerWidth = outerCanvasContainer.clientWidth;
    const scale          = containerWidth / canvas.getWidth();
    const zoom           = canvas.getZoom() * scale;

    canvas.setDimensions({width: containerWidth, height: containerWidth / ratio});
    canvas.setViewportTransform([zoom, 0, 0, zoom, 0, 0]);
}

That's all. It seems to work perfectly. Please let me know if any issues come up with this solution.
I have used fabric.js in version 3.6.2.

A: Basically you need to get the device screen's width and height. Afterwards just resize the canvas accordingly in your Javascript. Example:
var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
var height = (window.innerHeight > 0) ? window.innerHeight : screen.height;
var canvas = document.getElementById("canvas");
canvas.width = width;
canvas.height = height;

You might have screens with varying resolution ratios though, what I usually do in this case is calculate your original width's and the device's width ratio and then adjust both width and height accordingly with that value. Example:
var originalWidth = 960;  //Example value
var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
var widthRatio = originalWidth / width;
canvas.width *= widthRatio;
canvas.height *= widthRatio;

This usually works fine for me on any device, hope this helps.

A: Resize the canvas depending on the size of an element with jQuery.
window.addEventListener('resize', resizeCanvas, false);
function resizeCanvas() {
    canvas.setHeight(jQuery('#image').height());
    canvas.setWidth(jQuery('#image').width());
    canvas.renderAll();
}
resizeCanvas();


text:
Q: Setting value and key for Haneke Shared.JSONCache is throwing an error I'm trying to cache json I get back from a service using HanekeSwift but I get a syntax error saying "Cannot invoke 'set' with an argument list of type '(value: JSON, key:String, formatName: String, success: (_) -> _)'"
Here is my code for setting the cache:
let cache = Shared.JSONCache
var myJON = SwiftyJSON.JSON(responseData)
cache.set(value: myJSON, key: "key", formatName: HanekeGlobals.Cache.OriginalFormatName, success: {resultData in

})

This worked fine for me when I cached images as NSData. Only difference now is that my cache is a Shared.JSONCache and the value is of JSON type.


text:
Q: How do I fix this error in Python Django involving request.user.is_authenticated() and bool object not callable? I am trying to make profile pages for each user. I added a code that checks if the user is logged in and does a redirect (see line 12 of the code below).
from django.shortcuts import render
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect, HttpResponse

from .models import Account, ForSale, WTB

from mysite.forms import MyRegistrationForm

def signup(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect('/user/')
    else:
        if request.method == 'POST':
            form = MyRegistrationForm(request.POST)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect('/user/')

        context = {}
        context.update(csrf(request))
        context['form'] = MyRegistrationForm()

        return render(request, 'signup.html', context)

def index(request):
    return render(request, 'index.html')

However, upon accessing /signup/ on the site I get the following debug message:
TypeError at /signup/
'bool' object is not callable
Request Method: GET
Request URL:    http://url:8000/signup/
Django Version: 2.0
Exception Type: TypeError
Exception Value:
'bool' object is not callable
Exception Location: /www/mysite.com/mysite/views.py in signup, line 13
Python Executable:  /usr/bin/python3
Python Version: 3.5.2
Python Path:
    ['/www/mysite.com',
    '/usr/lib/python35.zip',
    '/usr/lib/python3.5',
    '/usr/lib/python3.5/plat-x86_64-linux-gnu',
    '/usr/lib/python3.5/lib-dynload',
    '/usr/lib/python3.5/site-packages',
    '/usr/local/lib/python3.5/dist-packages',
    '/usr/lib/python3/dist-packages']
Server time:    Sun, 3 Dec 2017 18:07:54 -0800

A: In older versions of Django request.user.is_authenticated was a method. It's now an attribute and no longer requires parenthesis. If you change your code to:
if request.user.is_authenticated:
It should be work as expected.
For more info see the docs here: https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#django.contrib.auth.models.User.is_authenticated

A: you forget to import csrf module please try to add this line and make sure to avoid hardcoded urls try to use url names
from django.core.context_processors import csrf


text:
Q: SIM 800L cannot connect to at I am trying to send some data using the sim800l module.
I am using the SoftwareSerial library and connected the RX and TX pins to Digital pins 10 and 11. I have also tried pins 2 and 3.
The module is connected to a 5v power supply and the only pins connected to the Arduino board are RX and TX.
The module is connected to the network.
this is the code I am using:
#include <SoftwareSerial.h>
SoftwareSerial myGsm(10,11);

void setup()
{
 myGsm.begin(9600);
 Serial.begin(9600);
 delay(500);

 myGsm.println("AT+CGATT=1");
 delay(200);
 printSerialData();

 myGsm.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");//setting the SAPBR,connection type is GPRS
 delay(1000);
 printSerialData();

 myGsm.println("AT+SAPBR=3,1,\"APN\",\"\"");//setting the APN,2nd parameter empty works for all networks
 delay(5000);
 printSerialData();

The problem is that nothing gets printed in the serial monitor.
I used the module to send sms messages using the FONA library and it worked.
Please help!

A: I think the problem is,
To print something on the serial monitor, you need to use the Serial.println();
The softwareSerial println only sends data to the devices connected to that pins.


text:
Q: Alternativas para armazenar e analisar dados Uma parte de um projeto que estou desenvolvendo é adquirir dados de tensão e corrente de uma placa solar. Por dia eu tenho em torno de 40 medidas como estas que estão aqui.
14/dez  16:54   18.21   0.12    18.35   0.0641
14/dez  16:54   17.82   0.27    17.98   0.2041
14/dez  16:54   17.42   0.44    17.61   0.3041
14/dez  16:54   14.23   0.39    15.30   0.3841
14/dez  16:54   5.92    0.63    7.45    0.6741
14/dez  16:54   4.97    0.54    6.50    0.6441
14/dez  16:54   4.56    0.48    5.91    0.5641
14/dez  16:54   3.51    0.68    4.59    0.7541
14/dez  16:55   2.32    0.60    2.97    0.6841
14/dez  16:55   2.19    0.51    2.76    0.6041
14/dez  16:55   2.13    0.44    2.67    0.5041
14/dez  16:55   0.71    0.67    0.90    0.7641
14/dez  16:55   0.61    0.64    0.77    0.7441
14/dez  16:55   0.00    0.69    0.00    0.821

15/dez  06:04   17.67   0.13    17.61   0.051
15/dez  06:04   15.82   0.25    15.82   0.181
15/dez  06:04   12.41   0.30    13.00   0.231
15/dez  06:04   8.09    0.22    8.72    0.161
15/dez  06:04   2.84    0.31    3.11    0.281
15/dez  06:04   2.38    0.25    2.60    0.191
15/dez  06:04   2.19    0.17    2.40    0.111
15/dez  06:04   1.69    0.36    1.79    0.301
15/dez  06:04   1.07    0.27    1.16    0.241
15/dez  06:04   1.02    0.21    1.10    0.171
15/dez  06:05   1.01    0.10    1.09    0.061
15/dez  06:05   0.33    0.32    0.35    0.311
15/dez  06:05   0.28    0.29    0.30    0.251
15/dez  06:05   0.00    0.33    0.00    0.312

Eu tenho que armazenar esses dados de modo que no futuro seja possível traçar gráficos escolhendo o dia e hora por exemplo.
O que quero é armazenar e depois recuperar os dados mais ou menos desta forma:

Ex grosseiro para recuperar: plot(data['14/12'].hora['07:00'].medidas)

Alguém sabe se da pra fazer isso usando banco de dados? Ou sugere outra solução para armazenar?
Se for em Python seria ainda melhor.
Obrigado

A: Para este exemplo coloquei (armazenei) exatamente os dados que colocaste num ficheiro e fui percorre-lo e retirar os dados, sendo que este ficheiro (tests.txt) está na mesma pasta do ficheiro com o código, podes tambem colocar (armazenar) num ficheiro.csv:
dados = {}
with open('tests.txt', 'r') as f:
    for line in f:
        params = [i.strip() for i in line.split('  ') if i.strip() != '']
        if not params:
            continue
        data, hora, v1, l1, v2, l2 = params
        dados[data] = dados.get(data, {})
        dados[data][hora] = dados[data].get(hora, [])
        dados[data][hora].append((v1, l1, v2, l2))

Nesta linha [i.strip() for i in line.split('  ') if i.strip() != '']. Nota que se puderes ficaria muito mais simples separar os dados por linha por só ex: ";" que ficaria: [i.strip() for i in line.split(';')] em vez de espaços inconstantes como puseste, e sem linhas vazias também se poderia retirar a verificação, if not params: continue.
No entanto este código é totalmente funcional para os dados/formato que colocaste
Consegues aceder a cada dia e/ou hora assim:
Dia:
print(dados['15/dez'])

Output:

{'06:05': [('1.01', '0.33', '0.28', '0.00'), ('0.10', '0.32', '0.29', '0.33'), ('1.09', '0.35', '0.30', '0.00'), ('0.061', '0.311', '0.251', '0.312')], '06:04': [('17.67', '0.13', '17.61', '0.051'), ('15.82', '0.25', '15.82', '0.181'), ('12.41', '0.30', '13.00', '0.231'), ('8.09', '0.22', '8.72', '0.161'), ('2.84', '0.31', '3.11', '0.281'), ('2.38', '0.25', '2.60', '0.191'), ('2.19', '0.17', '2.40', '0.111'), ('1.69', '0.36', '1.79', '0.301'), ('1.07', '0.27', '1.16', '0.241'), ('1.02', '0.21', '1.10', '0.171')]}

Hora (aqui acedes às várias medidas de cada hora):
print(dados['15/dez']['06:05'])

Output:

[('1.01', '0.33', '0.28', '0.00'), ('0.10', '0.32', '0.29', '0.33'), ('1.09', '0.35', '0.30', '0.00'), ('0.061', '0.311', '0.251', '0.312')]

Aqui vou deixar uma alternativa usando defaultdict:
from collections import [defaultdict][1]

dados = defaultdict(dict)
with open('tests.txt', 'r') as f:
    for line in f:
        params = [i.strip() for i in line.split('  ') if i.strip() != '']
        if not params:
            continue
        data, hora, v1, l1, v2, l2 = params
        if hora not in dados[data]:
            dados[data][hora] = []
        dados[data][hora].append((v1, l1, v2, l2))
print(dados)

A: Dá sim, mas acho desnecessário usar um banco de dados, visto que você não parecer ter muita experiência com isso.
Pesquise sobre CSV, você pode guardar seus dados em um .txt salvo dentro do projeto mesmo, quando precisar de novo é só reabrir o csv. Há diversas bibliotecas em python para te auxiliar no gerenciamento de arquivos CSV, é a forma mais fácil de se armazenar dados pequenos.
Caso queira um banco de dados você pode usar o Firebase, funciona pela nuvem e é bem simples de se usar. Para bancos locais recomendo SQLite.


text:
Q: Wireshark doesn't capture traffic - promiscuous mode? I am trying to create my own app to monitor LAN networks on Windows. I think this way: if Wireshark can capture packets on my home Wi-Fi, I will do it too. But Wireshark without any errors captures only packets like in this picture (I was capturing from Windows with IP address .66, mobile phone in network is .87).

I don't see any pages opened in device 87.

*

*Can you help me to understand why?

*If my Wi-Fi adapter does not support promiscuous mode, and it's needed to capture all packets from other devices, I can buy some USB Wi-Fi adapter which supports it. But how can I choose one?

*If Wireshark doesn't show any error, does it mean that promiscuous mode is enabled on my Wi-Fi adapter?

There is a lot of information about monitor mode on the Internet, but not too much about promiscuous mode. All help is appreciated. Please ask if I wrote something unclear.

A: If you're trying to capture WiFi traffic, you need to be able to put your adapter into monitor mode.  Since you're on Windows, my recommendation would be to update your Wireshark version to the latest available, currently 3.0.1, and install the latest npcap driver that comes with it, being sure to select the option to support raw 802.11 traffic (and "Monitor Mode") for wireless adapters.  That should be all you need.  Note that you may need to first turn on monitor mode using npcap's wlanhelper tool.
Download Wireshark from here.
Read more about npcap in the Npcap Users' Guide.
Read more about capturing WiFi traffic on the Wireshark WLAN (IEEE 802.11) capture setup wiki page.

A: No you don't need monitor mode. It's only useful for receiving every wifi packet from ALL wifi networks - this is what you want if you want to start attacking wifi networks (eg. capture handshakes).
When you are connected to a network it's going to be in another state.
When you are connected to a wifi network, or any network for the matter (ethernet), the gateway will pass the data to and from the host ONLY. Which means you will never receive the data intended from or to another machine.
If you take a look at your screenshot you will see that you will only see the data between you and the mobile phone: 192.168.0.67 -> 192.168.0.87 > 192.168.0.67.
What you want is a man in the middle attack. I'm not going to go into details about that but look it up.
It will allow you to read data between the victim and gateway (most likely router). Both ways hopefully.


text:
Q: Сортировка списка по возрастанию значения числа в Python
*

*Создайте класс объектов Auto для подержанных машин со следующими характеристиками:

*Марка.

*Модель.

*Год производства.

*Пробег.

*Цена.

*Отечественное или зарубежное производство.

*Создайте 5 объектов со следующими характеристиками:
KiaSor: «Kia», «Sorrento», 2003, 223 000 км, 415 000 руб, производство: Россия
HyunSol: «Hyundai», «Solaris», 2015, 41 000 км, 869 000 руб, производство: Корея
VolkPas: «Volkswagen», «Passat», 2012, 127 000 км, 900 000 руб производство: Германия
LadaPri: «Lada», «Priora», 2011, 139 000 км, 150 000 руб, производство: Россия
UazPat: «UAZ», «Patriot», 2011, 150 000 км, 345 400 руб, производство: Россия

*Создайте функцию, в результате которой возникнет список sortedByMileage, в котором содержатся все автомобили, рассортированные по пробегу ['Hyundai Solaris', '41000'], ['Volkswagen Passat', '127000'], ['Lada Priora', '139000'], ['UAZ Patriot', '150000'], ['Kia Sorrento', '223000']
У меня получается сортировка по возрастанию 1 2 3, а надо значения 41тыс. 127тыс.
[['Volkswagen Passat', '127000'], ['Lada Priora', '139000'], ['UAZ Patriot', '150000'], ['Kia Sorrento', '223000'], ['Hyundai Solaris', '41000']]
```
class Auto:
    def __init__(self, make, model, year, mileage, price, origin_ru):
        self.make= make
        self.model= model
        self.year= year
        self.mileage= mileage
        self.price= price
        self.orign_ru= origin_ru
    def getMake(self):
        return self.make
    def getModel(self):
        return self.model
    def getYear(self):
        return self.year
    def getMileage(self):
        return self.mileage
    def getPrice(self):
        return self.price
    def getOrign_ru(self):
        return self.origin_ru
    def makeModel(self):
        print('{} {}'.format(self.make, self.model))
    def getAttrValue(self, attr):
        return getattr(self, attr)
    def __repr__(self):
                def __repr__(self):
                        return f'{self.make}{self.model} - Price: RUR{self.price},Production Year: {self.year},Mileage: {self.mileage}'

KiaSor= Auto('Kia', 'Sorrento', 2003, 223000, 415000, 'Россия')
HyunSol= Auto('Hyundai', 'Solaris', 2015, 41000, 869000, 'Корея')
VolkPas= Auto('Volkswagen', 'Passat', 2012, 127000, 900000, 'Германия')
LadaPri= Auto('Lada', 'Priora', 2011, 139000, 150000, 'Россия')
UazPat= Auto('UAZ', 'Patriot', 2011, 150000, 345400, 'Россия')

sortedByMileage=[]
sortedByMileage1=['{} {}'.format(KiaSor.make, KiaSor.model),'{}'.format(KiaSor.mileage)]
sortedByMileage2=['{} {}'.format(HyunSol.make, HyunSol.model), '{}'.format(HyunSol.mileage)]
sortedByMileage3=['{} {}'.format(VolkPas.make, VolkPas.model), '{}'.format(VolkPas.mileage)]
sortedByMileage4=['{} {}'.format(LadaPri.make, LadaPri.model), '{}'.format(LadaPri.mileage)]
sortedByMileage5=['{} {}'.format(UazPat.make, UazPat.model), '{}'.format(UazPat.mileage)]
sortedByMileage=[sortedByMileage1,sortedByMileage2,sortedByMileage3,sortedByMileage4,sortedByMileage5]
def custom_key(sortedByMileage):
       return sortedByMileage[1]

sortedByMileage.sort(key=custom_key)
print (sortedByMileage)
```

A: вам нужна сортировка лямбда функцией.
В данном случае список groupx будет отсортирован по значению x.price
В принципе подставив туда любой другой параметр объекта можно сортировать и по другим основаниям.
sorted(groupx, key lambda x: x.price, reverse=True)


text:
Q: Html forms in Outlook cause security violation I have a simple form that I send in user's emails for resetting their password. It works in the Gmail client, but it doesn't work in Outlook.
<form action="${login_url}" method="post">
  <input type="hidden" name="email" id="email" value="${email}">
  <input type="hidden" name="pass" id="pass" value="${password}">
  <input type="submit" value="Password Reset">
</form>

In the console, I get the following error:

Refused to send form data to
'https://path/to/post-endpoint' because it violates the
following Content Security Policy directive: "form-action
*.officeapps.live.com".

Do I have to register my endpoint with MS Office or something? Or are there some HTML tags that I need to send in the email?


text:
Q: I need some help understanding the schematics of DIY HS102 oscilloscope I was looking on the schematics for the DIY HS102 oscilloscope by Martin Loren (http://hscope.martinloren.com/HS102-oscilloscope.html)
But I'm a bit confused about the role of the ASM1117 (LDO regulator ASM1117-1.2). it seems that the output is not used, so what's the point of having it?

A: I agree that the 1.2V regulator's output is not used, even on the drawing of the prototype board there's nothing connected to pin 2 (which is the output).
So the LDO only loads the 3.3 V line with it's quiescent current consumption.
I also see no reason why it is there. Removing it should not change anything.
Perhaps the author first thought he needed a 1.2 V and then later discovered that he didn't. Or indeed as Marcus suggests in the comments: the author didn't have a clue and just copied the design including superfluous components.

A: I'm guessing that the intent is to create an offset ground reference for the probes so that the one-sided (0 - 3.3V) measurement of the A-D can accommodate the +/-5V input claimed. The resistive dividers reduce that input down to +/-1.6V relative to the center point of the supply.
The setup of the firmware includes a step to ground the probes and calibrate the zero level, which would then subtract that offset from the input measurement, allowing a proper bipolar representation of the input voltage.
Obviously the regulator isn't configured correctly to do that  - there are a couple of resistors missing from the adjustment and the pinout is incorrect. It could be replaced by another 1k resistor and leave the circuit to function well enough with just a resistive divider, but there'd be a risk of the "Probe GND" suffering a small offset from a DC input on the probes, the regulator if it were functioning would minimize that.


text:
Q: BroadcastReceiver doesn't receive when bluetooth is connected I have added a BroadcastReceiver to my App:
public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
    //...
    }
}

which should get called, when my phone connects to a bluetooth device.
This is my Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.ginso.myplayer" >
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.BLUETOOTH"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        android:resizeableActivity = "true">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service
            android:name=".NotificationService"/>
        <receiver android:name=".MyReceiver">
            <intent-filter>
                <action android:name="android.bluetooth.adapter.action.ACL_CONNECTED"/>
                <action android:name="android.bluetooth.adapter.action.ACL_DISCONNECTED"/>
            </intent-filter>
        </receiver>
    </application>

</manifest>

But when i connect my bluetooth haedphone to my device, the onReceive doesn't get called. I have android 6 and i check all 3 permissions in the onCreate of my MainActivity and they are all granted(i only had to request WRITE_EXTERNAL_STORAGE however). What am i doing wrong?


text:
Q: Elegantly implementing queue length indicators to ExecutorServices Why, oh why doesn't java.util.concurrent provide a queue length indicators for  its ExecutorServices? Recently I found myself doing something like this:
ExecutorService queue = Executors.newSingleThreadExecutor();
AtomicInteger queueLength = new AtomicInteger();
...

public void addTaskToQueue(Runnable runnable) {
    if (queueLength.get() < MAX_QUEUE_LENGTH) {
        queueLength.incrementAndGet(); // Increment queue when submitting task.
        queue.submit(new Runnable() {
            public void run() {
                runnable.run();
                queueLength.decrementAndGet(); // Decrement queue when task done.
            }
        });
    } else {
        // Trigger error: too long queue
    }
}

Which works ok, but... I think this really should be implemented as a part of the ExecutorService. It's dumb and error prone to carry around a counter separated from the actual queue, whose length the counter is supposed to indicate (reminds me of C arrays). But, ExecutorServices are obtained via static factory methods, so there's no way to simply extend the otherwise excellent single thread executor and add a queue counter. So what should I do:

*

*Reinvent stuff already implemented in JDK?

*Other clever solution?

A: There is a more direct way:
ThreadPoolExecutor executor = new ThreadPoolExecutor( 1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>() );
// add jobs
// ...
int size = executor.getQueue().size();

This is directly copied from Executors.newSingleThreadExecutor in JDK 1.6. The LinkedBlockingQueue that is passed to the constructor is actually the very object that you will get back from getQueue.

A: While you can check the queue size directly. Another way of dealing with a queue that's getting too long is making the internal queue bounded.
public static
ExecutorService newFixedThreadPoolWithQueueSize(int nThreads, int queueSize) {
  return new ThreadPoolExecutor(nThreads, nThreads,
                              5000L, TimeUnit.MILLISECONDS,
                              new ArrayBlockingQueue<Runnable>(queueSize, true));
}

This will cause RejectedExecutionExceptions (see this) when you exceed the limit.
If you want to avoid the exception the calling thread can be hijacked to execute the function. See this SO question for a solution.
References

*

*ThreadPoolExecutor


text:
Q: Sending data with POST via link_to tag Have been dealing with this issue for some time and searched through the whole net, but nothing seems to be useful.
I'm trying to post data through a link_to tag like this:
// get_doctors.html.erb
<%= link_to "Ekle", patient_add_doctor_path(id: @patient.id), data: { doctor: doctor.id }, method: :post  %>

However, at the controller, I can not reach the data in my controller.
// patients_controller.rb

def add_doctor
    patient = Patient.find(params[:id].to_i)
    doctor  = Doctor.find(params[:doctor].to_i) // problem is here!
    patient.doctors << doctor
end

It gives me the error that params[:doctor] is 0.
Couldn't find Doctor with 'id'=0 [WHERE "users"."type" IN ('Doctor')]
Have tried many different ways. Tried also this,
<%= link_to "Ekle", patient_add_doctor_path(id: @patient.id), doctor: doctor.id, method: :post  %>

which is also did not worked.


text:
Q: Find $E[(X+Y)^2]$ given $E(X^2)=3$ $E(Y^2)=4$ and $E(XY) = 2$ I know this is an easy question but I'm having problems solving it
I sorta thought that you'd get $E(X^2) + 2E(XY) + E(Y^2)$ and that'd add up to: $3+4+4=11$ but my answer isn't correct. I'm guessing my intuition is definitely wrong
Thanks a lot.

A: First, observe that we have
$E((X+Y)^2) = E(X^2 + 2XY + Y^2)$
The key property that we will use is Linearity of expectation. This says for any random variables $X$ and $Y$, and any constants $a$ and $b$, we have
$$E(aX + bY) = aE(X) + bE(Y)$$
Applying this to what we did above, we get
$$E(X^2 + 2XY + Y^2) = E(X^2) + 2E(XY) + E(Y^2)$$
So your initial thought was correct.


text:
Q: How to Select Corresponding div for given button? Here I have five buttons and five divs. If I click the first button then some data should be filled in first div only, not the others. The same goes for the consecutive buttons. I am doing this in jQuery.
$(document).ready(function () {
    $(".btn").each(function () {
        // code  here to put some data in relative div
    });
});

<button type="button" class="btn">Button 1</button>
<button type="button" class="btn">Button 2</button>
<button type="button" class="btn">Button 3</button>
<button type="button" class="btn">Button 4</button>
<button type="button" class="btn">Button 5</button>

A: Firstly note that if you want this to happen when the buttons are clicked you should use the click() method, not each().
To make it work you can use the index() method to find the index of the clicked button and the eq() method to relate that index to the relevant .myDiv. Try this:

$(".btn").click(function() {
  var index = $(this).index('button');
  $('.myDiv').eq(index).text('clicked button ' + (index + 1));
});

<button type="button" class="btn">Button 1</button>
<button type="button" class="btn">Button 2</button>
<button type="button" class="btn">Button 3</button>
<button type="button" class="btn">Button 4</button>
<button type="button" class="btn">Button 5</button>