Q: Getting empty string on h:selectOneMenu I do not know why it is empty because I have the same piece of code in my system for a user register.
This is mu xhtml page
<!DOCTYPE html>

<ui:composition template="/template/main.xhtml">
    <ui:define name="content">

             Denunciar

            <h:form id="cadastrarDenuncia" styleClass="form-horizontal" p:role="form">

                <h:inputHidden value="#{denunciaBean.denuncia.ndenuncia}"/>

                           <h:outputLabel for="idTipoCrime" class="col-md-4 control-label">Tipo de Crime: </h:outputLabel>

                             <h:selectOneMenu class="form-control" id="idTipoCrime" value="#{denunciaBean.denuncia.tipoCrime}" required="true" requiredMessage="Campo obrigatório!">
                                <f:selectItem itemValue="" itemLabel="Selecione"/>
                                <f:selectItem itemValue="Roubo" itemLabel="Roubo"/>
                                <f:selectItem itemValue="Furto" itemLabel="Furto"/>
                                <f:selectItem itemValue="TraficoEntorpecentes" itemLabel="Tráfico de Entorpecentes"/>
                                <f:selectItem itemValue="Homicidio" itemLabel="Homicídio"/>
                                <f:selectItem itemValue="Latrocinio" itemLabel="Latrocício"/>
                                <f:selectItem itemValue="Receptacao" itemLabel="Receptação"/>
                                <f:selectItem itemValue="Estupro" itemLabel="Estupro"/>
                                <f:selectItem itemValue="Quadrilha" itemLabel="Quadrilha"/>
                                <f:selectItem itemValue="CrimeAmbiental" itemLabel="Crime Ambiental"/>
                                <f:selectItem itemValue="Sequestro" itemLabel="Sequestro"/>
                                <f:selectItem itemValue="ViolenciaDomestica" itemLabel="Violência Doméstica"/>
                                <f:selectItem itemValue="Assassinato" itemLabel="Assassinato"/>
                                <f:selectItem itemValue="Agressao" itemLabel="Agressão"/>
                                <f:selectItem itemValue="Ameaca" itemLabel="Ameaça"/>
                                <f:selectItem itemValue="Pedofilia" itemLabel="Pedofilia"/>
                             </h:selectOneMenu>

<h:message for="idTipoCrime"/>

                            <h:outputLabel class="col-md-4 control-label">Clique no local aproximado do acontecimento: </h:outputLabel>

                            <h:inputHidden id="lat" value="#{denunciaBean.denuncia.latitude}" />
                            <h:inputHidden id="lng" value="#{denunciaBean.denuncia.longitude}" />

                            <h:outputLabel class="col-md-4 control-label" for="idDataHoraCrime">Data e Hora do crime: </h:outputLabel>

                                <h:inputText id="data" label="Data e Hora do Crime" value="#{denunciaBean.denuncia.dataHoraCrime}"
                                size="16" maxlength="16" required="true">
                                    <f:convertDateTime dateStyle="long" pattern="dd/MM/yyyy HH:mm" />
                                </h:inputText>

<h:message for="idDataHoraCrime"/>

                            <h:outputLabel class="col-md-4 control-label" for="idObservacao">Observações: </h:outputLabel>

                                <h:inputTextarea class="form-control input-md" value="#{denunciaBean.denuncia.observacao}" id="idObservacao" placeholder="Observacao"/>

<h:message for="idObservacao"/>

                            <h:commandButton id="idConfirmarBt" styleClass="btn btn-primary" action="#{denunciaBean.salvar}" value="Confirmar"
                                onclick="if (!confirm('Confirmar denúncia?')) return false;"/>
                            <h:commandButton styleClass="btn btn-danger" value="Cancelar" onclick="redirecionar()"/>

            </h:form>

    </ui:define>
</ui:composition>

This is the class
package br.com.smartpatrolling.denuncia;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;

import br.com.smartpatrolling.usuario.Usuario;

@Entity
@Table(name = "denuncia")
public class Denuncia implements Serializable {

    private static final long serialVersionUID = -387555820515169694L;
    @Id
    @GeneratedValue
    private Integer ndenuncia;
    @ManyToOne
    // Permite excluir todas as denuncias do usuario ao excluir um usuário
    @OnDelete(action = OnDeleteAction.CASCADE)
    @JoinColumn(nullable = false)
    private Usuario usuario;
    private String tipoCrime;
    /** Local do crime */
    private double latitude;
    private double longitude;
    private String observacao;
    /** Data e hora aproximados do crime */
    private Date dataHoraCrime;
    /** Data e hora do cadastro da denuncia */
    @Column(nullable = false, updatable = false)
    private Date dataHoraCadastro;

    public Integer getNdenuncia() {
        return ndenuncia;
    }

    public void setNdenuncia(Integer ndenuncia) {
        this.ndenuncia = ndenuncia;
    }

    public Usuario getUsuario() {
        return usuario;
    }

    public void setUsuario(Usuario usuario) {
        this.usuario = usuario;
    }

    public String getTipoCrime() {
        return tipoCrime;
    }

    public void setTipoCrime(String tipoCrime) {
        this.tipoCrime = tipoCrime;
    }

    public String getObservacao() {
        return observacao;
    }

    public void setObservacao(String observacao) {
        this.observacao = observacao;
    }

    public Date getDataHoraCrime() {
        return dataHoraCrime;
    }

    public void setDataHoraCrime(Date dataHoraCrime) {
        this.dataHoraCrime = dataHoraCrime;
    }

    public Date getDataHoraCadastro() {
        return dataHoraCadastro;
    }

    public void setDataHoraCadastro(Date dataHoraCadastro) {
        this.dataHoraCadastro = dataHoraCadastro;
    }

    public double getLatitude() {
        return latitude;
    }

    public void setLatitude(double latitude) {
        this.latitude = latitude;
    }

    public double getLongitude() {
        return longitude;
    }

    public void setLongitude(double longitude) {
        this.longitude = longitude;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((dataHoraCadastro == null) ? 0 : dataHoraCadastro.hashCode());
        result = prime * result + ((dataHoraCrime == null) ? 0 : dataHoraCrime.hashCode());
        long temp;
        temp = Double.doubleToLongBits(latitude);
        result = prime * result + (int) (temp ^ (temp >>> 32));
        temp = Double.doubleToLongBits(longitude);
        result = prime * result + (int) (temp ^ (temp >>> 32));
        result = prime * result + ((ndenuncia == null) ? 0 : ndenuncia.hashCode());
        result = prime * result + ((observacao == null) ? 0 : observacao.hashCode());
        result = prime * result + ((tipoCrime == null) ? 0 : tipoCrime.hashCode());
        result = prime * result + ((usuario == null) ? 0 : usuario.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Denuncia other = (Denuncia) obj;
        if (dataHoraCadastro == null) {
            if (other.dataHoraCadastro != null)
                return false;
        } else if (!dataHoraCadastro.equals(other.dataHoraCadastro))
            return false;
        if (dataHoraCrime == null) {
            if (other.dataHoraCrime != null)
                return false;
        } else if (!dataHoraCrime.equals(other.dataHoraCrime))
            return false;
        if (Double.doubleToLongBits(latitude) != Double.doubleToLongBits(other.latitude))
            return false;
        if (Double.doubleToLongBits(longitude) != Double.doubleToLongBits(other.longitude))
            return false;
        if (ndenuncia == null) {
            if (other.ndenuncia != null)
                return false;
        } else if (!ndenuncia.equals(other.ndenuncia))
            return false;
        if (observacao == null) {
            if (other.observacao != null)
                return false;
        } else if (!observacao.equals(other.observacao))
            return false;
        if (tipoCrime == null) {
            if (other.tipoCrime != null)
                return false;
        } else if (!tipoCrime.equals(other.tipoCrime))
            return false;
        if (usuario == null) {
            if (other.usuario != null)
                return false;
        } else if (!usuario.equals(other.usuario))
            return false;
        return true;
    }
}

this is the bean
package br.com.smartpatrolling.web;

import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import org.primefaces.event.FlowEvent;

import br.com.smartpatrolling.denuncia.Denuncia;
import br.com.smartpatrolling.denuncia.DenunciaRN;

@ManagedBean(name = "denunciaBean")
@RequestScoped
public class DenunciaBean {

    private Denuncia denuncia = new Denuncia();
    private List<Denuncia> lista = null;
    @ManagedProperty(value = "#{contextoBean}")
    private ContextoBean contextoBean;

    public String salvar() {
        this.denuncia.setUsuario(this.contextoBean.getUsuarioLogado());
        DenunciaRN denunciaRN = new DenunciaRN();
        denunciaRN.salvar(this.denuncia);
        this.denuncia = new Denuncia();
        this.lista = null;
        return "minhasDenuncias";
    }

    public String excluir() {
        DenunciaRN denunciaRN = new DenunciaRN();
        denunciaRN.excluir(this.denuncia);
        this.denuncia = new Denuncia();
        this.lista = null;
        return null;
    }

    public List<Denuncia> getLista() {
        if (this.lista == null){
            DenunciaRN denunciaRN = new DenunciaRN();
            this.lista = denunciaRN.listarDenuncias(this.contextoBean.getUsuarioLogado());
        }
        return lista;
    }

    public void onPointSelect(ActionEvent event) {
        FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_INFO, "Point Selected", "Lat:" + denuncia.getLatitude() + ", Long:" + denuncia.getLongitude()));
    }

    public void setLista(List<Denuncia> lista) {
        this.lista = lista;
    }

    public Denuncia getDenuncia() {
        return denuncia;
    }

    public void setDenuncia(Denuncia denuncia) {
        this.denuncia = denuncia;
    }

    public String onFlowProcess(FlowEvent event) {
            return event.getNewStep();
    }

    public ContextoBean getContextoBean() {
        return contextoBean;
    }

    public void setContextoBean(ContextoBean contextoBean) {
        this.contextoBean = contextoBean;
    }
}

This is my data base when i make a dennounce. tipocrime is empty
enter image description here

A: My mistake was that I was using @RequestScoped instead of @ViewScoped in my bean.


Q: WHILE loop script I am trying to write a script that will continue to prompt a user to enter a grade, until the user enters 999.
If the user enters 90 or more, echo A.  If the user enters 80 or more, echo B.  If the user enters 70 or more, echo C.  Otherwise echo Failed.
I am thinking this needs a WHILE script.  Below is my current code
#!/bin/bash
# Asuume that the first paramter is going to be a grade
if [ $# -lt 1 ];
then
    echo -n "Please  pass a a grade "
fi
gr=$1
if [ $gr -ge 90 ]
then
    echo "A"
elif [ $gr -ge 80 ]
then
    echo "B"
elif [ $gr -ge 70 ]
then
    echo "C"
else
    echo "Failed"
fi
exit 0

The script prompts me, but closes after I enter 1 grade.
Thanks in advance

A: That's not a prompt, it's just a message.
Prompting would be:
read -p "Please pass a grade: " gr

But this get's into conflict with your following gr=$1, so put this into an else block:
if [ $# -lt 1 ]
then
    read -p "Please pass a grade: " gr
else
    gr=$1
fi

Note that you don't need a semicolon at the line end; it's the line break, which can be substituted by the semicolon.
And you don't need an exit to end a script, if you don't want to exit prematurely.

A: As you want to prompt the user to input grades until he enters 999, you should use read instead of command line arguments. As bash doesn't have a do-while loop, we can emulate it's behavior using while as shown below:
#!/bin/bash
read -p "Please  pass a grade " gr
while [ $gr -ne 999 ]; do
        if [ $gr -ge 90 ]
        then
            echo "A"
        elif [ $gr -ge 80 ]
        then
            echo "B"
        elif [ $gr -ge 70 ]
        then
            echo "C"
        else
            echo "Failed"
        fi
        read -p "Please  pass a grade " gr
done
exit 0

A: Please try below code.
 while  true
     do
       read -p "Please  pass a grade:" gr
       if [ ${gr} -eq 999 ]
          then
              exit 0
       elif [ ${gr} -ge 90 ]
          then
            echo "A"
       elif [ ${gr} -ge 80 ]
            then
                echo "B"
       elif [ ${gr} -ge 70 ]
           then
                echo "C"
            else
                echo "Failed"
       fi
    done


Q: String concatenation of algebric term I would like to add two integers and concatenate their result to a string, that is:
Add 1 to $i, and concatenate that result to the string 'icon'. I thought the following syntax would work:
$x = 'icon'.$i+1;

However it doesn't do what I want - it keeps returning the value 'icon1', disregarding the value of $i.
What's the right way to do what I want?

A: Try with:
$i = 0; // init $i
$x = 'icon'.($i+1);

If you want to regularly increment $i variable:
$x = 'icon'.(++$i);

A: try this :
$temp = $i+1;
$x = 'icon'.$temp;

You are getting wrong answer because of "Operator Precedence",
Ref this link : http://php.net/manual/en/language.operators.precedence.php
Here see the line : left   + - .   arithmetic and string
. has more Precedence than +, So your expression will be like : $x = ('icon'.$i)+1;
To solve it either use the method i mentioned above or hsz answer
ie : $x = 'icon'.($i+1);

A: Operator Precedence explains why this is happening.
You can use brackets:
$x = 'icon'.($i+1);

This should do the job.
My test:
$i = 18;
$x = 'icon'.($i+1);
var_dump($x);

--> string(6) "icon19"


Q: distributed associative domains in Chapel Are there any working examples of distributed domain maps for associative and/or opaque domains in Chapel, or any hints on how one would distribute a non-rectangular structure such as a graph over multiple locales? I know about distributed sparse arrays, but I am looking at less structured data. The documentation mentions a prototype domain map for associative domains -- is it available anywhere to experiment with? Thank you.

A: Yes, these distributed associative domains are new in 1.19 (which as of this writing will be released soon, but you can try them out using a master branch before then). The documentation for them here has an example:
https://chapel-lang.org/docs/master/modules/dists/HashedDist.html


Q: How to download files from a FTP using PhantomJS I have a file on a FTP Server. I´m trying to download it using PhantomJS. I´ve tried using the following code:
var page = require('webpage').create();

page.open('ftp://USERNAME:PASSWORD@www.mywebsite.com/exempleFIle.xlsx');
phantom.exit();

It runs without throwing any errors, however the file is not downloaded. Is it possible to download it with PhantomJS?
My main goal is synchronizing the files in the FTP with my computer, so I can put it in my Google Drive and from there using it in my reports. I use PhantomJS to access some webpages and get some data for the same purpose. Since I´m already using PhantomJS, I thought I could do the same for the ftp server, but if there is a simpler solution that use other methods, I´m open to trying it.
Thank You

A: PhantomJS is a headless web-browser, it's not an FTP client, so it won't be able to help you.

My main goal is synchronizing the files in the FTP with my computer

I'd suggest using lftp.
lftp -u user,password -e 'mirror /remote/server/files/ /local/computer/files/' ftp.myserver.com
This will get files from the remote server to the local computer.


Q: Symfony 3 - Form with OneToMany association in database I work on a OneToMany association in my database. This association work perfectly when I try to add data from fixtures and when I try to return data from database.
The problem is with my FormType CommandType which does'nt work. Symfony and Doctrine return this error message :

An exception occurred while executing 'INSERT INTO command_product (quantity, command_id, product_id) VALUES (?, ?, ?)' with params [3, null, 1]:\n\nSQLSTATE[23000]: Integrity constraint violation: 1048 Column 'command_id' cannot be null

CommandType's code :
class CommandType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('establishment', EntityType::class, array(
                'class' => Company::class,
                'required' => true
            ))
            ->add('dateCreation', DateTimeType::class, array(
                'widget' => 'single_text',
                'format' => 'yyyy-MM-dd',
                'required' => true
            ))
            ->add('contains', CollectionType::class, array(
                'entry_type' => CommandProductType::class,
                'required' => true,
                'allow_add' => true
            ))
            ->add('state',TextType::class, array(
                'required' => true
            ))
            ->add('totalAmount', MoneyType::class, array(
                'required' => true
            ));
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => Command::class
        ));
    }

    public function getBlockPrefix()
    {
        return 'appbundle_command';
    }
}

CommandProductType's code :
class CommandProductType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('quantity', NumberType::class, array(
                'required' => true
            ))
            ->add('product', EntityType::class, array(
                'class'    => Product::class,
                'required' => true
            ));
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => CommandProduct::class
        ));
    }

    public function getBlockPrefix()
    {
        return 'appbundle_commandproduct';
    }
}

Command's code class :
class Command
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var Company $establishment
     *
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Company")
     * @ORM\JoinColumn(name="establishment_id", referencedColumnName="id", nullable=false)
     */
    private $establishment;

    /**
     * @var DateTime $dateCreation
     *
     * @ORM\Column(name="dateCreation", type="datetime", nullable=false)
     * @Assert\Type("datetime")
     */
    private $dateCreation;

    /**
     * @var string $state
     *
     * @ORM\Column(name="state", type="string", length=255, nullable=false)
     * @Assert\Type("string")
     */
    private $state;

    /**
     * @var float $totalAmount
     *
     * @ORM\Column(name="totalAmount", type="float", precision=10, scale=2, nullable=false)
     * @Assert\NotBlank()
     * @Assert\Type(type="float")
     */
    private $totalAmount;

    /**
     * @var mixed $contains
     *
     * @ORM\OneToMany(targetEntity="AppBundle\Entity\CommandProduct", mappedBy="contain", cascade={"persist", "remove"})
     */
    private $contains;

    public function __construct()
    {
        $this->contains = new ArrayCollection();
    }

    /**
     * @var CommandProduct $commandProduct
     */
    public function addContain(CommandProduct $commandProduct = null)
    {
        $commandProduct->setContain($this);

        $this->contains->add($commandProduct);
    }

    /**
     * @param CommandProduct $commandProduct
     */
    public function removeContain(CommandProduct $commandProduct)
    {
        if ($this->contains->contains($commandProduct)) {
            $this->contains->removeElement($commandProduct);
        }
    }
}

CommandOrder's code class :
class CommandProduct
{
    /**
     * @var int $id
     *
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @var Command $contain
     *
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Command", inversedBy="contains")
     * @ORM\JoinColumn(name="command_id", referencedColumnName="id", nullable=false)
     */
    private $contain;

    /**
     * @var int $quantity
     *
     * @ORM\Column(name="quantity", type="integer", nullable=true, options={"default": 1})
     * @Assert\NotBlank()
     * @Assert\Type(type="int")
     */
    private $quantity;

    /**
     * @var Product $product
     *
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Product")
     * @ORM\JoinColumn(name="product_id", referencedColumnName="id")
     */
    private $product;
}


Q: Signalr: firsttime user, cannot get 'server button event' to 'hub' to 'client' to work hey guys I am trying out siqnalr for the first time and am having some issues getting it to work.
I can get the client to call the hub method with no issues.
I can get the hub to call the client with no issues.
But I want to call the hub from my server side button click event so I can update the client with processing info but no matter what I try I cannot get it to work.
does anyone have any ideas?
I am probably missing some thing simple but I have no idea what is wrong.
here is my code:
Global.asax
protected void Application_Start(object sender, EventArgs e)
    {
        RouteTable.Routes.MapHubs();
    }

TestHub.cs
  using System;
  using System.Linq;
  using Microsoft.AspNet.SignalR;

    namespace Hubs
    {

        ///
        /// Summary description for TestHub
        ///
        public class TestHub : Hub
        {

            public void Send(string name, string message)
            {
                // Call the broadcastMessage method to update clients.
                Clients.Caller.broadcastMessage(name, message);
            }

            internal static void Send2(string name, string message)
            {

                //test 1
                IHubContext context = GlobalHost.ConnectionManager.GetHubContext<TestHub>();
                context.Clients.All.Send(name, message);

                //test 2
                IHubContext context2 = GlobalHost.ConnectionManager.GetHubContext<TestHub>();
                context2.Clients.All.broadcastMessage(name, message);

            }

        }

    }

default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="Signalr2._default" %>

<!DOCTYPE html>

<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>

    <title></title>

    <form id="form1" runat="server">

        <telerik:RadScriptManager ID="RadScriptManager1" Runat="server">

        </telerik:RadScriptManager>

        <telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">

        </telerik:RadScriptBlock>

        <asp:Button ID="Button1" runat="server" Text="Server To Client Test" OnClick="Button1_Click" />

    </form>

default.aspx.cs
using System;
using System.Linq;
using Hubs;
using Microsoft.AspNet.SignalR;

namespace Signalr2
{
    public partial class _default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {

            //test 1
            IHubContext context = GlobalHost.ConnectionManager.GetHubContext<TestHub>();
            context.Clients.All.broadcastMessage("Now", DateTime.Now.ToString());

            //test 2
            IHubContext context2 = GlobalHost.ConnectionManager.GetHubContext<TestHub>();
            context2.Clients.All.Send("Now", DateTime.Now.ToString());

            //test 3
            TestHub.Send2("Now", DateTime.Now.ToString());

            string test = "";

        }
    }
}

A: Methods on hubs to be called from clients need to be public- try switching from Internal to Public for Send2-


Q: Returning Video file to a view on laravel 5.4 I am encountering a problem rendering video to my view in Laravel 5.4.
I have a view as follows:

    @if(!empty($video))
      <video id="my-video" class="video-js vjs-big-play-centered" controls data-setup="{}">
      <source src="{{url('video/'.$token.'/'.$video)}}" type="{{$video_mime_type}}">

          Please upgrade your browser.

        </video>
        @else

 Lesson video is unavailable!!!

        @endif

The route for getting the video content is as follows:
Route::get('video/{token}/{video}','ResourceController@show_video');

And the ResourceController class is as shown below:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Storage;
use Response;
use File;
use GuzzleHttp\Mimetypes;
use App\Mime;

class ResourceController extends Controller
{

 public function __construct()
{
   $this->middleware('auth')->only('show_video');
}
........
........
public function show_video($token,$filename)
{
    $token=\App\VideoPermission::where('token',$token)->first();
    if(!empty($token))
    {
    $token->delete();
    $mime_type=Mime::from_extension($filename);
    return response()->file(storage_path('app/lesson-files/'.$filename),[
        'Content-Type' => $mime_type,
        'Content-Disposition' => 'inline; filename="Lesson-file"'
        ]);
    }
    return false;
  }
}

When I play it on laptop browser, it plays well as expected but when I try to play the same video on a mobile phone browser (same Chrome browser on both situations), it throws the following exception:

UnexpectedValueException: The Response content must be a string or object implementing __toString(), "boolean" given. in /home/username/domainname.com/vendor/symfony/http-foundation/Response.php:409

Please could anyone help me figure out the source of the issue.
Thank you

A: I have later discovered that the problem is a result of an 'if' condition in the method that returns the file content. So, when the condition is not met for any reason, it returns 'false' as a response instead of the video file therefore resulting in the boolean response I receive.
That is the way the code is written to function when the required token is missing as shown below
if(!empty($token))
{
$token->delete();
$mime_type=Mime::from_extension($filename);
return response()->file(storage_path('app/lesson-files/'.$filename),[
    'Content-Type' => $mime_type,
    'Content-Disposition' => 'inline; filename="Lesson-file"'
    ]);
}
return false;

}
I later discovered that this happens when the user tries to access the application with an outdated browser which does not fulfill one of the conditions expected to return the video content.
In other words, the system is actually working as intended.
Thank you to all who tried to assist in one way or the other. I appreciate you all.


Q: How to show the custom user control(s) in flow layout panel dragging and at the same with a move icon mouse cursor in Winform in c#? How to show the custom user control(s) in flow layout panel dragging and at the same with a move icon mouse cursor in Winforms in c#?
I have been working on a Winforms Application and is using drag and drop functionality. I have the drag and drop functionality working, but need to make it more intuitive and user friendly.
Part of this will involve actually showing the item being dragged, preferably semi-transparent when dragging and also considered with the mouse down location at the item. What is the easiest way to do this?
The items I am dragging are custom user control(s) with text, pictures, data auto-created and in flow layout panel,but I am not even sure where to look for how to do this.
I added my code worked here :
A)   In the main form :
public main_form()
    {
        InitializeComponent();
        flowLayoutPanel1.AllowDrop = true;
        flowLayoutPanel1.DragDrop += new DragEventHandler(this.flowLayoutPanel1_DragDrop);
        flowLayoutPanel1.DragEnter += new DragEventHandler(this.flowLayoutPanel1_DragEnter);
        foreach (uploaded_items c in flowLayoutPanel1.Controls)
            c.MouseDown += new MouseEventHandler(c_MouseDown);
    }

    private void c_MouseDown(object sender, MouseEventArgs e)
    {
        uploaded_items data=new uploaded_items();
        foreach (uploaded_items c in flowLayoutPanel1.Controls)
        {
              if (c._isDragging == true) data = c;
        }
        Bitmap bmp = new Bitmap(data.Size.Width, data.Size.Height);
        data.DrawToBitmap(bmp, new Rectangle(Point.Empty, bmp.Size));
        bmp.MakeTransparent(Color.White);
        Cursor cur = new Cursor(bmp.GetHicon());
        Cursor.Current = cur;
    }

    private void flowLayoutPanel1_DragEnter(object sender, DragEventArgs e)
    {
        e.Effect = DragDropEffects.Move;
    }

    private void flowLayoutPanel1_DragDrop(object sender, DragEventArgs e)
    {
        uploaded_items data = (uploaded_items)e.Data.GetData(typeof(uploaded_items));
        FlowLayoutPanel _destination = (FlowLayoutPanel)sender;
        Point p = _destination.PointToClient(new Point(e.X, e.Y));
        var item = _destination.GetChildAtPoint(p);
        int index = _destination.Controls.GetChildIndex(item, false);
        _destination.Controls.SetChildIndex(data, index);
        _destination.Invalidate();

    }

B) In the user control :
public partial class uploaded_items : UserControl
{
    public uploaded_items()
    {
        InitializeComponent();
        AllowDrag = true;
    }

    public bool AllowDrag { get; set; }
    public bool _isDragging = false;
    private int _DDradius = 4;  //the min distance the mouse req to dragged so that drag action would be taken
    private int _mX = 0;        //positon on mouse down
    private int _mY = 0;

    protected override void OnGotFocus(EventArgs e)
    {
        this.BackColor = Color.SandyBrown;
        base.OnGotFocus(e);
    }

    protected override void OnLostFocus(EventArgs e)
    {
        this.BackColor = Color.Transparent;
        base.OnLostFocus(e);
    }

    protected override void OnClick(EventArgs e)
    {
        this.Focus();
        base.OnClick(e);
    }

    protected override void OnMouseDown(MouseEventArgs e)
    {
        this.Focus();
        base.OnMouseDown(e);
        _mX = e.X;
        _mY = e.Y;
        this._isDragging = false;
    }

    protected override void OnMouseMove(MouseEventArgs e)
    {
        if (!_isDragging)
        {
            // This is a check to see if the mouse is moving while pressed.
            // Without this, the DragDrop is fired directly when the control is clicked, now I have to drag a few pixels first.
            if (e.Button == MouseButtons.Left && _DDradius > 0 && this.AllowDrag)
            {
                int dist_x_dragged = e.X - _mX ;
                int dist_y_dragged = e.Y - _mY ;
                if (((dist_x_dragged ^ 2) + (dist_y_dragged ^ 2)) > _DDradius)
                {
                    DoDragDrop(this, DragDropEffects.All);
                    _isDragging = true;
                    return;
                }
            }
            base.OnMouseMove(e);
        }
    }

    protected override void OnMouseUp (MouseEventArgs e)
    {
        _isDragging = false;
        base.OnMouseUp(e);
    }

    #region Properties
    private string _title;
    private string _msg;
    private Image _icon;
    [Category("Custom Props")]
    public string title
    {
        get { return _title; }
        set { _title = value; lbl_title.Text = value; }
    }
    [Category("Custom Props")]
    public string msg
    {
        get { return _msg; }
        set { _msg = value; lbl_msg.Text = value; }
    }
    [Category("Custom Props")]
    public Image icon
    {
        get { return _icon; }
        set { _icon = value; pictureBox1.Image = value; }
    }
    #endregion
}

The primary drag and drop function is ok,
but I found I could not show the control / picture of the control dragging in this scheme:

*

*Limited area covered:
the bmp only appears when it's mouse down and dragged "carefully" on the user control, and it's only limited on the user control but not the text/ picture on the user control or the flow layout panel

*When I try to drag, the bmp disappeared

*the bmp is centered at mouse instantaneous location, but I wish it situated at the location at which the mouse initially down on the user control


Q: How to get output of a php file in separate html form at the middle of screen of lesser size How to get output of a php file in separate html form at the middle of screen of lesser size. See tyhe below part. It is not working. Help pl.

  <form>

   </form>

    <form id = "qform" name="qform" action="getques.php" style="visibility:hidden"
      method="post" target="_blank">
   <input type="text" name="subnm1" >

   <input type="text" name="chpno1" >

   <input type="text" name="qnumber1" >

   <input type="submit">
   </form>

The above code is opening a new window but i want the size of that window not full screen but less. How to do that?

A: If I understand your question then, The easiest way would be to open create a page which takes all these parameter as query string. You can then open the new page in the window by making it a hyperlink. The new page can also process your input by taking all these parameter from query string.

Submit


Q: LCC-- How to stop debugger from breaking at the start of the application? I'm not sure of how many users there are out there that use the LCC C compiler and the WEdit GUI for Windows but it has a "feature" that is can get to be quite annoying.  When you start an application with the debugger, it breaks the application at the start of the Main function.  How can I cut this off so that the debugger immediately executes the code until I halt it or it hits a break point that I've created?

A: Wow, people still use LCC... Last time I used it was ~10 years ago.
I decompiled wedit.exe and can confirm there is no official way to disable this behavior.
I patched the binary if that works for you. I uploaded it here.
To those who concerned about viruses and such I patched wedit taken from here. About box says it's version 4.0 compiled at Sep 16 2009.
Here is patched function to those who interested:
int __cdecl sub_44CF0D(HANDLE hProcess)
{
  int result; // eax@1
  int v2; // ST0C_4@10
  int v3; // eax@20
  int v4; // eax@23
  int v5; // eax@25
  int v6; // [sp+10h] [bp-68h]@11
  int v7; // [sp+14h] [bp-64h]@1
  struct _DEBUG_EVENT DebugEvent; // [sp+18h] [bp-60h]@1

  v7 = 1;
  result = WaitForDebugEvent(&DebugEvent, dwMilliseconds);
  if ( result )
  {
    sub_44C67A(&DebugEvent);
    if ( DebugEvent.dwDebugEventCode == 1 )
    {
      if ( DebugEvent.u.Exception.ExceptionRecord.ExceptionCode == EXCEPTION_ACCESS_VIOLATION
        && !(dword_482860 & 1)
        && !dword_484328
        && DebugEvent.u.Exception.dwFirstChance )
      {
        sub_44E1A5(0);
        sub_44CEB2(v2);
        return ContinueDebugEvent(DebugEvent.dwProcessId, DebugEvent.dwThreadId, 0x80010001u);
      }
      v6 = 0;
      v7 = sub_44D2C4((int)&DebugEvent, hProcess, (int)&v6);
      if ( v6 && DebugEvent.u.Exception.dwFirstChance )
        return ContinueDebugEvent(DebugEvent.dwProcessId, DebugEvent.dwThreadId, 0x80010001u);
      goto LABEL_41;
    }
    if ( DebugEvent.dwDebugEventCode == 3 )
    {
      if ( dword_483C94 )
      {
        dword_48428C = 1;
LABEL_41:
        if ( dword_483C6C )
          sub_44ECDC();
        if ( v7 )
        {
          result = ContinueDebugEvent(DebugEvent.dwProcessId, DebugEvent.dwThreadId, 0x10002u);
        }
        else
        {
          dword_49BF68 = 1;
          ResetEvent(dword_484AE4);
          dword_4843C8 = DebugEvent.dwThreadId;
          result = sub_4524CD();
        }
        return result;
      }
      Sleep(0x32u);
      dword_49BF64 = 1;
      dword_49BF68 = 1;
      qword_483C74 = __PAIR__(
                       (unsigned int)DebugEvent.u.Exception.ExceptionRecord.ExceptionAddress,
                       DebugEvent.u.Exception.ExceptionRecord.ExceptionInformation[2]);
      if ( dword_484288 )
        ::hProcess = (HANDLE)DebugEvent.u.Exception.ExceptionRecord.ExceptionFlags;
      else
        ::hProcess = hProcess;
      dword_483C84 = DebugEvent.dwProcessId;
      hThread = DebugEvent.u.Exception.ExceptionRecord.ExceptionRecord;
      dword_483C9C = (HANDLE)DebugEvent.u.Exception.ExceptionRecord.ExceptionCode;
      dwThreadId = DebugEvent.dwThreadId;
      dword_483C94 = 0;
      if ( sub_45A83A() )
      {
        v4 = sub_4026A6(28);
        dword_484330 = v4;
        *(_DWORD *)(v4 + 4) = hThread;
        *(_DWORD *)(v4 + 8) = dwThreadId;
        if ( dword_484288 )
        {
          sub_455B58();
        }
        else
        {
          Sleep(0x64u);
          v5 = sub_45AAFC();
          if ( !v5 )
            return PostMessageA(dword_4849EC, 0x111u, 0x64u, 0);
          if ( dword_484354 )
            goto LABEL_50;
          sub_455B58();
          if ( dword_483C70 && *(_DWORD *)(dword_483C70 + 52) )
            *(_DWORD *)(*(_DWORD *)(dword_483C70 + 52) + 36) = sub_451577(**(_DWORD **)(dword_483C70 + 52), 1u);
          v5 = *(_DWORD *)(dword_483C70 + 52);
          if ( v5 && *(_DWORD *)(v5 + 36) )
          {
LABEL_50:
            if ( !dword_483C6C )
              sub_44E92A(v5);
            sub_44CC3D();
            sub_451600();
            PostMessageA(dword_4849EC, 0x111u, 0x154u, 0);
          }
          else
          {
            sub_4029CA("Imposible to find %s\nRunning without source display", *(_DWORD *)(dword_483C70 + 20));
            dword_484344 = 1;
            v7 = 1;
            PostMessageA(dword_4849EC, 0x111u, 0x154u, 0);
          }
        }
        goto LABEL_41;
      }
      dword_484338 = 1;
      v3 = sub_44DB56(qword_483C74);
      if ( v3 )
        *(_BYTE *)(v3 + 29) &= 0xFDu;
      result = ContinueDebugEvent(DebugEvent.dwProcessId, DebugEvent.dwThreadId, 0x10002u);
    }
    else
    {
      if ( DebugEvent.dwDebugEventCode != 5 )
        goto LABEL_41;
      if ( DebugEvent.dwProcessId != dword_483C84 )
      {
        v7 = 1;
        goto LABEL_41;
      }
      dword_49BF64 = 0;
      dword_49BF68 = 1;
      dword_481614 = 0;
      result = sub_402A32(4520, SLOBYTE(DebugEvent.u.Exception.ExceptionRecord.ExceptionCode));
      if ( !dword_483C6C )
        result = sub_40B155(lpCmdLine);
    }
  }
  else
  {
    if ( dword_483C6C )
      result = sub_44ECDC();
  }
  return result;
}

if under LABEL_50 is what I patched (from 0x75 to 0xEB).
It was easy to spot the place because I expected WriteProcessMemory to be used to write 0xCC at entry-point of application that is being debugged.


Q: SCNShadable protocol gives internal error during fragment function compilation on newer devices We have written a shader modifier based on the SCNShadable protocol which works well until the number of uniform variables is rather slow (say 5-10). Later we needed to extend the shader modifier and use new uniforms, a total number of 25, including 8 textures and corresponding float4x4 matrices. Then it stopped working, could not compile the fragment function, which gave the following useless error message:
Error Domain=AGXMetalA12 Code=3 "Internal error during fragment function compilation" UserInfo={NSLocalizedDescription=Internal error during fragment function compilation}

When we reduced the number of float4x4 matrices to 2, it started to work again on an iPhone 7 and other Metal GPU Family 3 devices, but not on Metal GPU Family 4 or newer devices.
Our question is if someone knows any limitations that explain this kind of behaviour.


Q: How to get an array of files to upload I am running into a scenario that I cannot get more than one file to upload. If I add more than one file, only the last one will send through. I know this means I need to put the files into an array, but when I try I get an error from the fileUpload class.
IF I change the input html's name to `name="uploadedFile[]"' then I get the following error in my fileUpload class:

PHP Warning:  basename() expects parameter
1 to be string, array given in
/php/fileUpload.php on line 11
PHP Warning:  move_uploaded_file() expects parameter 1
to be string, array given in
/php/fileUpload.php on line 46

Then in my Communication class, you will see that if there is more than one file being uploaded, I send it as a zip, so I'm not sure if anything would need to be changed in there.
Does anyone see what I need to do to get the array to work?
HTML:
<input type="file" name="uploadedFile" class="inputfile" id="uploadedFileTest" data-multiple-caption="{count} files selected" multiple>

FileUpload class:
class fileUpload
{

    public function __construct()
    {}
    public function upload() {

        $target_dir = "uploads/";
        $target_file = $target_dir . basename($_FILES["uploadedFile"]["name"]);
        $uploadOk = 1;
        $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
// Check if $uploadOk is set to 0 by an error
        if ($uploadOk == 0) {
            return 0;
// if everything is ok, try to upload file
        } else {
            if (move_uploaded_file($_FILES["uploadedFile"]["tmp_name"], $target_file)) {
                return basename($_FILES["uploadedFile"]["name"]);
            } else {
                return 0;
            }
        }
    }
}

Rest of the php file:
$files = null;
if (!empty($_FILES['uploadedFile']['name']) && $_FILES['uploadedFile']['error'] != 4) {
    $fu = new fileUpload();
    $filename = $fu->upload();
    $template = str_replace("{filename}", "A file was uploaded. You can download the file from: {$filename}", $template);
    clearstatcache();
}

Communication Class - what sends out the attachment(s):
if (!empty($file) && !$recipient && count($file['uploadedFile']['name']) > 1) {

                $f = new ZipArchive();
                $zip = $f->open('uploads/' . $file['uploadedFile']['name'][0] . ".zip", ZipArchive::CREATE | ZipArchive::OVERWRITE);
                if ($zip) {
                    for ($index = 0; $index < count($file['uploadedFile']['name']); $index++) {
//                        echo $file['uploadedFile']['name'][$index] . "\n";
                        $f->addFile($file['uploadedFile']['tmp_name'][$index], $file['uploadedFile']['name'][$index]);
                    }
                    $f->close();

                    $message["attachment[0]"] = curl_file_create("uploads/{$file['uploadedFile']['name'][0]}.zip",
                        pathinfo("uploads/{$file['uploadedFile']['name'][0]}.zip", PATHINFO_EXTENSION),
                        $file['uploadedFile']['name'][0] . ".zip");
                } else {
                    throw new Exception("Could not zip the files.");
                }
//                $message['html'] = str_replace("{filename}", "A file was uploaded. You can download the file from: {$file['uploadedFile']['name']}", $message['html']);

            } elseif (count($file['uploadedFile']['name']) == 1) {
                $message["attachment[0]"] = curl_file_create("uploads/{$file['uploadedFile']['name']}",
                    pathinfo("uploads/{$file['uploadedFile']['name']}", PATHINFO_EXTENSION),
                    $file['uploadedFile']['name']);

            }

A: Try inspecting the $_FILES array to see the structure of a single file upload and a mulit-file upload.
Here is a small function you can use to visually inspect an array:
function varDumpToString($var, $type=false){
    ob_start();
    var_export($var);
    $return = ob_get_clean();

    return ($type === 'web'
        ? str_replace("\n", '
', $return)
        : $return
    );
}

Usage:
echo varDumpToString($_FILES, 'web');

Alternatively:
error_log(varDumpToString($_FILES));


Q: How to configure spark runner for apache beam pipeline for java I'm new to Apache Beam and Apace spark, i want to configure the beam pipeline for spark runner. what is mentioned in the documentation is not clear to me.

A: You can pass argument --runner SparkRunner to the pipeline launcher to use spark as the underlying runner. Also, Please share what language of Beam SDK you are using. Python and java have some what different ways to run on Spark via Beam.


Q: LLVM segmentation fault with opt command when i am trying to run the very simple (Hello world) pass given in llvm (my file is pass Hello.cpp) on a file XX.c
(X64 OS)
the opt command
opt -load ../../../Release+Asserts/lib/Hello.so -hello vv.bc > vv.txt

gives this error
0  libLLVM-3.2svn.so 0x00007f314b0f1e52
1  libLLVM-3.2svn.so 0x00007f314b0f22b3

2  libpthread.so.0   0x00007f314a0c7340

3  libstdc++.so.6    0x00007f31499645cb std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(std::string const&) + 11

4  libLLVM-3.2svn.so 0x00007f314aadef1d llvm::createPrintFunctionPass(std::string const&, llvm::raw_ostream*, bool) + 77

5  libLLVM-3.2svn.so 0x00007f314aad1585 llvm::PMTopLevelManager::schedulePass(llvm::Pass*) + 37

6  opt               0x0000000000413e4f main + 4767

7  libc.so.6         0x00007f31492eeec5 __libc_start_main + 245

8  opt               0x000000000040dfca
Stack dump:
0.  Program arguments: opt -load ../../../Release+Asserts/lib/Hello.so -hello vv.bc

Segmentation fault (core dumped)
any suggestion would be appreciable. I am new to both Linux and llvm

A: Something I found extremely useful is to use the verifier pass.
So first, make sure basic opt flow works as intended, and that the input file is legal:
opt -verify vv.bc -o out.bc

Then make sure your pass results in a legal module:
opt -load ../../../Release+Asserts/lib/Hello.so -hello -verify vv.bc -o out.bc

If that still won't help, I'd fire up the debugger.


Q: Is it possible to create fluent interface that can nest generic types many times in C# I'm trying to create a Fluent API that describes a nested structure and as a result I would like to use generics to type the resulting object. I would like to do something like:
var test = new Query<Entity>().Select(x => x.UniqueValue<string>())
                              .Select(x => x.UniqueValue<DateTime>())
                              .Select(x => x.UniqueValue<decimal>());

Where test would be of type:
Result<Entity, string, Result<Entity, DateTime, Result<Entity, decimal>>>

So far I have code like:
   class Program
{
    static void Main(string[] args)
    {
        // test : ResultWithResult<Entity,string, Result<Entity, DateTime, ChildLessResult<Entity, decimal>>>
        var test = new Query<Entity>().Select(x => x.UniqueValue<string>())
                                      .Select(x => x.UniqueValue<DateTime>())
                                      .Select(x => x.UniqueValue<decimal>());
    }
}

public class Entity
{
    public string Item1 { get; set; }
}

public class Aggregate<TEntity>
{
    public ChildLessResult<TEntity, TReturnValue> UniqueValue<TReturnValue>()
    {
        return new ChildLessResult<TEntity, TReturnValue>();
    }
}

public class Query<TEntity>
{
    public ChildLessResult<TEntity, TReturnValue> Select<TReturnValue>(Func<Aggregate<TEntity>, ChildLessResult<TEntity, TReturnValue>> predicate)
    {
        var aggregator = new Aggregate<TEntity>();
        return predicate(aggregator);
    }
}

public class ChildLessResult<TEntity, TReturnValue>
{
    public Result<TEntity, TReturnValue, TChild> Select<TChild>(Func<Aggregate<TEntity>, ChildLessResult<TEntity, TChild>> predicate)
    {
        return new Result<TEntity, TReturnValue, TChild>();
    }
}

public class Result<TEntity, TReturnValue, TChild>
{
    private ChildLessResult<TEntity, TChild> _child = new ChildLessResult<TEntity, TChild>();

    public ResultWithResult<TEntity, TReturnValue, Result<TEntity, TChild, ChildLessResult<TEntity, TNewChild>>> Select<TNewChild>(Func<Aggregate<TEntity>, ChildLessResult<TEntity, TNewChild>> predicate)
    {
        return new ResultWithResult<TEntity, TReturnValue,
            Result<TEntity, TChild, ChildLessResult<TEntity, TNewChild>>>();
    }
}

public class ResultWithResult<TEntity, TReturnValue, TChild>
{
}

As you can see this is pretty limited since it only allows you to go as deep as the structures you have defined and you would need a new structure for each level deeper. Is it possible to create types that would allow an unlimited number of levels (i.e. as many Selects as you would ever want without the same corresponding number of Types).

A: Yes, sort of.... it is possible to create some very long and deep nested types, more or less automatically. The trick is you need to use generic type inference, and since constructors don't do inference, you have to use a factory method. For example:
public class MyType<TData,TChild>
{
    public MyType(TData data, TChild child)
    {
    }
}

public class MyTypeFactory
{
   public static MyType<TData,TChild> Create<TData,TChild>(TData data, TChild child)
   {
      return new MyType<TData,TChild>(data, child);
   }

   public static MyType<TData,object> Create<TData>(TData data)
   {
      return new MyType<TData,object>(data, null);
   }
}

public static class Program
{
    static public void Main()
    {
        var grandchild  = MyTypeFactory.Create( 12 );
        var child       = MyTypeFactory.Create( 13D, grandchild );
        var parent      = MyTypeFactory.Create( 14M, child) ;
        var grandparent = MyTypeFactory.Create( 15F, parent );

        Console.WriteLine(  grandchild.GetType().FullName );
        Console.WriteLine(       child.GetType().FullName );
        Console.WriteLine(      parent.GetType().FullName );
        Console.WriteLine( grandparent.GetType().FullName );
    }
}

The output:

MyType'2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
MyType'2[[System.Double, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[MyType'2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], uy2zelya, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]
MyType'2[[System.Decimal, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[MyType'2[[System.Double, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[MyType'2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], uy2zelya, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]], uy2zelya, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]
MyType'2[[System.Single, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[MyType'2[[System.Decimal, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[MyType'2[[System.Double, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[MyType'2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], uy2zelya, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]], uy2zelya, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]], uy2zelya, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]

It's even type-safe, amazingly enough. If you add the necessary properties...
public class MyType<TData,TChild>
{
    protected readonly TChild _child;
    protected readonly TData _data;

    public MyType(TData data, TChild child)
    {
        _data = data;
        _child = child;
    }

    public TChild Child
    {
        get
        {
            return _child;
        }
    }

    public TData Data
    {
        get
        {
            return _data;
        }
    }
}

...this will work:
var grandchildValue = grandparent.Child.Child.Child.Data;
Console.WriteLine(grandchildValue); //12
Console.WriteLine(grandchildValue.GetType().Name); //int32

And of course you can use the builder pattern:
public static class ExtensionMethods
{
    static public MyType<TDataAdd,MyType<TDataIn,TResultIn>> AddColumn<TDataIn,TResultIn,TDataAdd>(this MyType<TDataIn,TResultIn> This, TDataAdd columnValue)
    {
        return MyTypeFactory.Create(columnValue, This);
    }
}

var grandparent = MyTypeFactory.Create( 12 )
    .AddColumn( 13D )
    .AddColumn( 14M )
    .AddColumn( 15F );

var grandchildValue = grandparent.Child.Child.Child.Data;
Console.WriteLine(grandchildValue);                       //12
Console.WriteLine(grandchildValue.GetType().FullName);    //System.Int32

See my code on DotNetFiddle
P.S. This is a great example of why we needed the var keyword! Otherwise you'd be typing forever.


Q: Can declaring POD types throw an exception? When I declare a condition_variable, it may throw std::system_error.
But how about when I declare a POD type (e.g. int, double or float)?
Like the code below:
int main()
{
    //do something
    int i;    //will here throw exception?
}

If declaring a POD type may throw exception, how do I guarantee
void test() noexcept
{
    //do something
    int i;
}

is noexcept?

A:
But how about declare a fundamental type (e.g., int, double or float)?

Declaring POD type objects won't cause an exception to be thrown.
Constructors of non-POD types can throw exceptions. Only the documents/source code of those types can help you figure out whether that will happen for a particular type.

A: It is the constructor of std::condition_variable that can throw an exception. Primitive types like int and double do not have any constructors. They simply have some stack space allocated for them and that's it, plus a value being written if you initialize the variable. The only way this could cause an exception is if you overflow the stack and the ensuing undefined behaviour happens to throw one.

A: POD types typically are initialized with initializer expressions instead of constructors. Like constructors, initializers can throw exceptions. But if you have neither a constructor nor an initializer, there's no code associated with the definition and therefore also no possibility for that code to throw.


Q: SQL query to replace multiple occurrences with the most frequent ones I have a products table, which has the product description in two languages, one in English and one in an alternate language.
Let's say:

Product_Desc
Product_Desc_Alt

A
A1

A
A2

A
A1

A
A3

B
B1

B
B2

B
B2

C
C1

If I do a GROUP BY statement, there are multiple alternate language occurrences for the same product. So, let's say:
SELECT Product_Desc, COUNT(DISTINCT Product_Desc_Alt) AS CNT
FROM products
GROUP BY Product_Desc
ORDER BY CNT DESC

Product_Desc
CNT

A
3

B
2

C
1

I would like to replace the Product_Desc_Alt occurrences with the most frequent ones,
so for example I would like the output to be:

Product_Desc
Product_Desc_Alt

A
A1

A
A1

A
A1

A
A1

B
B2

B
B2

B
B2

C
C1

Obviously, if a product has only one alter lang description, just keep that one.
There may be lots of ways to do that, but I can't think of one.
I am using Azure Databricks so this could also happen with PySpark, but I am interested in doing this the SQL way.
Thanks a lot!

A: Is this what you mean?
UPDATE products
SET Product_Desc_Alt = (
  SELECT TOP 1 Product_Desc_Alt
  FROM   products P2
  WHERE  P2.Product_Desc = products.Product_Desc
  GROUP BY Product_Desc_Alt
  ORDER BY COUNT(*) DESC
)


Q: How to get text wrapped with  I wanted to get the text inside break html but this it's not wrap with paragraph just a text inside break. Division is my only identifier for this which is "Msg". How can I get one of each element?

       HI!

         2017-11-30-15.28.09.133

         123

         abc

       Your number is 5.

Draft:
HtmlElement msg = (HtmlElement) page.getFirstByXPath("//div[@name='Msg']/text()");
System.err.println(msg.getTextContent());

A: Understood correctly you might want the code output as

Your number is 5.

  123

  123

  HI!2017-11-30-15.28.09.133

Maybe you might want to try with StringTokenizer (the codes below will hit java.util.NoSuchElementException as the nextToken() call is forced, but hopefully it will become a general idea)
import java.util.StringTokenizer;
..
String sampleStr= "Hello
 there
";
StringTokenizer token = new StringTokenizer(sampleStr);
System.out.println(token.nextToken());//You can use .trim()
System.out.println(token.nextToken());

Would this help?


Q: How to save media file in app specific folder using Media Store API - Scoped Storage Android I am trying to use scoped storage for Android 10 and above to save images taken from the camera in the app specific folder.
I know how to do it using File API but I am looking for to do it with Media store API.
Here is the issue, using the below code it saves images in Internal storage > Pictures, but doesn't save it in app specific folder. Hence if I uninstall the app, the images saved by the app still remains in the memory. I want them to get deleted automatically if user removes the app from his phone.
Let me know if I am doing it wrong or missing something.
    private void dispatchTakePictureIntent() throws IOException {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            if (!checkIfVersionCodeQAndAbove()) {
                try {
                    photoFile = createImageFile();
                } catch (IOException ex) {
                    // Error occurred while creating the File
                    return;
                }
                // Continue only if the File was successfully created
                if (photoFile != null) {
                    Uri photoURI = FileProvider.getUriForFile(getActivity().getApplicationContext(), getActivity().getPackageName() + ".provider", createImageFile());
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                }
            }
            if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
                startActivityForResult(takePictureIntent, TAKE_PICTURE);
            }
        }
    }

private void storeImageUsingMediaApi(Intent data) {
        if (getActivity()!=null) {
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
            String imageFileName = "JPEG_" + timeStamp + "_";

            ContentValues contentValues = new ContentValues();
            contentValues.put(MediaStore.Images.Media.TITLE, imageFileName + ".jpg");
            contentValues.put(MediaStore.Images.Media.DESCRIPTION, "profile_image");
            contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES  + File.separator + "MyApp");

            ContentResolver resolver = getActivity().getContentResolver();

            OutputStream stream = null;
            Uri uri = null;
            try {
                Bundle extras = data.getExtras();
                Bitmap bitmap = null;
                if (extras != null) {
                    bitmap = (Bitmap) extras.get("data");
                }

                final Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                uri = resolver.insert(contentUri, contentValues);

                if (uri == null) {
                    throw new IOException("Failed to create new MediaStore record.");
                }

                stream = resolver.openOutputStream(uri);

                if (stream == null) {
                    throw new IOException("Failed to get output stream.");
                }

                if (bitmap!=null && !bitmap.compress(Bitmap.CompressFormat.JPEG, 95, stream)) {
                    throw new IOException("Failed to save bitmap.");
                }

                stream.close();

                selctedImageUri = String.valueOf(uri);

                Glide.with(getActivity()).load(uri).into(imageProfile);

            } catch (IOException e) {
                if (uri != null) {
                    // Don't leave an orphan entry in the MediaStore
                    resolver.delete(uri, null, null);
                }
                e.printStackTrace();
            }
        }
    }

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        CgUtils.showLog(getTag(), "frag onActivityResult");

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == TAKE_PICTURE) {
                CgUtils.showLog(getTag(), "frag TAKE_PICTURE");

                if (checkIfVersionCodeQAndAbove()) {
                    storeImageUsingMediaApi(data);
                } else {
                    Uri imageUri = Uri.parse(selctedImageUri);
                    if (imageUri.getPath() != null) {
                        File file = new File(imageUri.getPath());
                        try {
                            InputStream ims = new FileInputStream(file);
                            imageProfile.setImageBitmap(BitmapFactory.decodeStream(ims));
                        } catch (FileNotFoundException e) {
                            CgUtils.showLog(TAG, "error " + e.toString());
                        }
                    }
                }
                if (!selctedImageUri.isEmpty()) {
                    if (null != loginResponse)
                        loginResponse.setImageUri(selctedImageUri);
                    new InsertLoginResponse(getActivity(), loginResponse, false).executeOnExecutor(CgUtils.getExecutorType());

                    sharedPreferencesEditor.putString(CgConstants.USER_PROF_PIC, selctedImageUri);
                    sharedPreferencesEditor.commit();
                }
            }
      }
}


Q: Auto dial out issue in asterisk I am applying an auto dial in asterisk using .call file
My a.call
Channel: DAHDI/g0/09*********
MaxRetries: 1
RetryTime: 600
WaitTime: 30
Context: outgoing
Extension: 10
Priority: 1

My problem is that every time above number is called by same number means  even if i change the dialled number(receiver number above) the caller number is same.How can i set the caller number in an outgoing call?
Thanks in advance.

A: You can use
Channel: DAHDI/g0/09*********
MaxRetries: 1
RetryTime: 600
WaitTime: 30
Context: outgoing
Extension: 10
Priority: 1
Callerid: 12345

Note, dahdi g0 have be digital trunk and ALLOW change of callerid.

A: You just add the parameter on your .call file
Callerid: <your_callerid>


Q: Fetching cached image not working I was trying to load and cache images in my app for showing on UITableView.
The original concepts looks like:
if (image in cache){
    show cached image;
}else{
   if (image in file){
     show filed image;
   }else{
      load image from web asynchronously;
      if (finished){
         store in cache;
         store in file;
      }
   }
}

Here's the whole class I created to handle image storage:
ImageStore.h
@interface ImageStore : NSObject

@property (nonatomic, strong) NSCache *imageCache;

+ (ImageStore*)sharedImageStore;
//cache
- (void)writeImage: (UIImage*)image ToCacheForKey: (NSString*)imageURL;
- (UIImage*)readImageFromCacheForKey: (NSString*)imageURL;
- (BOOL)imageCachedForKey: (NSString*)imageURL;
//file
- (BOOL)writeImage: (UIImage*)image ToPlistFileForKey: (NSString*)imageURL;
- (UIImage*)readImageFromPlistFileForKey: (NSString*)imageURL;
- (BOOL)imageFiledInPlistForKey: (NSString*)imageURL;
@end

ImageStore.m
#import "ImageStore.h"

@implementation ImageStore
static ImageStore* sharedImageStore;
NSMutableDictionary* plistDictioary;

+(ImageStore*)sharedImageStore
{
    if (sharedImageStore == nil){
        sharedImageStore= [[self alloc] init];
    }
    return sharedImageStore;

}

+(id)alloc
{
    {
        NSAssert(sharedImageStore == nil, @"second singleton");
        sharedImageStore = [super alloc];

        return sharedImageStore;
    }

    return nil;
}

-(id)init
{
    self = [super init];
    if (self != nil)
    {
        _imageCache = [[NSCache alloc] init];
    }

    return self;
}

#pragma mark - Cache
- (void)writeImage:(UIImage *)image ToCacheForKey:(NSString *)imageURL{

    if(image != nil){
        [_imageCache setObject:image forKey:imageURL];
    }else{
        NSLog(@"NIL image:%@ ",imageURL);
    }
}

- (UIImage *)readImageFromCacheForKey:(NSString *)imageURL{

    return [_imageCache objectForKey:imageURL];
}

- (BOOL)imageCachedForKey:(NSString *)imageURL{

    if ([_imageCache objectForKey:imageURL] == nil)
    {
        return false;
    }

    return true;

}

#pragma mark - File
- (BOOL)writeImage:(UIImage*)image ToPlistFileForKey: (NSString*)imageURL{

    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:image];
    if (plistDictioary == nil) {
        plistDictioary = [NSMutableDictionary new];
    }
    [plistDictioary setObject:data forKey:imageURL];

    BOOL didWriteSuccessfull = [plistDictioary writeToFile:[self getPlistFilePath] atomically:YES];
    return didWriteSuccessfull;

}

- (UIImage *)readImageFromPlistFileForKey:(NSString *)imageURL{

    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:[self getPlistFilePath]];
    NSData * data = [dict objectForKey:imageURL];
    UIImage * image = [UIImage imageWithData:data];
    return image;

}

- (BOOL)imageFiledInPlistForKey:(NSString *)imageURL{

    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:[self getPlistFilePath]];
    if ([dict objectForKey:imageURL] == nil) {

        return NO;
    }else{

        return YES;
    }

}

- (NSString*)getPlistFilePath{

    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * documentsDirectory = [paths objectAtIndex:0];
    NSString * path = [documentsDirectory stringByAppendingPathComponent:@"Images.plist"];
    return path;
}
@end

Implementation in tableView:cellForRowAtIndex:
if ([[ImageStore sharedImageStore]imageCachedForKey:[[dataArray objectAtIndex:indexPath.row] objectForKey:@"image"]]) {
  //cache
  NSLog(@"cached");

  cell.image = [[ImageStore sharedImageStore] readImageFromCacheForKey:[[dataArray objectAtIndex:indexPath.row] objectForKey:@"image"]];

}else{

  NSLog(@"nothing cached");

  if ([[ImageStore sharedImageStore] imageFiledInPlistForKey:[[dataArray objectAtIndex:indexPath.row] objectForKey:@"image"]]) {
     //plist file

     cell.image = [[ImageStore sharedImageStore] readImageFromPlistFileForKey:[[dataArray objectAtIndex:indexPath.row] objectForKey:@"image"]];
  }else{
     //loading with UIImage category async method (see below)

     [UIImage loadFromURL:[NSURL URLWithString:[[dataArray objectAtIndex:indexPath.row] objectForKey:@"image"]] completionBlock:^(BOOL succeeded, UIImage *image) {

            if (succeeded){
                cell.image = image;
            }
        }];
    }
}

EDIT
Downloaded Images stored in the UIImage Category:
+ (void)loadFromURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, UIImage *image))completionBlock
{

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                               if ( !error )
                               {
                                   UIImage *image = [[UIImage alloc] initWithData:data];
                                   [[ImageStore sharedImageStore] writeImage:image ToCacheForKey:[url absoluteString]];//write to NSCache
                                   [[ImageStore sharedImageStore] writeImage:image ToPlistFileForKey:[url absoluteString]];//write to Plist
                                   completionBlock(YES,image);

                               } else{

                                   completionBlock(NO,nil);
                               }
                           }];

}

(Sorry for the long method naming.)
The console returns "nothing cached" for every onscreen cell, and sometimes the scrolling become stutter when checking cache and file.
I've been trying handy caching for a couple of days while there's already a bunch of useful image caching library. It'd be nice to know what am I doing wrong with this! Thanks for any advice.

A: The problem is in the writeImage:ToPlistFileForKey: method. You convert an image to a data as below:
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:image];

But convert the data to image like this:
UIImage * image = [UIImage imageWithData:data];

This will always return a nil that because the format of the archived data is NSPropertyListBinaryFormat_v1_0 not PNG(or bitmap format).
Instead of using [NSKeyedArchiver archivedDataWithRootObject:image], you should use UIImagePNGRepresentation(image) as below:
- (BOOL)writeImage:(UIImage*)image ToPlistFileForKey: (NSString*)imageURL {
    archivedDataWithRootObject:image];
    NSData *data = UIImagePNGRepresentation(image);
    if (plistDictioary == nil) {
        plistDictioary = [NSMutableDictionary new];
    }
    [plistDictioary setObject:data forKey:imageURL];

    BOOL didWriteSuccessfull = [plistDictioary writeToFile:[self getPlistFilePath] atomically:YES];
    return didWriteSuccessfull;
}

The UIImagePNGRepresentation function which returns the data for the specified image in PNG format, then you get an image [UIImage imageWithData:data].
Hope this will help you.


Q: PHP stream_context_create with proxy I'm currently developing an web application which uses an XML Interface located on a different server, that I have to access via a proxy.
So I tried to set the proxy in a stream_context_create array, but it doesn't seem to work.
$set = array(
    'http' => array(
        'method' => 'GET',
        'header' => sprintf(
            'Proxy-Authorization: Basic %s',
            base64_encode(Constants::XML_AUTH)
        ),
        'protocol_version' => '1.1',
        'proxy' => '89.122.180.178:46565'
    )
);
$stream = stream_context_create($set);

I'm not quite sure what I'm doing wrong.
If I comment out the proxy key i get a 403 Forbidden Response as it should be.
If I comment in the proxy key I receive a 400 Bad Request Response.
I'm not quite sure what I'm doing wrong. Can you help me out? I never did a communication through a proxy before with PHP.

A: My guess is that the proxy declaration is missing the protocol. An URI has to be specified (according to the doc), that contains the protocol (scheme).
So this could work: 'proxy' => 'tcp://89.122.180.178:46565'. It might be necessary to remove 'protocol_version' since this may not be required for tcp.
Does that work for you? (or have you already solved it? ... ;-)


Q: Want to multiply, not repeat variable I want to input a command-line variable and then multiply it, but when I print the variable it repeats by the number I want to multiply it by.
eg:
#!/usr/bin/env python3
import sys
st_run_time_1 = sys.argv[1]*60

print ("Station 1 : %s" % st_run_time_1)

When I run the script I get the following:
    python3 test.py 2
Station 1 : 222222222222222222222222222222222222222222222222222222222222

A: sys.argv[x] is string. Multiplying string by number casue that string repeated.
>>> '2' * 5         # str * int
'22222'

>>> int('2') * 5    # int * int
10

To get multiplied number, first convert sys.argv[1] to numeric object using int or float, ....
import sys
st_run_time_1 = int(sys.argv[1]) * 60 # <---

print ("Station 1 : %s" % st_run_time_1)

A: You are multiplying a string with an integer, and that always means repetition. Python won't ever auto-coerce a string to an integer, and sys.argv is always a list of strings.
If you wanted integer arithmetic, convert the sys.argv[1] string to an integer first:
st_run_time_1 = int(sys.argv[1]) * 60


Q: NotificationHub Push Notification returns : The Token obtained from the Token Provider is wrong I have Wp8.1 Silverlight app that receives push notification (WNS) from  Mobileservice (the old azure service).
I therefore wanted to update to the new service because of the new features. I have now created/upgraded a new server to use App Service - Mobile App. And tested push notification with the sample app from azure (everything works).
Going back to my app WP8.1 -> Adding the new package Microsoft.Azure.Mobile.Client through NuGet (2.0.1), there is the issue that the Microsoft.WindowsAzure.Mobile.Ext does not contain the 'GetPush' extension. It seems like it is missing it? looking to the WP8 version, it only registers to MPNS, and I need WNS. So I do not know if any other assembly could be used.
Can I add another assembly reference?
Update
The following code lets me register the device on the server, and I can see the device register correctly. where the channelUri and the installationInformation are retrieved by the client and send to the server.
Installation ins = new Installation();
ins.Platform = NotificationPlatform.Wns;
ins.PushChannel = uTagAndChan.ChannelUri;
ins.Tags = uTagAndChan.Tags;
ins.InstallationId = uTagAndChan.installationInformation;
await hubClient.CreateOrUpdateInstallationAsync(ins);

Sending a test toast-notification to the registered tags, results in the following error :

The Token obtained from the Token Provider is wrong

Searching on this issue I found Windows Store App Push Notifications via Azure Service Bus. Which the proposed solution says to register to the notification hub directly from the app, I would rather not have the app to have directly access to the hub. But is this the only way? (mind you the answer was not accepted, but I will try it all though it is not a desired solution)
Update
Registering  for notifications via client (WP8.1 Silverligt), makes a registration to MPNS, which I do not want.
The snippet on the server registers a WNS, the two registrations can be seen here:

The URI retrieval is done using
var channel = await Windows.Networking.PushNotifications.PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();

which in the description states it returns a WNS. This seems to infer that the registration I am doing on the server (code snippet in the top) is correct and the registration on the client is faulty.
But the registration on the image seems wrong. Shouldn't the PNS Identifier be different for the two registrations? also expiration date seems wrong ?
How to mend this since the GetPush() (which was available in the sample registered the client correctly for notifications) does not exist in the NuGet package?
Update
I read one place that deleting and recreating the NotificationHub could help. I will try this today. Even IF it works, it would be more desirable to have the solution, and to know if the registrations are done correctly?
Temporary solution:
Deltede, recreated, inserted Package SID and Secret. And it works again (strange)!
Still interested in the underlying issue!

A: Deleted and recreated the service, setting all the same settings made it work again.

A: I had same issue with my UWP. But in my case I had issue with self signed certificate.
When I set the AppxPackageSigningEnabled property to True (in .csproj) then notifications stopped working and I got "The token obtained from the Token Provider is wrong" (Test send from Azure Portal).
The certificate must have same issuer as Publisher in Identity element in .appxmanifest file.


Q: How to turn users input into a list in Python? Here is my code so far.
def pfunc():
    portList = []
    user_choice_port = userPort.get()
    portList.append(user_choice_port)

the userPort is basically a text variable for what the user will enter into an entry box (which will be ports). The user will enter the port numbers like this:
23, 80, 44, etc.

How do I take those numbers and put them into a list. Cause whenever I do it puts them in as a string that looks like this:
['23, 80, 44']

When I want it to look like this:
[23,80,44]

I cannot figure this out so any help would be appreciated

A: This should help.
user_choice_port = "23, 80, 44"
print map(int, user_choice_port.split(","))
print [int(n) for n in user_choice_port.split(",")]


Q: Leads to implement cart in shopping cart using Spring
I have implemented shopping cart up to product. But have no idea on how to implement separate cart for each user.
Please share your ideas

A: Please share your effort / code along with your question always.
According to me this can go with many scenarios
One of the scenarios would be like,
User have One Cart, Cart will have many products and many Products belongs to many carts
Code goes as below, You can go ahead and add required parameters to the entity.
User Entity
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name = "USERS")
public class User {

    @Id
    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "USER_NAME")
    private String userName;

    @OneToOne(mappedBy = "user", fetch = FetchType.LAZY)
    private Cart cart;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Cart getCart() {
        return cart;
    }

    public void setCart(Cart cart) {
        this.cart = cart;
    }

}

Cart Entity
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name = "CART")
public class Cart {

    @Id
    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = "USER_ID")
    private User user;

    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinTable(name = "CART_PRODUCT", joinColumns = @JoinColumn(name = "CART_ID") , inverseJoinColumns = @JoinColumn(name = "PRODUCT_ID") )
    private Set<Product> products;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Set<Product> getProducts() {
        return products;
    }

    public void setProducts(Set<Product> products) {
        this.products = products;
    }

}

Product Entity
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

@Entity
@Table(name = "PRODUCT")
public class Product {

    @Id
    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "name")
    private String productName;

    @ManyToMany(cascade = CascadeType.ALL, mappedBy = "products")
    private Set<Cart> carts;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getProductName() {
        return productName;
    }

    public void setProductName(String productName) {
        this.productName = productName;
    }

    public Set<Cart> getCarts() {
        return carts;
    }

    public void setCarts(Set<Cart> carts) {
        this.carts = carts;
    }

}


Q: Format to Currency using DisplayFor Html Helper I have page that will show some currency data.
I want to format the data with currency format but only using Display Template.
I have the following code:
 @foreach (var item in Model.Data)
{

    @Html.DisplayFor(modelItem => item.Name)
    @Html.DisplayFor(modelItem => item.Amount1)
    @Html.DisplayFor(modelItem => item.LName)
    @Html.DisplayFor(modelItem => item.Amount2)
    @Html.DisplayFor(modelItem => item.Amount3)

}

I have created a DisplayTemplate String.cshtml, since my datatype is string:
@model string

@{
    IFormatProvider formatProvider = new System.Globalization.CultureInfo("en-US");
    @Model.ToString("C",formatProvider)
}

But when I run it, I'm getting the error:

No overload for method 'ToString' takes 2 arguments

How can I display positive amount as $1000.00 and negative amount as ($1000.00) either using DisplayTemplate or string.Format("{0:C}")

A: The problem you're having is because you're trying to convert a string to a currency.  From MSDN:

The Currency ("C") Format Specifier
The "C" (or currency) format specifier converts a number to a string that represents a currency amount.

The .ToString(string format, IFormatProvider formatProvider) overload you're trying to use only exists for numeric types, which is why it's not compiling.
As an example to demonstrate this:
public class TestModel
{
    public decimal Amount { get; set; }
    public string StringAmount { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var model = new TestModel
        {
            Amount = 1.99M,
            StringAmount = "1.99"
        };

        IFormatProvider formatProvider = new CultureInfo("en-US");

        // Prints $1.99
        Console.WriteLine(model.Amount.ToString("C", formatProvider));

        // Prints 1.99
        Console.WriteLine(string.Format(formatProvider, "{0:C}", model.StringAmount));
    }
}

So you have a couple of choices:

*

*Convert your data to a numeric type in the template, and then format it.

*Store your data as a numeric type to begin with.

I believe 2 is the better option, because you're wanting to work with numeric data, so storing it as a string only adds complexity when it comes to calculating and formatting (as you can see here), as you're always going to have to perform conversions first.


Q: Spring's CachingConnectionFactory. Why do we need to close sessions although they are to be cached? I am trying to get my head around the Spring CachingConnectionFactory.
ActiveMQ documentation recommends when using JmsTemplate that a Spring CachingConnectionFactory or an ActiveMQ PooledConnectionFactory is used as the connection factory implementation.
I understand this because using the normal ConnectionFactory a connection is created, a session started, and both are closed for EVERY call of the jmsTemplate.send() which is very wasteful.
So I am trying to implement a custom JmsTemplate bean with a CachingConnectionFactory for use where I may have many requests that are A) Persisted to DB B) Enqueued JMS.
@Configuration
public class JMSConfig {

    @Autowired
    private CachingConnectionFactory cachingConnectionFactory;

    @Bean
    @Qualifier("jmsTemplateCached")
    public JmsTemplate jmsTemplateCachingConnectionFactory() {
        cachingConnectionFactory.setSessionCacheSize(10);

        JmsTemplate jmsTemplate = new JmsTemplate();
        jmsTemplate.setDeliveryMode(DeliveryMode.PERSISTENT);
        jmsTemplate.setSessionAcknowledgeMode(JmsProperties.AcknowledgeMode.CLIENT.getMode());
        jmsTemplate.setSessionTransacted(true);
        jmsTemplate.setDeliveryPersistent(true);
        jmsTemplate.setConnectionFactory(cachingConnectionFactory);
        return jmsTemplate;
    }
}

My first question regards the Spring Docs For CachngConnecionFactory which say:

SingleConnectionFactory subclass that adds Session caching as well MessageProducer caching. This ConnectionFactory also switches the "reconnectOnException" property to "true" by default, allowing for automatic recovery of the underlying Connection.
By default, only one single Session will be cached, with further requested Sessions being created and disposed on demand. Consider raising the "sessionCacheSize" value in case of a high-concurrency environment.

But then in bold:

NOTE: This ConnectionFactory requires explicit closing of all Sessions obtained from its shared Connection. This is the usual recommendation for native JMS access code anyway. However, with this ConnectionFactory, its use is mandatory in order to actually allow for Session reuse.

Does this mean I only need to close sessions if I create a connection "manually" via the template or my CachingConnectionFactory bean? In other words like:
    Connection connection = jmsTemplateCached.getConnectionFactory().createConnection();

    Session sess = connection.createSession(true, JmsProperties.AcknowledgeMode.CLIENT.getMode());

    MessageProducer producer = sess.createProducer(activeMQQueue);

    try {
        producer.send(activeMQQueue, new ActiveMQTextMessage());
        sess.commit();
    } catch (JMSException e) {
        sess.rollback();
    } finally {
        sess.close();
    }

If I use the template like below, should I close or not close the session?
    @Autowired
    public JmsTemplate jmsTemplateCached;

    @Transactional
    public InboundResponse peristAndEnqueueForProcessing(InboundForm  inboundForm) throws IrresolvableException, JsonProcessingException, JMSException {

    //Removed for clarity, an entity has been persisted and is then to be enqueued via JMS.

        log.debug("Queue For Processing : {}", persistedRequest);

        String serialisedMessage = objectMapper.writeValueAsString(persistedRequest);
        ActiveMQTextMessage activeMQTextMessage = new ActiveMQTextMessage();
        activeMQTextMessage.setText(serialisedMessage);

        //Will throw JMS Exception on failure
        Session sessionUsed = jmsTemplateCached.execute((session, messageProducer) -> {
            messageProducer.send(activeMQQueue, activeMQTextMessage);
            session.commit();
            return session;
        });

        return response;
    }

Secondly, if the above jmsTemplate.execute() throws an exception, what happens to the session? Will it rollback after x time?

A: The JmsTemplate reliably closes its resources after each operation (returning the session to the cache), including execute().
That comment is related to user code using sessions directly; the close operation is intercepted and used to return the session to the cache, instead of actually closing it. You MUST call close, otherwise the session will be orphaned.
Yes, the transaction will roll back (immediately) if its sessionTransacted is true.
You should NOT call commit - the template will do that when execute exits normally (if it is sessionTransacted).


Q: ASP.NET MVC With MEF integration I am following the same approach used in this link in my ASP.NET MVC 2 project and it is working fine.
All my pages are partial views (ascx). So I have created a class library in my solution as a plugin the same way done in the link sample and put a new partial view and a controller that is called from the host application using MEF the same way also and it worked fine.
The difference in my plugin project is that I created a new folder to put my models in.
This code below represent the partial view showing as a plugin view in my host application through MEF successfully
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>

Hello I am a Plugin Partial View

But since I have added a model in my application models folder, I need to bind it to the partial view the same way done in my host ASP.NET MVC 2 host project.
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Plugin.Models.ViewModel>" %>

Hello I am a Plugin Partial View

Once adding the ViewModel to the partial view an error shows in firebug and my view is not loading anymore. The error in http response showing in firebug looks as follows:
<!DOCTYPE html>

<title>Parser Error</title>
<meta name="viewport" content="width=device-width" />

Server Error in '/' Application.

 Parser Error

         Description: An error occurred during the parsing of a resource required to service this request.   Please review the following specific parse error details and modify your source file appropriately.

         Parser Error Message: Could not load type 'System.Web.Mvc.ViewUserControl<Plugin.Models.ViewModel>'.

        Source Error:

Line 11: --%>
Line 12:
Line 13: <%@ Control Language="C#"     Inherits="System.Web.Mvc.ViewUserControl<Plugin.Models.ViewModel>" %>
Line 14:
Line 15:

         Source File:  /Modules/Message/Views/Message/PartialView.ascx    Line:  13

        Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18010

I have also copied the web.config file and added the model namespace as following:
<system.web>
  <pages>
    <namespaces>
      <add namespace='Plugin.Models.ViewModel' />
    </namespaces>
  </pages>
</system.web>

But this is not working either.

A: See Tom Clarkson answer on
Views in separate assemblies in ASP.NET MVC


Q: datetime field won't update in MySQL Database Hi I am having an issue with updating a users last login time in my database, if I set it to update a different column it works perfectly, but it just does not work when i try to update the specific column "lastlogin".
My code:
    @mysql_query("UPDATE my_users SET lastlogin=NOW() WHERE id=".$_SESSION["id"]);

My DB column:

column name: lastlogin

type: datetime

Null: No

Default: 0000-00-00 00:00:00

Anything wrong with the way the column is setup in the DB? Like I mentioned above if I was to tell it to put NOW() in another column it works fine.

A: Solved. There was another similar statement further down which was over riding this one! How stupid of me but easy to miss!

A: use mysql_error to try and find what is wrong, then post that into here so we can help if you need it. (Would comment but to low rep)

A: From my experience in the past, mysql_query() doesn't necessarily substitute variables before executing sql. Try writing in this format. Also use mysql_error to check if there are any issues with your code execution:
$sql = "UPDATE my_users SET lastlogin=NOW() WHERE id=".$_SESSION["id"];
mysql_query($sql) or die(mysql_error());

If there is no error, then there are few possibilities as to why the laslogin entry is not happening:

*

*$_SESSION["id"] does not hold any value and no value is being passed to mysql.

*There is no id matching with $_SESSION["id"].

To debug:

*

*Also try updating some other columns.

*You might also want to check if you are using correct extensions like PDO..

Also found that, earlier version of mysql doesn't support updating datetime column with now(). In that case try resetting column type to TIMESTAMP. Refer this for details: https://bugs.mysql.com/bug.php?id=27645


Q: How can I model association between two polymorphic classes without using an enumeration I am using an enum to label two different classes of products - a SensorDevice and a [data]CaptureDevice.
They are intended to be used physically plugged to one another, but not every sensor model can be used by each receiver model, so I created an Enum for the different platforms, so the GUI would only display the compatible accessories for a given device:
enum Platform {
    Standard,
    Deluxe,
    Jumbo
}

abstract class CaptureDevice
{
    public Platform platform;

    public bool IsCompatibleWith(SensorDevice sd)
    {
        return sd.Platforms.Contains(this.Platform); // <- this is type-checking!
    }
}

abstract class SensorDevice
{
    public IEnumerable<Platform> Platforms;

    public bool IsCompatibleWith(CaptureDevice cd)
    {
        return this.Platforms.Contains(cd.Platform); // <- this is type-checking!
    }
}

I started to find this quite smelly, since the enum is hard-coded. I am considering to use "Replace Type Code by Polymorphism" refactor, but I am not quite sure how to do it for this situation. Any suggestion?

A: You could do the following to get rid of enum.
Replace enum with a class.
public abstract class Platform {}

Add Device class which answers if it's compatible with a Platform.
public abstract class Device
{
    public abstract bool IsCompatibleWith(Platform platform);
}

Make CaptureDevice a subclass of Device.
public abstract class CaptureDevice : Device
{
    public Platform Platform;

    public override bool IsCompatibleWith(Platform platform)
    {
        // I'm using type comparison for the sake of simplicity,
        // but you can implement different business rules in here.

        return this.Platform.GetType() == platform.GetType();
    }

    public bool IsCompatibleWith(SensorDevice sd)
    {
       // We are compatible if sensor is compatible with my platform.

        return sd.IsCompatibleWith(this.Platform);
    }
}

Make SensorDevice a subclass of Device.
public abstract class SensorDevice : Device
{
    public IEnumerable<Platform> Platforms;

    public override bool IsCompatibleWith(Platform platform)
    {
        // I'm using type comparison again.

        return this.Platforms.Any(p => p.GetType() == platform.GetType());
    }

    public bool IsCompatibleWith(CaptureDevice cd)
    {
        // We are compatible if capture is compatible with one of my platforms.

        return this.Platforms.Any(p => cd.IsCompatibleWith(p));
    }
}

Basically, that's all you need to do. To illustrate how it works, I've added the code below.
// Platforms
public class StandardPlatform : Platform { }
public class DeluxPlatform : Platform { }
public class JumboPlatform : Platform { }

// Capture device(s)
public class CD1 : CaptureDevice
{
    public CD1()
    {
        Platform = new StandardPlatform();
    }
}

// Sensor device(s)
public class SD1 : SensorDevice
{
    public SD1()
    {
        Platforms = new List<Platform>
        {
            new StandardPlatform(),
            new DeluxPlatform()
        };
    }
}

public class SD2 : SensorDevice
{
    public SD2()
    {
        Platforms = new List<Platform> {new JumboPlatform()};
    }
}

// Somewhere in the code...
var cd1 = new CD1();
var sd1 = new SD1();

Console.WriteLine(cd1.IsCompatibleWith(sd1)); // True
Console.WriteLine(sd1.IsCompatibleWith(cd1)); // True

var sd2 = new SD2();
Console.WriteLine(sd2.IsCompatibleWith(cd1)); // False
Console.WriteLine(cd1.IsCompatibleWith(sd2)); // False

A: EDIT: If you want to get rid off the enum, why shouldn't use a config file ?
You configure your platforms like this:
<Platforms>
    <Platform name="Standard">
        <Device>Namespace.of.your.Device.CaptureDevice</Device>
        <Device>Namespace.of.another.Device.AnotherDevice</Device>
    </Platform>
    <Platform name="Deluxe">
        <Device>Namespace.of.your.Device.CaptureDevice</Device>
    </Platform>
</Platforms>

Other syntax:
<Platforms>
    <Platform>
        <Name>Standard</Name>
        <Devices>
            <Device>Namespace.of.your.Device.CaptureDevice</Device>
            <Device>Namespace.of.another.Device.AnotherDevice</Device>
        <Devices>
    </Platform>
</Platforms>

Then, you have the same base structure, you could do something like this:
abstract class ADevice<T> where T : ADevice<T>
{
    public ADevice<T>(T device , string filename)
    {
        // Parsing of the file
        // Plus, setting the Platforms Property
    }

    // Or (but you should keep the first constructor to see the filename dependency)
    public ADevice<T>(T device)
    {
        // Parsing of the file
    }

    public IEnumerable<Platform> Platforms { get; private set; }

    public bool IsCompatibleWith(T device)
    {
        return this.Platforms.Contains(device.Platform); // <- this is type-checking!
    }
}

Then:
abstract class CaptureDevice : ADevice<CaptureDevice>
{
    public CaptureDevice(CaptureDevice device, string filename)
        : base(device, filename)
    {
    }

    // Or (But still same comment)
    public CaptureDevice(CaptureDevice device)
        : base(device, defaultFilename)
    {
    }
}

Same for SensorDevice
And instead of the Enum, you can create a simple class for the moment as:
public class Platform
{
    public Platform(string name)
    {
        Name = name;
    }

    public string Name { get; }
}